dsh-drawai 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +430 -418
  2. package/README.md +96 -249
  3. package/lib/audio-media.js +5 -2
  4. package/lib/client.js +45 -12
  5. package/lib/drawing-runner.js +6 -4
  6. package/lib/ffmpeg-manager.js +1056 -0
  7. package/lib/index.js +7719 -7396
  8. package/lib/motion/apply.js +4 -3
  9. package/lib/motion/asset-pack.js +394 -335
  10. package/lib/motion/assets.js +4 -3
  11. package/lib/motion/beats.js +3 -2
  12. package/lib/motion/collect.js +3 -1
  13. package/lib/motion/delivery.js +29 -1
  14. package/lib/motion/demo-assets-lock.js +10 -0
  15. package/lib/motion/ffmpeg.js +5 -4
  16. package/lib/motion/jobs.js +5 -1
  17. package/lib/motion/mgstyles/vendor/README.md +28 -0
  18. package/lib/motion/mgstyles/vendor/modules/d3/LICENSE +13 -0
  19. package/lib/motion/mgstyles/vendor/modules/d3/dist/d3.min.js +2 -0
  20. package/lib/motion/mgstyles/vendor/modules/opentype.js/LICENSE +20 -0
  21. package/lib/motion/mgstyles/vendor/modules/opentype.js/dist/opentype.mjs +14460 -0
  22. package/lib/motion/mgstyles/vendor/modules/simplex-noise/LICENSE +21 -0
  23. package/lib/motion/mgstyles/vendor/modules/simplex-noise/dist/esm/simplex-noise.js +466 -0
  24. package/lib/motion/mgstyles/vendor/modules/topojson-client/LICENSE +13 -0
  25. package/lib/motion/mgstyles/vendor/modules/topojson-client/dist/topojson-client.min.js +2 -0
  26. package/lib/motion/preview.js +13 -4
  27. package/lib/motion/render.js +179 -159
  28. package/lib/motion/runtime/package-lock.json +3058 -0
  29. package/lib/motion/runtime/package.json +16 -0
  30. package/lib/motion/style-frames.js +306 -268
  31. package/lib/motion/sync.js +214 -214
  32. package/lib/motion/video-runtime.js +192 -0
  33. package/lib/motion-capture.js +2 -1
  34. package/lib/motion-film-review.js +2 -2
  35. package/lib/motion-project.js +105 -79
  36. package/lib/motion-render-worker.js +174 -144
  37. package/lib/motion-vision.js +3 -2
  38. package/lib/routing/router.js +222 -211
  39. package/lib/routing/vendor/README.md +96 -96
  40. package/lib/routing/vendor/libavoid-routing.js +753 -753
  41. package/lib/routing/vendor/libavoid.min.js +59 -59
  42. package/lib/shotcard-reference.js +2 -2
  43. package/lib/style-kernel.js +16 -6
  44. package/lib/video-export.js +32 -20
  45. package/package.json +17 -12
@@ -1,335 +1,394 @@
1
- /**
2
- * 动效素材包(字体 + 素材库)的定位与按需下载。
3
- *
4
- * 背景:素材约 200MB,塞进 npm tarball 会让包变成 147MB(0.4.0 实测),既不合适
5
- * 也不好发。改成发到 GitHub Release,插件首次用到时下载一次、逐文件校验、落到
6
- * 用户目录(`~/.dsh/drawai-assets/<version>/`),之后离线可用。
7
- *
8
- * 解析顺序(第一个命中的赢):
9
- * 1. 环境变量 DRAWAI_ASSETS_DIR —— 测试与自定义安装位置
10
- * 2. 与代码同级(`lib/motion/` 或 `src/motion/`)—— 开发目录 / 源码安装
11
- * 3. 用户缓存目录 —— 下载下来的那一份
12
- *
13
- * 注意别和 `./assets.js` 搞混:那个管的是**工程里的**素材清单(capture/probe)。
14
- */
15
- import { spawn } from 'node:child_process'
16
- import { createHash } from 'node:crypto'
17
- import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
- import { homedir } from 'node:os'
19
- import { dirname, join } from 'node:path'
20
- import { fileURLToPath } from 'node:url'
21
- import { gunzipSync } from 'node:zlib'
22
-
23
- import { ASSETS_LOCK } from './asset-pack-lock.js'
24
-
25
- export const ASSETS_VERSION = ASSETS_LOCK.version
26
- export const ASSETS_FILE = ASSETS_LOCK.file
27
- export const ASSETS_REPO = 'fourzkw/dsh-drawai'
28
- export const ASSETS_TAG = `assets-${ASSETS_VERSION}`
29
- /** 默认走 GitHub Release;企业内网 / 镜像可用 DRAWAI_ASSETS_URL 指到自己的地址。 */
30
- export const ASSETS_URL = process.env.DRAWAI_ASSETS_URL || `https://github.com/${ASSETS_REPO}/releases/download/${ASSETS_TAG}/${ASSETS_FILE}`
31
- export const ASSETS_PAGE = `https://github.com/${ASSETS_REPO}/releases/tag/${ASSETS_TAG}`
32
-
33
- const SENTINELS = ['fonts/font-faces.json', 'media-library']
34
- const READY_FILE = '.ready.json'
35
-
36
- /** 素材缺失 / 下载失败时抛这个:带够用户能自己动手排查的信息。 */
37
- export class AssetPackError extends Error {
38
- constructor(message, detail = {}) {
39
- super(message)
40
- this.name = 'AssetPackError'
41
- this.code = detail.code || 'assets-unavailable'
42
- this.url = ASSETS_URL
43
- this.dir = detail.dir || cacheDir()
44
- this.cause = detail.cause
45
- }
46
- }
47
-
48
- export function cacheDir() {
49
- const custom = process.env.DRAWAI_ASSETS_DIR
50
- if (custom) return custom
51
- return join(homedir(), '.dsh', 'drawai-assets', ASSETS_VERSION)
52
- }
53
-
54
- function isReady(dir) {
55
- if (!dir) return false
56
- try {
57
- return SENTINELS.every((rel) => existsSync(join(dir, rel)))
58
- } catch {
59
- return false
60
- }
61
- }
62
-
63
- export function bundledDir() {
64
- try {
65
- return fileURLToPath(new URL('./', import.meta.url))
66
- } catch {
67
- return null
68
- }
69
- }
70
-
71
- /** 已经能用的素材根目录;没有就返回 null。同步、很便宜。 */
72
- export function assetsRoot() {
73
- const bundled = bundledDir()
74
- if (isReady(bundled)) return bundled
75
- const cache = cacheDir()
76
- if (isReady(cache)) return cache
77
- return null
78
- }
79
-
80
- /** 给状态展示用:不下载、只报告。 */
81
- export function assetsState() {
82
- const bundled = bundledDir()
83
- if (isReady(bundled)) return { ready: true, source: 'bundled', root: bundled, dir: cacheDir(), version: ASSETS_VERSION }
84
- const cache = cacheDir()
85
- if (isReady(cache)) return { ready: true, source: 'cache', root: cache, dir: cache, version: ASSETS_VERSION }
86
- return { ready: false, source: null, root: null, dir: cache, version: ASSETS_VERSION, url: ASSETS_URL }
87
- }
88
-
89
- function readManifest(root) {
90
- const file = join(root, 'manifest.json')
91
- if (!existsSync(file)) return null
92
- try {
93
- return JSON.parse(readFileSync(file, 'utf8'))
94
- } catch {
95
- return null
96
- }
97
- }
98
-
99
- function readTar(buf) {
100
- const entries = []
101
- let offset = 0
102
- while (offset + 512 <= buf.length) {
103
- const header = buf.subarray(offset, offset + 512)
104
- if (header.every((byte) => byte === 0)) break
105
- const raw = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/, '').trim()
106
- const prefix = raw(345, 155)
107
- const name = raw(0, 100)
108
- const size = parseInt(raw(124, 12) || '0', 8) || 0
109
- const flag = String.fromCharCode(header[156] || 48)
110
- const full = (prefix ? prefix + '/' + name : name).replace(/^\/+/, '')
111
- offset += 512
112
- const data = buf.subarray(offset, offset + size)
113
- offset += Math.ceil(size / 512) * 512
114
- if (flag === '5') continue
115
- if (!full) continue
116
- if (flag !== '0' && flag !== '\0' && flag !== '7') continue
117
- entries.push({ path: full, data })
118
- }
119
- return entries
120
- }
121
-
122
- function assertSafePath(rel) {
123
- if (!rel || rel.startsWith('/') || /^[a-zA-Z]:/.test(rel)) throw new Error('素材包里有非法路径:' + rel)
124
- if (rel.split('/').includes('..')) throw new Error('素材包里有越级路径:' + rel)
125
- }
126
-
127
- /**
128
- * Node 22 的 fetch 不认系统/环境代理(NODE_USE_ENV_PROXY 要 24+),
129
- * 国内直连 github.com 基本连不上。所以设了代理就走 curl(Win10+ / macOS / 主流 Linux 都自带),
130
- * 由它处理 CONNECT 隧道与重定向。
131
- */
132
- function proxyFromEnv() {
133
- const raw = process.env.HTTPS_PROXY || process.env.https_proxy
134
- || process.env.HTTP_PROXY || process.env.http_proxy
135
- || process.env.ALL_PROXY || process.env.all_proxy
136
- return raw && raw.trim() ? raw.trim() : ''
137
- }
138
-
139
- function hashFile(path) {
140
- return new Promise((resolve, reject) => {
141
- const hash = createHash('sha256')
142
- const stream = createReadStream(path)
143
- stream.on('data', (chunk) => hash.update(chunk))
144
- stream.on('end', () => resolve(hash.digest('hex')))
145
- stream.on('error', reject)
146
- })
147
- }
148
-
149
- function downloadCurl(url, dest, onProgress, proxy) {
150
- return new Promise((resolve, reject) => {
151
- const args = [
152
- '-L', '--fail', '--silent', '--show-error',
153
- '--connect-timeout', '20', '--retry', '2', '--retry-delay', '2',
154
- '-o', dest,
155
- ]
156
- if (proxy) args.push('--proxy', proxy)
157
- args.push(url)
158
- const child = spawn('curl', args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })
159
- let stderr = ''
160
- child.stderr.on('data', (chunk) => { if (stderr.length < 500) stderr += chunk.toString() })
161
- const timer = setInterval(() => {
162
- try { if (onProgress) onProgress(statSync(dest).size, 0) } catch { /* 还没建文件 */ }
163
- }, 2000)
164
- child.on('error', (err) => { clearInterval(timer); reject(err) })
165
- child.on('close', async (code) => {
166
- clearInterval(timer)
167
- if (code !== 0) return reject(new Error('curl 退出码 ' + code + (stderr ? ':' + stderr.trim() : '')))
168
- try {
169
- const bytes = statSync(dest).size
170
- resolve({ bytes, sha256: await hashFile(dest) })
171
- } catch (err) { reject(err) }
172
- })
173
- })
174
- }
175
-
176
- async function downloadFetch(url, dest, onProgress) {
177
- if (typeof fetch !== 'function') throw new AssetPackError('当前 Node 没有 fetch(需要 18+)', { code: 'no-fetch' })
178
- let res
179
- try {
180
- res = await fetch(url, { redirect: 'follow', headers: { 'user-agent': 'dsh-drawai-assets' } })
181
- } catch (err) {
182
- const wrapped = new Error(err?.message || String(err))
183
- wrapped.cause = err
184
- throw wrapped
185
- }
186
- if (!res.ok) throw new AssetPackError('下载失败:HTTP ' + res.status + '(' + url + ')', { code: 'http-' + res.status })
187
- const total = Number(res.headers.get('content-length') || 0)
188
- const hash = createHash('sha256')
189
- const out = createWriteStream(dest)
190
- let got = 0
191
- let lastTick = 0
192
- try {
193
- for await (const chunk of res.body) {
194
- hash.update(chunk)
195
- got += chunk.length
196
- if (!out.write(chunk)) await new Promise((resolve) => out.once('drain', resolve))
197
- const now = Date.now()
198
- if (onProgress && now - lastTick > 2000) {
199
- lastTick = now
200
- onProgress(got, total)
201
- }
202
- }
203
- } finally {
204
- await new Promise((resolve) => out.end(resolve))
205
- }
206
- return { bytes: got, sha256: hash.digest('hex') }
207
- }
208
-
209
- async function downloadTo(url, dest, onProgress) {
210
- const proxy = proxyFromEnv()
211
- try {
212
- return await downloadFetch(url, dest, onProgress)
213
- } catch (first) {
214
- if (!proxy) throw new AssetPackError('连不上 GitHub:' + (first?.message || first), { code: 'network', cause: first })
215
- try {
216
- return await downloadCurl(url, dest, onProgress, proxy)
217
- } catch (second) {
218
- const err = new AssetPackError('下载失败(直连与代理 ' + proxy + ' 都不通):' + (second?.message || second), { code: 'network', cause: second })
219
- err.directCause = first
220
- throw err
221
- }
222
- }
223
- }
224
-
225
- let inflight = null
226
-
227
- /**
228
- * 保证素材可用。已经可用时是一次同步检查、立刻返回。
229
- * @param {{onProgress?: (got:number,total:number)=>void, force?: boolean}} [opts]
230
- */
231
- export async function ensureAssets(opts = {}) {
232
- const ready = assetsRoot()
233
- if (ready && !opts.force) return { root: ready, source: 'existing', downloaded: false }
234
- if (inflight) return inflight
235
- inflight = (async () => {
236
- const dir = cacheDir()
237
- const tmp = `${dir}.tmp-${process.pid}-${Date.now()}`
238
- const archive = `${tmp}.tar.gz`
239
- try {
240
- mkdirSync(dirname(dir), { recursive: true })
241
- rmSync(tmp, { recursive: true, force: true })
242
- mkdirSync(tmp, { recursive: true })
243
- const { bytes, sha256 } = await downloadTo(ASSETS_URL, archive, opts.onProgress)
244
- if (ASSETS_LOCK.bytes && bytes !== ASSETS_LOCK.bytes) {
245
- throw new AssetPackError(`素材包大小不对(收到 ${bytes} 字节,应为 ${ASSETS_LOCK.bytes}),可能下载被截断了`, { code: 'size-mismatch' })
246
- }
247
- if (ASSETS_LOCK.sha256 && sha256 !== ASSETS_LOCK.sha256) {
248
- throw new AssetPackError('素材包校验失败(sha256 不匹配),请重试;反复失败请手动下载安装', { code: 'checksum' })
249
- }
250
- const entries = readTar(gunzipSync(readFileSync(archive)))
251
- const manifestEntry = entries.find((item) => item.path === 'manifest.json')
252
- const manifest = manifestEntry ? JSON.parse(manifestEntry.data.toString('utf8')) : null
253
- if (!manifest || !Array.isArray(manifest.files)) throw new AssetPackError('素材包里没有 manifest.json,无法校验', { code: 'no-manifest' })
254
- const expected = new Map(manifest.files.map((item) => [item.path, item.sha256]))
255
- let written = 0
256
- for (const entry of entries) {
257
- if (entry.path === 'manifest.json') continue
258
- assertSafePath(entry.path)
259
- const want = expected.get(entry.path)
260
- const got = createHash('sha256').update(entry.data).digest('hex')
261
- if (want && want !== got) throw new AssetPackError('素材包内容损坏:' + entry.path, { code: 'bad-file' })
262
- const target = join(tmp, entry.path)
263
- mkdirSync(dirname(target), { recursive: true })
264
- writeFileSync(target, entry.data)
265
- written += 1
266
- }
267
- writeFileSync(join(tmp, READY_FILE), JSON.stringify({
268
- version: ASSETS_VERSION, files: written, bytes, sha256, at: new Date().toISOString(),
269
- }, null, 2) + '\n', 'utf8')
270
- rmSync(dir, { recursive: true, force: true })
271
- renameSync(tmp, dir)
272
- return { root: dir, source: 'download', downloaded: true, files: written }
273
- } catch (err) {
274
- rmSync(tmp, { recursive: true, force: true })
275
- if (err instanceof AssetPackError) throw err
276
- throw new AssetPackError('素材包安装失败:' + (err?.message || err), { code: 'install', cause: err })
277
- } finally {
278
- rmSync(archive, { force: true })
279
- inflight = null
280
- }
281
- })()
282
- return inflight
283
- }
284
-
285
- /** 工具层用:拿到素材根目录,或者抛一条人能照着做的错误。 */
286
- export async function requireAssets({ onProgress } = {}) {
287
- try {
288
- const got = await ensureAssets({ onProgress })
289
- return got.root
290
- } catch (err) {
291
- const reason = err?.message || String(err)
292
- throw new AssetPackError(
293
- '动效素材包(字体 + 素材库,一次性约 ' + Math.round((ASSETS_LOCK.bytes || 0) / 1048576) + 'MB)还没准备好:' + reason + '\n'
294
- + '怎么处理:\n'
295
- + ' 1) 联网后重试一次刚才的操作,插件会自动下载并校验;\n'
296
- + ' 2) 或者手动下载 ' + ASSETS_URL + ' ,解压到 ' + cacheDir()
297
- + '(目录里应当直接看到 fonts/ 和 media-library/);\n'
298
- + ' 3) 走代理的话先设 HTTPS_PROXY 再重试。\n'
299
- + '在此之前,画布与图片相关功能不受影响,只有动效(字体/素材库)用不了。',
300
- { dir: cacheDir(), cause: err },
301
- )
302
- }
303
- }
304
-
305
- /** 媒体素材库根目录(没有素材时返回 null,不抛)。 */
306
- export function mediaLibraryRoot() {
307
- const root = assetsRoot()
308
- if (!root) return null
309
- const dir = join(root, 'media-library')
310
- return existsSync(dir) ? dir : null
311
- }
312
-
313
- /** 字体目录(没有素材时返回 null,不抛)。 */
314
- export function fontsDir() {
315
- const root = assetsRoot()
316
- if (!root) return null
317
- const dir = join(root, 'fonts')
318
- return existsSync(dir) ? dir : null
319
- }
320
-
321
- export function assetsSummary() {
322
- const state = assetsState()
323
- if (!state.ready) return { ready: false, version: ASSETS_VERSION, dir: state.dir, url: ASSETS_URL, page: ASSETS_PAGE }
324
- const manifest = readManifest(state.root) || {}
325
- return {
326
- ready: true,
327
- version: ASSETS_VERSION,
328
- source: state.source,
329
- root: state.root,
330
- files: manifest.counts?.files ?? null,
331
- bytes: manifest.counts?.bytes ?? null,
332
- url: ASSETS_URL,
333
- page: ASSETS_PAGE,
334
- }
335
- }
1
+ /**
2
+ * 动效素材包(字体 + 素材库)的定位与按需下载。
3
+ *
4
+ * 背景:素材约 200MB,塞进 npm tarball 会让包变成 147MB(0.4.0 实测),既不合适
5
+ * 也不好发。改成发到 GitHub Release,插件首次用到时下载一次、逐文件校验、落到
6
+ * 用户目录(`~/.dsh/drawai-assets/<version>/`),之后离线可用。
7
+ *
8
+ * 解析顺序(第一个命中的赢):
9
+ * 1. 环境变量 DRAWAI_ASSETS_DIR —— 测试与自定义安装位置
10
+ * 2. 与代码同级(`lib/motion/` 或 `src/motion/`)—— 开发目录 / 源码安装
11
+ * 3. 用户缓存目录 —— 下载下来的那一份
12
+ *
13
+ * 注意别和 `./assets.js` 搞混:那个管的是**工程里的**素材清单(capture/probe)。
14
+ */
15
+ import { spawn } from 'node:child_process'
16
+ import { createHash } from 'node:crypto'
17
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, join, resolve, sep } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { gunzipSync } from 'node:zlib'
22
+
23
+ import { ASSETS_LOCK } from './asset-pack-lock.js'
24
+ import { DEMO_ASSETS_LOCK } from './demo-assets-lock.js'
25
+
26
+ export const ASSETS_VERSION = ASSETS_LOCK.version
27
+ export const ASSETS_FILE = ASSETS_LOCK.file
28
+ export const ASSETS_REPO = 'fourzkw/dsh-drawai'
29
+ export const ASSETS_TAG = `assets-${ASSETS_VERSION}`
30
+ /** 默认走 GitHub Release;企业内网 / 镜像可用 DRAWAI_ASSETS_URL 指到自己的地址。 */
31
+ export const ASSETS_URL = process.env.DRAWAI_ASSETS_URL || `https://github.com/${ASSETS_REPO}/releases/download/${ASSETS_TAG}/${ASSETS_FILE}`
32
+ export const ASSETS_PAGE = `https://github.com/${ASSETS_REPO}/releases/tag/${ASSETS_TAG}`
33
+
34
+ /**
35
+ * 上游 demo 用的数据文件(现在只有 22-hud 的 land-50m.json)单独一个小包:
36
+ * 530KB,跟 200MB 的字体/素材库包分开,谁用到谁下载。
37
+ */
38
+ export const DEMO_ASSETS_VERSION = DEMO_ASSETS_LOCK.version
39
+ export const DEMO_ASSETS_FILE = DEMO_ASSETS_LOCK.file
40
+ export const DEMO_ASSETS_TAG = `demo-assets-${DEMO_ASSETS_VERSION}`
41
+ export const DEMO_ASSETS_URL = process.env.DRAWAI_DEMO_ASSETS_URL || `https://github.com/${ASSETS_REPO}/releases/download/${DEMO_ASSETS_TAG}/${DEMO_ASSETS_FILE}`
42
+ export const DEMO_ASSETS_PAGE = `https://github.com/${ASSETS_REPO}/releases/tag/${DEMO_ASSETS_TAG}`
43
+
44
+ const SENTINELS = ['fonts/font-faces.json', 'media-library']
45
+ const READY_FILE = '.ready.json'
46
+
47
+ /** 素材缺失 / 下载失败时抛这个:带够用户能自己动手排查的信息。 */
48
+ export class AssetPackError extends Error {
49
+ constructor(message, detail = {}) {
50
+ super(message)
51
+ this.name = 'AssetPackError'
52
+ this.code = detail.code || 'assets-unavailable'
53
+ this.url = detail.url || ASSETS_URL
54
+ this.dir = detail.dir || cacheDir()
55
+ this.cause = detail.cause
56
+ }
57
+ }
58
+
59
+ export function cacheDir() {
60
+ const custom = process.env.DRAWAI_ASSETS_DIR
61
+ if (custom) return custom
62
+ return join(homedir(), '.dsh', 'drawai-assets', ASSETS_VERSION)
63
+ }
64
+
65
+ function isReady(dir) {
66
+ if (!dir) return false
67
+ try {
68
+ return SENTINELS.every((rel) => existsSync(join(dir, rel)))
69
+ } catch {
70
+ return false
71
+ }
72
+ }
73
+
74
+ export function bundledDir() {
75
+ try {
76
+ return fileURLToPath(new URL('./', import.meta.url))
77
+ } catch {
78
+ return null
79
+ }
80
+ }
81
+
82
+ /** 已经能用的素材根目录;没有就返回 null。同步、很便宜。 */
83
+ export function assetsRoot() {
84
+ const bundled = bundledDir()
85
+ if (isReady(bundled)) return bundled
86
+ const cache = cacheDir()
87
+ if (isReady(cache)) return cache
88
+ return null
89
+ }
90
+
91
+ /** 给状态展示用:不下载、只报告。 */
92
+ export function assetsState() {
93
+ const bundled = bundledDir()
94
+ if (isReady(bundled)) return { ready: true, source: 'bundled', root: bundled, dir: cacheDir(), version: ASSETS_VERSION }
95
+ const cache = cacheDir()
96
+ if (isReady(cache)) return { ready: true, source: 'cache', root: cache, dir: cache, version: ASSETS_VERSION }
97
+ return { ready: false, source: null, root: null, dir: cache, version: ASSETS_VERSION, url: ASSETS_URL }
98
+ }
99
+
100
+ /** demo 数据包没有「随包一份」的形态,永远只落在用户缓存目录。 */
101
+ export function demoCacheDir() {
102
+ const custom = process.env.DRAWAI_DEMO_ASSETS_DIR
103
+ if (custom) return custom
104
+ return join(homedir(), '.dsh', 'drawai-assets', 'demo-' + DEMO_ASSETS_VERSION)
105
+ }
106
+
107
+ /** 已经落地的 demo 数据根目录;没有就返回 null。同步、很便宜。 */
108
+ export function demoAssetsRoot() {
109
+ const dir = demoCacheDir()
110
+ return existsSync(join(dir, READY_FILE)) ? dir : null
111
+ }
112
+
113
+ /** 素材根目录下的某个文件(带越界校验);没有就返回 null。 */
114
+ export function demoAssetsFile(relativePath) {
115
+ const root = demoAssetsRoot()
116
+ if (!root) return null
117
+ const base = resolve(root)
118
+ const file = resolve(join(base, relativePath))
119
+ if (file !== base && !file.startsWith(base + sep)) return null
120
+ return existsSync(file) ? file : null
121
+ }
122
+
123
+ function readManifest(root) {
124
+ const file = join(root, 'manifest.json')
125
+ if (!existsSync(file)) return null
126
+ try {
127
+ return JSON.parse(readFileSync(file, 'utf8'))
128
+ } catch {
129
+ return null
130
+ }
131
+ }
132
+
133
+ function readTar(buf) {
134
+ const entries = []
135
+ let offset = 0
136
+ while (offset + 512 <= buf.length) {
137
+ const header = buf.subarray(offset, offset + 512)
138
+ if (header.every((byte) => byte === 0)) break
139
+ const raw = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/, '').trim()
140
+ const prefix = raw(345, 155)
141
+ const name = raw(0, 100)
142
+ const size = parseInt(raw(124, 12) || '0', 8) || 0
143
+ const flag = String.fromCharCode(header[156] || 48)
144
+ const full = (prefix ? prefix + '/' + name : name).replace(/^\/+/, '')
145
+ offset += 512
146
+ const data = buf.subarray(offset, offset + size)
147
+ offset += Math.ceil(size / 512) * 512
148
+ if (flag === '5') continue
149
+ if (!full) continue
150
+ if (flag !== '0' && flag !== '\0' && flag !== '7') continue
151
+ entries.push({ path: full, data })
152
+ }
153
+ return entries
154
+ }
155
+
156
+ function assertSafePath(rel) {
157
+ if (!rel || rel.startsWith('/') || /^[a-zA-Z]:/.test(rel)) throw new Error('素材包里有非法路径:' + rel)
158
+ if (rel.split('/').includes('..')) throw new Error('素材包里有越级路径:' + rel)
159
+ }
160
+
161
+ /**
162
+ * Node 22 的 fetch 不认系统/环境代理(NODE_USE_ENV_PROXY 要 24+),
163
+ * 国内直连 github.com 基本连不上。所以设了代理就走 curl(Win10+ / macOS / 主流 Linux 都自带),
164
+ * 由它处理 CONNECT 隧道与重定向。
165
+ */
166
+ function proxyFromEnv() {
167
+ const raw = process.env.HTTPS_PROXY || process.env.https_proxy
168
+ || process.env.HTTP_PROXY || process.env.http_proxy
169
+ || process.env.ALL_PROXY || process.env.all_proxy
170
+ return raw && raw.trim() ? raw.trim() : ''
171
+ }
172
+
173
+ function hashFile(path) {
174
+ return new Promise((resolve, reject) => {
175
+ const hash = createHash('sha256')
176
+ const stream = createReadStream(path)
177
+ stream.on('data', (chunk) => hash.update(chunk))
178
+ stream.on('end', () => resolve(hash.digest('hex')))
179
+ stream.on('error', reject)
180
+ })
181
+ }
182
+
183
+ function downloadCurl(url, dest, onProgress, proxy) {
184
+ return new Promise((resolve, reject) => {
185
+ const args = [
186
+ '-L', '--fail', '--silent', '--show-error',
187
+ '--connect-timeout', '20', '--retry', '2', '--retry-delay', '2',
188
+ '-o', dest,
189
+ ]
190
+ if (proxy) args.push('--proxy', proxy)
191
+ args.push(url)
192
+ const child = spawn('curl', args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })
193
+ let stderr = ''
194
+ child.stderr.on('data', (chunk) => { if (stderr.length < 500) stderr += chunk.toString() })
195
+ const timer = setInterval(() => {
196
+ try { if (onProgress) onProgress(statSync(dest).size, 0) } catch { /* 还没建文件 */ }
197
+ }, 2000)
198
+ child.on('error', (err) => { clearInterval(timer); reject(err) })
199
+ child.on('close', async (code) => {
200
+ clearInterval(timer)
201
+ if (code !== 0) return reject(new Error('curl 退出码 ' + code + (stderr ? ':' + stderr.trim() : '')))
202
+ try {
203
+ const bytes = statSync(dest).size
204
+ resolve({ bytes, sha256: await hashFile(dest) })
205
+ } catch (err) { reject(err) }
206
+ })
207
+ })
208
+ }
209
+
210
+ async function downloadFetch(url, dest, onProgress) {
211
+ if (typeof fetch !== 'function') throw new AssetPackError('当前 Node 没有 fetch(需要 18+)', { code: 'no-fetch' })
212
+ let res
213
+ try {
214
+ res = await fetch(url, { redirect: 'follow', headers: { 'user-agent': 'dsh-drawai-assets' } })
215
+ } catch (err) {
216
+ const wrapped = new Error(err?.message || String(err))
217
+ wrapped.cause = err
218
+ throw wrapped
219
+ }
220
+ if (!res.ok) throw new AssetPackError('下载失败:HTTP ' + res.status + '(' + url + ')', { code: 'http-' + res.status })
221
+ const total = Number(res.headers.get('content-length') || 0)
222
+ const hash = createHash('sha256')
223
+ const out = createWriteStream(dest)
224
+ let got = 0
225
+ let lastTick = 0
226
+ try {
227
+ for await (const chunk of res.body) {
228
+ hash.update(chunk)
229
+ got += chunk.length
230
+ if (!out.write(chunk)) await new Promise((resolve) => out.once('drain', resolve))
231
+ const now = Date.now()
232
+ if (onProgress && now - lastTick > 2000) {
233
+ lastTick = now
234
+ onProgress(got, total)
235
+ }
236
+ }
237
+ } finally {
238
+ await new Promise((resolve) => out.end(resolve))
239
+ }
240
+ return { bytes: got, sha256: hash.digest('hex') }
241
+ }
242
+
243
+ async function downloadTo(url, dest, onProgress) {
244
+ const proxy = proxyFromEnv()
245
+ try {
246
+ return await downloadFetch(url, dest, onProgress)
247
+ } catch (first) {
248
+ if (!proxy) throw new AssetPackError('连不上 GitHub:' + (first?.message || first), { code: 'network', cause: first })
249
+ try {
250
+ return await downloadCurl(url, dest, onProgress, proxy)
251
+ } catch (second) {
252
+ const err = new AssetPackError('下载失败(直连与代理 ' + proxy + ' 都不通):' + (second?.message || second), { code: 'network', cause: second })
253
+ err.directCause = first
254
+ throw err
255
+ }
256
+ }
257
+ }
258
+
259
+ /**
260
+ * 下载并安装一个素材包。两个包(字体素材库 / demo 数据)共用这一段:
261
+ * 落地、大小与 sha256 校验、逐文件校验、写 ready 标记,失败时清干净临时目录。
262
+ */
263
+ async function installPack({ lock, url, dir, onProgress }) {
264
+ const tmp = `${dir}.tmp-${process.pid}-${Date.now()}`
265
+ const archive = `${tmp}.tar.gz`
266
+ try {
267
+ mkdirSync(dirname(dir), { recursive: true })
268
+ rmSync(tmp, { recursive: true, force: true })
269
+ mkdirSync(tmp, { recursive: true })
270
+ const { bytes, sha256 } = await downloadTo(url, archive, onProgress)
271
+ if (lock.bytes && bytes !== lock.bytes) {
272
+ throw new AssetPackError(`素材包大小不对(收到 ${bytes} 字节,应为 ${lock.bytes}),可能下载被截断了`, { code: 'size-mismatch', url, dir })
273
+ }
274
+ if (lock.sha256 && sha256 !== lock.sha256) {
275
+ throw new AssetPackError('素材包校验失败(sha256 不匹配),请重试;反复失败请手动下载安装', { code: 'checksum', url, dir })
276
+ }
277
+ const entries = readTar(gunzipSync(readFileSync(archive)))
278
+ const manifestEntry = entries.find((item) => item.path === 'manifest.json')
279
+ const manifest = manifestEntry ? JSON.parse(manifestEntry.data.toString('utf8')) : null
280
+ if (!manifest || !Array.isArray(manifest.files)) throw new AssetPackError('素材包里没有 manifest.json,无法校验', { code: 'no-manifest', url, dir })
281
+ const expected = new Map(manifest.files.map((item) => [item.path, item.sha256]))
282
+ let written = 0
283
+ for (const entry of entries) {
284
+ if (entry.path === 'manifest.json') continue
285
+ assertSafePath(entry.path)
286
+ const want = expected.get(entry.path)
287
+ const got = createHash('sha256').update(entry.data).digest('hex')
288
+ if (want && want !== got) throw new AssetPackError('素材包内容损坏:' + entry.path, { code: 'bad-file', url, dir })
289
+ const target = join(tmp, entry.path)
290
+ mkdirSync(dirname(target), { recursive: true })
291
+ writeFileSync(target, entry.data)
292
+ written += 1
293
+ }
294
+ writeFileSync(join(tmp, READY_FILE), JSON.stringify({
295
+ version: lock.version, files: written, bytes, sha256, at: new Date().toISOString(),
296
+ }, null, 2) + '\n', 'utf8')
297
+ rmSync(dir, { recursive: true, force: true })
298
+ renameSync(tmp, dir)
299
+ return { root: dir, source: 'download', downloaded: true, files: written }
300
+ } catch (err) {
301
+ rmSync(tmp, { recursive: true, force: true })
302
+ if (err instanceof AssetPackError) throw err
303
+ throw new AssetPackError('素材包安装失败:' + (err?.message || err), { code: 'install', cause: err, url, dir })
304
+ } finally {
305
+ rmSync(archive, { force: true })
306
+ }
307
+ }
308
+
309
+ let inflight = null
310
+ let demoInflight = null
311
+
312
+ /**
313
+ * 保证素材可用。已经可用时是一次同步检查、立刻返回。
314
+ * @param {{onProgress?: (got:number,total:number)=>void, force?: boolean}} [opts]
315
+ */
316
+ export async function ensureAssets(opts = {}) {
317
+ const ready = assetsRoot()
318
+ if (ready && !opts.force) return { root: ready, source: 'existing', downloaded: false }
319
+ if (inflight) return inflight
320
+ inflight = installPack({ lock: ASSETS_LOCK, url: ASSETS_URL, dir: cacheDir(), onProgress: opts.onProgress })
321
+ try {
322
+ return await inflight
323
+ } finally {
324
+ inflight = null
325
+ }
326
+ }
327
+
328
+ /**
329
+ * 保证 demo 数据包可用:上游 demo 第一次请求缺的数据文件时下载一次(约 530KB)。
330
+ * 已经落地时是同步检查。
331
+ */
332
+ export async function ensureDemoAssets(opts = {}) {
333
+ const ready = demoAssetsRoot()
334
+ if (ready && !opts.force) return { root: ready, source: 'existing', downloaded: false }
335
+ if (demoInflight) return demoInflight
336
+ demoInflight = installPack({ lock: DEMO_ASSETS_LOCK, url: DEMO_ASSETS_URL, dir: demoCacheDir(), onProgress: opts.onProgress })
337
+ try {
338
+ return await demoInflight
339
+ } finally {
340
+ demoInflight = null
341
+ }
342
+ }
343
+
344
+ /** 工具层用:拿到素材根目录,或者抛一条人能照着做的错误。 */
345
+ export async function requireAssets({ onProgress } = {}) {
346
+ try {
347
+ const got = await ensureAssets({ onProgress })
348
+ return got.root
349
+ } catch (err) {
350
+ const reason = err?.message || String(err)
351
+ throw new AssetPackError(
352
+ '动效素材包(字体 + 素材库,一次性约 ' + Math.round((ASSETS_LOCK.bytes || 0) / 1048576) + 'MB)还没准备好:' + reason + '\n'
353
+ + '怎么处理:\n'
354
+ + ' 1) 联网后重试一次刚才的操作,插件会自动下载并校验;\n'
355
+ + ' 2) 或者手动下载 ' + ASSETS_URL + ' ,解压到 ' + cacheDir()
356
+ + '(目录里应当直接看到 fonts/ 和 media-library/);\n'
357
+ + ' 3) 走代理的话先设 HTTPS_PROXY 再重试。\n'
358
+ + '在此之前,画布与图片相关功能不受影响,只有动效(字体/素材库)用不了。',
359
+ { dir: cacheDir(), cause: err },
360
+ )
361
+ }
362
+ }
363
+
364
+ /** 媒体素材库根目录(没有素材时返回 null,不抛)。 */
365
+ export function mediaLibraryRoot() {
366
+ const root = assetsRoot()
367
+ if (!root) return null
368
+ const dir = join(root, 'media-library')
369
+ return existsSync(dir) ? dir : null
370
+ }
371
+
372
+ /** 字体目录(没有素材时返回 null,不抛)。 */
373
+ export function fontsDir() {
374
+ const root = assetsRoot()
375
+ if (!root) return null
376
+ const dir = join(root, 'fonts')
377
+ return existsSync(dir) ? dir : null
378
+ }
379
+
380
+ export function assetsSummary() {
381
+ const state = assetsState()
382
+ if (!state.ready) return { ready: false, version: ASSETS_VERSION, dir: state.dir, url: ASSETS_URL, page: ASSETS_PAGE }
383
+ const manifest = readManifest(state.root) || {}
384
+ return {
385
+ ready: true,
386
+ version: ASSETS_VERSION,
387
+ source: state.source,
388
+ root: state.root,
389
+ files: manifest.counts?.files ?? null,
390
+ bytes: manifest.counts?.bytes ?? null,
391
+ url: ASSETS_URL,
392
+ page: ASSETS_PAGE,
393
+ }
394
+ }