-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbuild.mjs
More file actions
221 lines (172 loc) · 4.35 KB
/
build.mjs
File metadata and controls
221 lines (172 loc) · 4.35 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { build } from 'esbuild'
import chokidar from 'chokidar'
import fg from 'fast-glob'
import fs from 'fs-extra'
import path from 'path'
import { exec } from 'child_process'
import { promisify } from 'util'
import crypto from 'crypto'
const sh = promisify(exec)
const ROOT = process.cwd()
const WORKERS_DIR = path.join(ROOT, 'workers')
const DIST_DIR = path.join(ROOT, 'dist/workers')
const WATCH = process.argv.includes('--watch')
/**
* 构建完成 Hook
* 可自定义:
* - wrangler deploy
* - zip打包
* - manifest生成
* - 通知其他服务
*/
async function runPostBuild(worker) {
console.log(`[hook] ${worker.name}`)
// 示例:
// await sh(`echo built ${workerName}`)
// 示例:自动部署某 worker
// if (workerName === 'base-worker') {
// await sh(`wrangler deploy --config ${outDir}/wrangler.toml`)
// }
await fillVersionHash(worker)
}
async function fillVersionHash(worker) {
const manifestPath = path.join(worker.outDir, 'manifest.json')
const files = await collectFiles(worker.outDir)
const hash = crypto.createHash('sha256')
for (const file of files.sort()) {
const rel = path.relative(worker.outDir, file)
// 避免 manifest 自身参与 hash
if (rel === 'manifest.json') continue
const content = await fs.readFile(file)
hash.update(rel)
hash.update('\0')
hash.update(content)
hash.update('\0')
}
const versionHash = hash.digest('hex')
let manifest = {}
try {
manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'))
} catch {
// manifest 不存在则自动创建
}
manifest.version_hash = versionHash
await fs.writeFile(
manifestPath,
JSON.stringify(manifest, null, 2) + '\n'
)
}
/**
* 递归收集目录下所有文件
*/
async function collectFiles(dir) {
const result = []
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
result.push(...await collectFiles(fullPath))
} else {
result.push(fullPath)
}
}
return result
}
/**
* 获取所有 worker
*/
async function getWorkers() {
const entries = await fg('workers/*/index.js')
return entries.map(entry => {
const workerName = path.basename(path.dirname(entry))
return {
name: workerName,
srcDir: path.join(WORKERS_DIR, workerName),
entry: path.resolve(entry),
outDir: path.join(DIST_DIR, workerName),
}
})
}
/**
* 拷贝静态资源
*/
async function copyAssets(worker) {
await fs.ensureDir(worker.outDir)
const files = await fs.readdir(worker.srcDir)
await Promise.all(
files
.filter(f => !f.endsWith('.js'))
.map(file =>
fs.copy(
path.join(worker.srcDir, file),
path.join(worker.outDir, file)
)
)
)
}
/**
* 构建单个 worker
*/
async function buildWorker(worker) {
console.log(`[build] ${worker.name}`)
await fs.ensureDir(worker.outDir)
await build({
entryPoints: [worker.entry],
outfile: path.join(worker.outDir, 'index.js'),
bundle: true,
format: 'esm',
minify: false, // To make the output code clearer
// sourcemap: true,
platform: 'browser',
target: 'es2022',
})
await copyAssets(worker)
await runPostBuild(worker)
console.log(`[done] ${worker.name}`)
}
/**
* 全量构建
*/
async function fullBuild() {
const workers = await getWorkers()
await Promise.all(workers.map(buildWorker))
}
/**
* Watch 模式
*/
async function watchMode() {
await fullBuild()
const watcher = chokidar.watch(WORKERS_DIR, {
ignoreInitial: true,
})
watcher.on('all', async (_, changedPath) => {
const rel = path.relative(ROOT, changedPath)
const parts = rel.split(path.sep)
if (parts[0] !== 'workers' || parts.length < 2) return
const workerName = parts[1]
const worker = {
name: workerName,
srcDir: path.join(WORKERS_DIR, workerName),
entry: path.join(WORKERS_DIR, workerName, 'index.js'),
outDir: path.join(DIST_DIR, workerName),
}
try {
await buildWorker(worker)
} catch (err) {
console.error(`[error] ${workerName}`, err.message)
}
})
console.log('[watching]')
}
/**
* 主流程
*/
async function main() {
await fs.emptyDir(DIST_DIR)
if (WATCH) {
await watchMode()
} else {
await fullBuild()
}
}
main()