dsh-seal-scripts 0.4.10 → 0.4.12

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.
package/lib/core/zip.js CHANGED
@@ -9,7 +9,10 @@
9
9
  * 只依赖 node 内置模块(node:zlib)。
10
10
  */
11
11
 
12
- import { inflateRawSync } from 'node:zlib'
12
+ import fs from 'node:fs'
13
+ import fsp from 'node:fs/promises'
14
+ import { Readable } from 'node:stream'
15
+ import { inflateRawSync, createInflateRaw } from 'node:zlib'
13
16
 
14
17
  const SIG_LOCAL = 0x04034b50
15
18
  const SIG_CENTRAL = 0x02014b50
@@ -18,9 +21,15 @@ const SIG_EOCD = 0x06054b50
18
21
  /** 通用标志位 bit 11:文件名是 UTF-8。写包时一直置上。 */
19
22
  const FLAG_UTF8 = 0x0800
20
23
 
21
- /** 包内单个文件上限 / 解压后合计上限。 */
22
- export const MAX_ZIP_ENTRY_BYTES = 64 * 1024 * 1024
23
- export const MAX_ZIP_TOTAL_BYTES = 128 * 1024 * 1024
24
+ /*
25
+ * 0.4.11:包内单文件 64 MB / 合计 128 MB 两个死数删掉。
26
+ * 解压炸弹仍然要防,但改成「按磁盘余量判」而不是拍一个数:解压前先用中央目录算出
27
+ * 解压后总字节(zipUncompressedTotal),留出余量,超过就拒绝(见 importToolSequence)。
28
+ * 这样正常的大包不会被挡在门外,真炸弹照样装不下。
29
+ */
30
+
31
+ /** 解压时至少要给磁盘留这么多余量,判「装不装得下」用。 */
32
+ export const DISK_RESERVE_BYTES = 16 * 1024 * 1024
24
33
 
25
34
  let CRC_TABLE = null
26
35
 
@@ -58,7 +67,10 @@ function dosDateTime(date) {
58
67
  }
59
68
 
60
69
  /**
61
- * 打一个 zip 包(全部 store,压缩率 0)。
70
+ * 打一个 zip 包(全部 store,压缩率 0),**在内存里拼整包**。
71
+ *
72
+ * 0.4.11 起导出走 writeZipFile(流式写盘),这个函数只留给「小包、顺手要一个 Buffer」
73
+ * 的调用方;两者字节格式一致,可以互换。
62
74
  *
63
75
  * @param {Array<{name:string, data?:Buffer|string, mtime?:Date}>} entries 用 / 分隔;目录条目以 / 结尾
64
76
  * @returns {Buffer}
@@ -76,7 +88,6 @@ export function buildZip(entries) {
76
88
  ? Buffer.alloc(0)
77
89
  : (Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data === undefined ? '' : entry.data), 'utf8'))
78
90
  const nameBuf = Buffer.from(name, 'utf8')
79
- if (body.length > MAX_ZIP_ENTRY_BYTES) throw new Error('单个文件超过上限:' + name)
80
91
  const crc = crc32(body)
81
92
  const stamp = dosDateTime(entry.mtime)
82
93
 
@@ -197,9 +208,7 @@ export function readZip(buf) {
197
208
  else if (method === 8) data = inflateRawSync(raw)
198
209
  else throw new Error('不支持的压缩方法 ' + method + '(' + name + ');只认 store / deflate')
199
210
 
200
- if (data.length > MAX_ZIP_ENTRY_BYTES) throw new Error('包内文件超过上限:' + name)
201
211
  total += data.length
202
- if (total > MAX_ZIP_TOTAL_BYTES) throw new Error('解压后合计超过上限(' + MAX_ZIP_TOTAL_BYTES + ' 字节)')
203
212
  if (data.length !== uncompSize) throw new Error('zip 损坏:' + name + ' 解出来的长度对不上')
204
213
  out.push({ name, isDir: false, data, method, crc })
205
214
  }
@@ -224,3 +233,314 @@ export function safeEntryName(raw) {
224
233
  }
225
234
  return parts.join('/')
226
235
  }
236
+
237
+ /* ───────────────── 0.4.11:流式写包 + 按磁盘余量判解压 ───────────────── */
238
+
239
+ /**
240
+ * 增量 CRC32(流式写盘用):state 从 -1 起,最后 (state ^ -1) >>> 0。
241
+ * @param {number} state
242
+ * @param {Buffer|Uint8Array} buf
243
+ * @returns {number}
244
+ */
245
+ export function crc32Update(state, buf) {
246
+ const table = crcTable()
247
+ let c = state
248
+ for (let i = 0; i < buf.length; i++) c = table[(c ^ buf[i]) & 0xFF] ^ (c >>> 8)
249
+ return c
250
+ }
251
+
252
+ /**
253
+ * 打一个 zip **直接写进磁盘**,不把整包拼在内存里(0.4.11 的导出走这条路)。
254
+ *
255
+ * store(压缩率 0):条目的 crc 先占位写进本地头,正文边读边写边算,
256
+ * 写完再用 pwrite 把 crc 补回本地头 offset+14。这样源文件只读一遍。
257
+ *
258
+ * @param {string} file 目标文件(会被覆盖)
259
+ * @param {Array<{name:string, source?:string, data?:Buffer|string, mtime?:Date}>} entries
260
+ * source 给绝对路径(流式拷贝),或 data 给内容
261
+ * @returns {Promise<{file:string, bytes:number, entries:number}>}
262
+ */
263
+ export async function writeZipFile(file, entries) {
264
+ const handle = await fsp.open(file, 'w')
265
+ const centrals = []
266
+ let offset = 0
267
+ try {
268
+ for (const entry of entries) {
269
+ const name = String(entry.name).split('\\').join('/')
270
+ if (name === '') throw new Error('zip 条目名不能为空')
271
+ const isDir = name.endsWith('/')
272
+ const nameBuf = Buffer.from(name, 'utf8')
273
+ const stamp = dosDateTime(entry.mtime)
274
+ let size = 0
275
+ let body = null
276
+ if (!isDir) {
277
+ if (typeof entry.source === 'string' && entry.source !== '') {
278
+ size = (await fsp.stat(entry.source)).size
279
+ } else {
280
+ body = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data === undefined ? '' : entry.data), 'utf8')
281
+ size = body.length
282
+ }
283
+ }
284
+
285
+ const local = Buffer.alloc(30)
286
+ local.writeUInt32LE(SIG_LOCAL, 0)
287
+ local.writeUInt16LE(20, 4)
288
+ local.writeUInt16LE(FLAG_UTF8, 6)
289
+ local.writeUInt16LE(0, 8)
290
+ local.writeUInt16LE(stamp.time, 10)
291
+ local.writeUInt16LE(stamp.date, 12)
292
+ local.writeUInt32LE(0, 14) // crc 占位,写完正文补
293
+ local.writeUInt32LE(size, 18)
294
+ local.writeUInt32LE(size, 22)
295
+ local.writeUInt16LE(nameBuf.length, 26)
296
+ local.writeUInt16LE(0, 28)
297
+ const headerOffset = offset
298
+ await handle.write(Buffer.concat([local, nameBuf]))
299
+ offset += local.length + nameBuf.length
300
+
301
+ let crc = 0
302
+ if (!isDir) {
303
+ let state = -1
304
+ if (body !== null) {
305
+ await handle.write(body)
306
+ offset += body.length
307
+ crc = crc32(body)
308
+ } else {
309
+ const stream = fs.createReadStream(entry.source, { highWaterMark: 1 << 20 })
310
+ for await (const chunk of stream) {
311
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
312
+ await handle.write(buf)
313
+ offset += buf.length
314
+ state = crc32Update(state, buf)
315
+ }
316
+ crc = (state ^ -1) >>> 0
317
+ }
318
+ const crcBuf = Buffer.alloc(4)
319
+ crcBuf.writeUInt32LE(crc, 0)
320
+ await handle.write(crcBuf, 0, 4, headerOffset + 14)
321
+ }
322
+
323
+ const central = Buffer.alloc(46)
324
+ central.writeUInt32LE(SIG_CENTRAL, 0)
325
+ central.writeUInt16LE(20, 4)
326
+ central.writeUInt16LE(20, 6)
327
+ central.writeUInt16LE(FLAG_UTF8, 8)
328
+ central.writeUInt16LE(0, 10)
329
+ central.writeUInt16LE(stamp.time, 12)
330
+ central.writeUInt16LE(stamp.date, 14)
331
+ central.writeUInt32LE(crc, 16)
332
+ central.writeUInt32LE(size, 20)
333
+ central.writeUInt32LE(size, 24)
334
+ central.writeUInt16LE(nameBuf.length, 28)
335
+ central.writeUInt16LE(0, 30)
336
+ central.writeUInt16LE(0, 32)
337
+ central.writeUInt16LE(0, 34)
338
+ central.writeUInt16LE(0, 36)
339
+ central.writeUInt32LE(isDir ? 0x10 : 0, 38)
340
+ central.writeUInt32LE(headerOffset, 42)
341
+ centrals.push(central, nameBuf)
342
+ }
343
+
344
+ const centralBuf = Buffer.concat(centrals)
345
+ const eocd = Buffer.alloc(22)
346
+ eocd.writeUInt32LE(SIG_EOCD, 0)
347
+ eocd.writeUInt16LE(0, 4)
348
+ eocd.writeUInt16LE(0, 6)
349
+ eocd.writeUInt16LE(entries.length, 8)
350
+ eocd.writeUInt16LE(entries.length, 10)
351
+ eocd.writeUInt32LE(centralBuf.length, 12)
352
+ eocd.writeUInt32LE(offset, 16)
353
+ eocd.writeUInt16LE(0, 20)
354
+ await handle.write(centralBuf)
355
+ await handle.write(eocd)
356
+ offset += centralBuf.length + eocd.length
357
+ } finally {
358
+ await handle.close().catch(() => {})
359
+ }
360
+ return { file, bytes: offset, entries: entries.length }
361
+ }
362
+
363
+ /**
364
+ * 只读中央目录,算出「解压后一共多大」——不解、不占内存。
365
+ * 解压炸弹的判断就靠它 + 磁盘余量。
366
+ * @param {Buffer} buf
367
+ * @returns {{bytes:number, files:number}}
368
+ */
369
+ export function zipUncompressedTotal(buf) {
370
+ if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
371
+ if (buf.length < 22) throw new Error('不是 zip:文件太短')
372
+ const eocd = findEocd(buf)
373
+ if (eocd < 0) throw new Error('不是 zip:找不到中央目录(可能只是改了扩展名的普通文件)')
374
+ const count = buf.readUInt16LE(eocd + 10)
375
+ const cdSize = buf.readUInt32LE(eocd + 12)
376
+ const cdOffset = buf.readUInt32LE(eocd + 16)
377
+ if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
378
+ throw new Error('不支持 zip64 包;重新导出一个普通 zip 再试')
379
+ }
380
+ if (cdOffset + cdSize > buf.length) throw new Error('zip 损坏:中央目录越界')
381
+ let bytes = 0
382
+ let files = 0
383
+ let p = cdOffset
384
+ for (let n = 0; n < count; n++) {
385
+ if (p + 46 > buf.length || buf.readUInt32LE(p) !== SIG_CENTRAL) {
386
+ throw new Error('zip 损坏:中央目录第 ' + (n + 1) + ' 项读不出来')
387
+ }
388
+ const uncompSize = buf.readUInt32LE(p + 24)
389
+ const nameLen = buf.readUInt16LE(p + 28)
390
+ const extraLen = buf.readUInt16LE(p + 30)
391
+ const commentLen = buf.readUInt16LE(p + 32)
392
+ const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8')
393
+ p += 46 + nameLen + extraLen + commentLen
394
+ if (uncompSize === 0xFFFFFFFF) throw new Error('不支持 zip64 包:' + name)
395
+ if (name.endsWith('/')) continue
396
+ bytes += uncompSize
397
+ files++
398
+ }
399
+ return { bytes, files }
400
+ }
401
+
402
+ /**
403
+ * 目录所在磁盘的可用字节数;拿不到给 null(调用方据此跳过这一道检查)。
404
+ * @param {string} dir
405
+ * @returns {Promise<number|null>}
406
+ */
407
+ export async function freeBytesOf(dir) {
408
+ try {
409
+ const st = await fsp.statfs(dir)
410
+ return Number(st.bavail) * Number(st.bsize)
411
+ } catch {
412
+ return null
413
+ }
414
+ }
415
+
416
+ /**
417
+ * 从磁盘上的 zip 文件里读中央目录(只读表,不解压任何条目)。
418
+ * 0.4.11 的导入走这条路:包有多大都不用整个读进内存。
419
+ * @param {string} file
420
+ * @returns {Promise<Array<{name:string,isDir:boolean,method:number,crc:number,compSize:number,uncompSize:number,localOffset:number}>>}
421
+ */
422
+ export async function readZipCentralFromFile(file) {
423
+ const handle = await fsp.open(file, 'r')
424
+ try {
425
+ const { size } = await handle.stat()
426
+ if (size < 22) throw new Error('不是 zip:文件太短')
427
+ const tailLen = Math.min(size, 22 + 0xFFFF)
428
+ const tail = Buffer.alloc(tailLen)
429
+ await handle.read(tail, 0, tailLen, size - tailLen)
430
+ const eocd = findEocd(tail)
431
+ if (eocd < 0) throw new Error('不是 zip:找不到中央目录(可能只是改了扩展名的普通文件)')
432
+ const count = tail.readUInt16LE(eocd + 10)
433
+ const cdSize = tail.readUInt32LE(eocd + 12)
434
+ const cdOffset = tail.readUInt32LE(eocd + 16)
435
+ if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
436
+ throw new Error('不支持 zip64 包;重新导出一个普通 zip 再试')
437
+ }
438
+ if (cdOffset + cdSize > size) throw new Error('zip 损坏:中央目录越界')
439
+ const cd = Buffer.alloc(cdSize)
440
+ await handle.read(cd, 0, cdSize, cdOffset)
441
+ const entries = []
442
+ let p = 0
443
+ for (let n = 0; n < count; n++) {
444
+ if (p + 46 > cd.length || cd.readUInt32LE(p) !== SIG_CENTRAL) {
445
+ throw new Error('zip 损坏:中央目录第 ' + (n + 1) + ' 项读不出来')
446
+ }
447
+ const flags = cd.readUInt16LE(p + 8)
448
+ const method = cd.readUInt16LE(p + 10)
449
+ const crc = cd.readUInt32LE(p + 16)
450
+ const compSize = cd.readUInt32LE(p + 20)
451
+ const uncompSize = cd.readUInt32LE(p + 24)
452
+ const nameLen = cd.readUInt16LE(p + 28)
453
+ const extraLen = cd.readUInt16LE(p + 30)
454
+ const commentLen = cd.readUInt16LE(p + 32)
455
+ const localOffset = cd.readUInt32LE(p + 42)
456
+ const name = cd.subarray(p + 46, p + 46 + nameLen).toString('utf8').split('\\').join('/')
457
+ p += 46 + nameLen + extraLen + commentLen
458
+ if (compSize === 0xFFFFFFFF || uncompSize === 0xFFFFFFFF) throw new Error('不支持 zip64 包:' + name)
459
+ if ((flags & 0x01) === 0x01) throw new Error('不支持加密的 zip:' + name)
460
+ entries.push({ name, isDir: name.endsWith('/'), method, crc, compSize, uncompSize, localOffset })
461
+ }
462
+ return entries
463
+ } finally {
464
+ await handle.close().catch(() => {})
465
+ }
466
+ }
467
+
468
+ /**
469
+ * 逐条取出包里的文件内容(流式:一条读完再下一条,内存里只有一块)。
470
+ *
471
+ * visit 收到 { name, isDir, method, uncompSize, read },read 是 async iterator(给 Buffer 块)。
472
+ * 目录条目 content 为空;读取条目的完整性(长度 + crc)在流结束时校验,不一致直接抛。
473
+ *
474
+ * @param {string} file
475
+ * @param {(entry:{name:string,isDir:boolean,method:number,uncompSize:number,read:()=>AsyncIterable<Buffer>}) => Promise<void>} visit
476
+ */
477
+ export async function forEachZipEntry(file, visit) {
478
+ const entries = await readZipCentralFromFile(file)
479
+ const handle = await fsp.open(file, 'r')
480
+ try {
481
+ const { size } = await handle.stat()
482
+ for (const e of entries) {
483
+ if (e.isDir) {
484
+ await visit({ name: e.name, isDir: true, method: e.method, uncompSize: 0, read: null })
485
+ continue
486
+ }
487
+ const head = Buffer.alloc(30)
488
+ await handle.read(head, 0, 30, e.localOffset)
489
+ if (head.readUInt32LE(0) !== SIG_LOCAL) throw new Error('zip 损坏:找不到 ' + e.name + ' 的本地头')
490
+ const lNameLen = head.readUInt16LE(26)
491
+ const lExtraLen = head.readUInt16LE(28)
492
+ const dataStart = e.localOffset + 30 + lNameLen + lExtraLen
493
+ const dataEnd = dataStart + e.compSize
494
+ if (dataEnd > size) throw new Error('zip 损坏:' + e.name + ' 的数据越界')
495
+
496
+ const rawChunks = async function* () {
497
+ let pos = dataStart
498
+ while (pos < dataEnd) {
499
+ const want = Math.min(1 << 20, dataEnd - pos)
500
+ const buf = Buffer.allocUnsafe(want)
501
+ const { bytesRead } = await handle.read(buf, 0, want, pos)
502
+ if (bytesRead <= 0) break
503
+ pos += bytesRead
504
+ yield buf.subarray(0, bytesRead)
505
+ }
506
+ }
507
+
508
+ const read = async function* () {
509
+ let state = -1
510
+ let total = 0
511
+ if (e.method === 0) {
512
+ for await (const chunk of rawChunks()) {
513
+ state = crc32Update(state, chunk)
514
+ total += chunk.length
515
+ yield chunk
516
+ }
517
+ } else if (e.method === 8) {
518
+ const inflater = createInflateRaw()
519
+ const src = Readable.from(rawChunks())
520
+ src.pipe(inflater)
521
+ try {
522
+ for await (const chunk of inflater) {
523
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
524
+ state = crc32Update(state, buf)
525
+ total += buf.length
526
+ yield buf
527
+ }
528
+ } finally {
529
+ src.destroy()
530
+ inflater.destroy()
531
+ }
532
+ } else {
533
+ throw new Error('不支持的压缩方法 ' + e.method + '(' + e.name + ');只认 store / deflate')
534
+ }
535
+ if (total !== e.uncompSize) {
536
+ throw new Error('zip 损坏:' + e.name + ' 解出来的长度对不上(' + total + ' != ' + e.uncompSize + ')')
537
+ }
538
+ if (((state ^ -1) >>> 0) !== e.crc) throw new Error('zip 损坏:' + e.name + ' 的 crc 对不上')
539
+ }
540
+
541
+ await visit({ name: e.name, isDir: false, method: e.method, uncompSize: e.uncompSize, read: () => read() })
542
+ }
543
+ } finally {
544
+ await handle.close().catch(() => {})
545
+ }
546
+ }
@@ -5,13 +5,18 @@
5
5
  * DSH 挂着压缩中间件(compression + dsha-web-mobile 的 compress.js),
6
6
  * 它们会在 res.end 时重算响应体并补头;我们先写头就会撞上
7
7
  * ERR_HTTP_HEADERS_SENT,连接直接异常,浏览器只看到 Failed to fetch。
8
+ *
9
+ * 0.4.11:请求体不再有「1 MB / 48 MB」这种死上限。
10
+ * 普通 JSON 端点走 readBody(边收边攒成 Buffer,不先攒字符串);
11
+ * 导入端点走 readBodyToFile(直接流到磁盘上的临时文件,包多大都不吃内存)。
8
12
  */
9
13
 
10
- /** 默认请求体上限(设置页的普通 JSON)。 */
11
- export const MAX_BODY_BYTES = 1_048_576
14
+ import fs from 'node:fs'
12
15
 
13
- /** 导入 zip 专用上限(0.4.3):包里是脚本文件,比普通 JSON 大得多。 */
14
- export const MAX_IMPORT_BODY_BYTES = 48 * 1024 * 1024
16
+ /**
17
+ * 一条请求体上限(只在调用方显式给数时生效)。0.4.11 起默认不限。
18
+ */
19
+ export const NO_LIMIT = 0
15
20
 
16
21
  /**
17
22
  * 回一个 JSON。永不抛错:响应已经发出去或客户端断开都只当没写。
@@ -43,29 +48,30 @@ export function sameOrigin(req) {
43
48
  }
44
49
 
45
50
  /**
46
- * 读请求体。三种情况都要能返回,不能挂住:
47
- * 请求体已经读完(readableEnded)→ 直接给空串
48
- * 正常有 body → 收完给字符串
49
- * 超限 → reject
51
+ * 读请求体,攒成 Buffer。四种情况都要能返回,不能挂住:
52
+ * 请求体已经读完(readableEnded)→ 直接给空 Buffer
53
+ * 正常有 body → 收完给 Buffer
54
+ * 给了 limit 且超了 → reject(默认不限,0.4.11 起没有 1 MB / 48 MB 这类死数)
55
+ * 客户端断开 / 出错 → reject
50
56
  *
51
- * 0.4.3 起上限可以按端点上调(导入的那个端点要收几十 MB 的 zip 的 base64)。
52
57
  * @param {import('node:http').IncomingMessage} req
53
- * @param {number} [limit]
58
+ * @param {number} [limit] 0 或负数 = 不限
59
+ * @returns {Promise<Buffer>}
54
60
  */
55
- export function readBody(req, limit = MAX_BODY_BYTES) {
56
- const max = Number.isFinite(limit) && limit > 0 ? limit : MAX_BODY_BYTES
61
+ export function readBodyBuffer(req, limit = NO_LIMIT) {
62
+ const max = Number.isFinite(limit) && limit > 0 ? limit : Infinity
57
63
  return new Promise((yes, no) => {
58
- if (req.readableEnded === true) { yes(''); return }
59
- let data = ''
64
+ if (req.readableEnded === true) { yes(Buffer.alloc(0)); return }
65
+ const chunks = []
60
66
  let bytes = 0
61
- let tooLarge = false
62
- req.setEncoding('utf8')
67
+ let failed = false
63
68
  req.on('data', (chunk) => {
64
- if (tooLarge) return
65
- bytes += Buffer.byteLength(chunk)
69
+ if (failed) return
70
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
71
+ bytes += buf.length
66
72
  if (bytes > max) {
67
- tooLarge = true
68
- data = ''
73
+ failed = true
74
+ chunks.length = 0
69
75
  // 已经太大:暂停上游,不再收;交给调用方回 413。
70
76
  try { req.pause() } catch { /* 有些 req 没有 pause */ }
71
77
  const err = new Error('请求体超过上限(' + max + ' 字节)')
@@ -73,10 +79,47 @@ export function readBody(req, limit = MAX_BODY_BYTES) {
73
79
  no(err)
74
80
  return
75
81
  }
76
- data += chunk
82
+ chunks.push(buf)
77
83
  })
78
- req.on('end', () => { if (!tooLarge) yes(data) })
79
- req.on('error', (e) => { if (!tooLarge) no(e) })
80
- req.on('aborted', () => { if (!tooLarge) no(new Error('aborted')) })
84
+ req.on('end', () => { if (!failed) yes(Buffer.concat(chunks, bytes)) })
85
+ req.on('error', (e) => { if (!failed) no(e) })
86
+ req.on('aborted', () => { if (!failed) no(new Error('aborted')) })
87
+ })
88
+ }
89
+
90
+ /**
91
+ * 读请求体成字符串(普通 JSON 端点用)。默认不限。
92
+ * @param {import('node:http').IncomingMessage} req
93
+ * @param {number} [limit]
94
+ * @returns {Promise<string>}
95
+ */
96
+ export function readBody(req, limit = NO_LIMIT) {
97
+ return readBodyBuffer(req, limit).then((buf) => buf.toString('utf8'))
98
+ }
99
+
100
+ /**
101
+ * 把请求体直接流进一个文件(导入大包走这条路):内存里只有一块,包多大都行。
102
+ * @param {import('node:http').IncomingMessage} req
103
+ * @param {string} file 目标文件(覆盖写)
104
+ * @returns {Promise<{bytes:number}>}
105
+ */
106
+ export function readBodyToFile(req, file) {
107
+ return new Promise((yes, no) => {
108
+ const stream = fs.createWriteStream(file)
109
+ let bytes = 0
110
+ let failed = false
111
+ const fail = (err) => {
112
+ if (failed) return
113
+ failed = true
114
+ stream.destroy()
115
+ no(err instanceof Error ? err : new Error(String(err)))
116
+ }
117
+ stream.on('error', fail)
118
+ req.on('data', (chunk) => { bytes += Buffer.byteLength(chunk) })
119
+ req.on('error', fail)
120
+ req.on('aborted', () => fail(new Error('aborted')))
121
+ req.on('end', () => { /* 等 stream 的 finish */ })
122
+ req.pipe(stream)
123
+ stream.on('finish', () => { if (!failed) yes({ bytes }) })
81
124
  })
82
125
  }
@@ -2,11 +2,13 @@
2
2
  * 「自创工具」页的数据:工具组清单的那一段原文,以及导入 / 导出(0.4.3)。
3
3
  */
4
4
 
5
+ import fsp from 'node:fs/promises'
6
+ import path from 'node:path'
5
7
  import { readOptionsSync } from '../../core/settings.js'
6
8
  import { readLocaleSync } from '../../core/locale.js'
7
- import { catalogText, toolSequenceRoot } from '../../core/schema.js'
8
- import { exportToolSequence, importToolSequence, MAX_EXPORT_BYTES } from '../../core/tool-transfer.js'
9
- import { MAX_IMPORT_BODY_BYTES, readBody, respond } from '../http-util.js'
9
+ import { catalogText, toolSequenceRoot, runsDir } from '../../core/schema.js'
10
+ import { exportToolSequence, importToolSequence } from '../../core/tool-transfer.js'
11
+ import { readBody, readBodyToFile, respond } from '../http-util.js'
10
12
 
11
13
  const PREFIX = '/api/session-recall.'
12
14
 
@@ -63,41 +65,76 @@ export function routesTools(route, { dshHome, onOptionsChanged }) {
63
65
  })
64
66
 
65
67
  /**
66
- * 导入(0.4.3):收一个 zip(base64),先解包校验,再按工具脚本目录逐个落地。
68
+ * 导入(0.4.3;0.4.11 改成两条入口)。
69
+ *
70
+ * application/zip(或任何非 JSON):请求体就是 zip 原始字节。先流式落到
71
+ * _runs/ 里的临时文件,再按中央目录逐条解出来直接写 staging——包多大都不吃内存。
72
+ * dryRun / name 走查询参数:?dryRun=1&name=xxx.zip
73
+ * application/json:老客户端(base64 包在 JSON 里)照旧能导入,但不再有 48 MB 上限。
74
+ *
67
75
  * dryRun 为真时只报「会装哪些、会盖哪些」,不写盘——设置页要用户点一次确认。
68
76
  */
69
77
  route(PREFIX + 'toolSequence/import', async (req, res) => {
70
78
  if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
71
- const raw = await readBody(req, MAX_IMPORT_BODY_BYTES)
72
- let body
73
- try { body = JSON.parse(raw || '{}') } catch { respond(res, 400, { error: { code: 'bad-json', message: '请求体不是 JSON' } }); return }
74
- const data = typeof body.data === 'string' ? body.data : ''
75
- if (data === '') { respond(res, 400, { error: { code: 'missing-file', message: '没有收到包内容' } }); return }
79
+ let query
80
+ try { query = new URL(req.url ?? '/', 'http://placeholder').searchParams } catch { query = new URLSearchParams() }
81
+ const ctype = String(req.headers['content-type'] ?? '').toLowerCase()
82
+ let dryRun = query.get('dryRun') === '1'
83
+ let name = query.get('name') || 'toolSequence.zip'
76
84
  let buffer
77
- try { buffer = Buffer.from(data, 'base64') } catch { respond(res, 400, { error: { code: 'bad-base64', message: '包内容不是合法的 base64' } }); return }
78
- if (buffer.length === 0) { respond(res, 400, { error: { code: 'empty-file', message: '包是空的' } }); return }
79
-
80
- const dryRun = body.dryRun === true
81
- let result
85
+ let tmpFile = ''
86
+ let bytes = 0
82
87
  try {
83
- result = await importToolSequence({ dshHome, buffer, dryRun })
84
- } catch (error) {
85
- respond(res, 400, { error: { code: 'import-failed', message: error?.message ?? String(error) } })
86
- return
87
- }
88
- // 真装上了就把工具表立刻对一次;和选项那条路由同一个道理:赶在下一轮 assemble() 之前。
89
- if (!dryRun) {
90
- try { onOptionsChanged?.() } catch { /* 同步失败不影响已经落地的文件,下一轮 pre-step 还会再对一次 */ }
88
+ if (ctype.includes('application/json')) {
89
+ const raw = await readBody(req)
90
+ let body
91
+ try { body = JSON.parse(raw || '{}') } catch {
92
+ respond(res, 400, { error: { code: 'bad-json', message: '请求体不是 JSON' } })
93
+ return
94
+ }
95
+ const data = typeof body.data === 'string' ? body.data : ''
96
+ if (data === '') { respond(res, 400, { error: { code: 'missing-file', message: '没有收到包内容' } }); return }
97
+ try { buffer = Buffer.from(data, 'base64') } catch { respond(res, 400, { error: { code: 'bad-base64', message: '包内容不是合法的 base64' } }); return }
98
+ if (buffer.length === 0) { respond(res, 400, { error: { code: 'empty-file', message: '包是空的' } }); return }
99
+ bytes = buffer.length
100
+ if (body.dryRun === true) dryRun = true
101
+ if (typeof body.name === 'string' && body.name !== '') name = body.name
102
+ } else {
103
+ // 原始字节:先落临时文件(在 _runs/ 里,导出时会跳过),再流式解包。
104
+ const dir = runsDir(dshHome)
105
+ await fsp.mkdir(dir, { recursive: true })
106
+ tmpFile = path.join(dir, 'import.tmp-' + Date.now() + '-' + process.pid + '.zip')
107
+ const written = await readBodyToFile(req, tmpFile)
108
+ bytes = written.bytes
109
+ if (bytes === 0) {
110
+ respond(res, 400, { error: { code: 'empty-file', message: '包是空的' } })
111
+ return
112
+ }
113
+ }
114
+
115
+ let result
116
+ try {
117
+ result = await importToolSequence({ dshHome, buffer, file: tmpFile || undefined, dryRun })
118
+ } catch (error) {
119
+ respond(res, 400, { error: { code: 'import-failed', message: error?.message ?? String(error) } })
120
+ return
121
+ }
122
+ // 真装上了就把工具表立刻对一次;和选项那条路由同一个道理:赶在下一轮 assemble() 之前。
123
+ if (!dryRun) {
124
+ try { onOptionsChanged?.() } catch { /* 同步失败不影响已经落地的文件,下一轮 pre-step 还会再对一次 */ }
125
+ }
126
+ respond(res, 200, {
127
+ ok: true,
128
+ dryRun,
129
+ name,
130
+ size: bytes,
131
+ path: toolSequenceRoot(dshHome),
132
+ imported: result.imported,
133
+ overwritten: result.overwritten,
134
+ skipped: result.skipped
135
+ })
136
+ } finally {
137
+ if (tmpFile !== '') await fsp.rm(tmpFile, { force: true }).catch(() => {})
91
138
  }
92
- respond(res, 200, {
93
- ok: true,
94
- dryRun,
95
- name: typeof body.name === 'string' ? body.name : 'toolSequence.zip',
96
- size: buffer.length,
97
- path: toolSequenceRoot(dshHome),
98
- imported: result.imported,
99
- overwritten: result.overwritten,
100
- skipped: result.skipped
101
- })
102
139
  })
103
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-seal-scripts",
3
- "version": "0.4.10",
3
+ "version": "0.4.12",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "index.js",