-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
content-dump.ts
91 lines (79 loc) · 2.19 KB
/
content-dump.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import path from 'node:path'
import fs from 'graceful-fs'
import { existsSync } from './file-system'
import { CWD } from './constants'
let cacheDir: string
let assetDir: string
let cacheDirExist = false
const asset: { [locale: string]: any } = Object.create(null)
const cached = new Map<string, boolean>()
function initFromCache(filename: string) {
if (!cached.has(filename)) {
try {
const content = fs.readFileSync(path.join(assetDir, filename), 'utf8')
cached.set(filename, true)
return JSON.parse(content)
} catch {
cached.set(filename, false)
}
}
return {}
}
export function addPage({
locale,
route,
title,
structurizedData,
distDir
}: {
locale: string
route: string
title: string
structurizedData: any
distDir?: string
}): void {
if (!cacheDir || !assetDir) {
initConfig(distDir)
}
const dataFilename = `nextra-data-${locale}.json`
asset[locale] ||= initFromCache(dataFilename)
asset[locale][route] = {
title,
data: structurizedData
}
// To prevent race conditions, we temporarily use the sync method to flush.
// @TODO: introduce mutex lock, or only generate the asset when finishing the
// entire build.
const content = JSON.stringify(asset[locale])
fs.writeFileSync(path.join(assetDir, dataFilename), content)
fs.writeFileSync(path.join(cacheDir, dataFilename), content)
}
export function initConfig(distDir = '.next') {
cacheDir = path.join(CWD, distDir, 'cache')
assetDir = path.join(CWD, distDir, 'static', 'chunks')
}
// Copy cached data to the asset directory.
export function restoreCache(distDir?: string): void {
if (!cacheDir || !assetDir) {
initConfig(distDir)
if (!existsSync(assetDir)) {
fs.mkdirSync(assetDir, { recursive: true })
}
cacheDirExist = existsSync(cacheDir)
if (!cacheDirExist) {
fs.mkdirSync(cacheDir, { recursive: true })
}
}
if (!cacheDirExist) {
return
}
if (!existsSync(assetDir)) {
fs.mkdirSync(assetDir, { recursive: true })
}
const files = fs.readdirSync(cacheDir)
for (const file of files) {
if (file.startsWith('nextra-data-')) {
fs.copyFileSync(path.join(cacheDir, file), path.join(assetDir, file))
}
}
}