Files
image-workbench-desktop/src/storage-zip.js
T

177 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
;(function (global) {
'use strict'
/* ZIP 读写(自 app.js Workbench() 收编,P1 拆分批 5)
*
* 为什么是手写 ZIP 而不是 JSZip(原始决策,从 app.js 迁来):
* - CDN 动态插 <script> 加载 JSZip 在线上已被 CSP script-src 'self' 拦死(本地实测 onerror,
* window.JSZip 永远 undefined)—— 那条兜底等于死路,而且它会让 ZIP 备份**无法恢复**。
* - 读取改成不依赖网络的方案:ZIP 解析用浏览器原生能力自解析
* (STORE 直取 / DEFLATE 走 DecompressionStream('deflate-raw')),既不碰 CSP,也不依赖 CDN。
* - 写入用 STORE(图片本身已是 PNG/JPEG,已压缩,STORE 体积几乎不变还省几十秒 CPU):
* JSZip 无论是否 streamFiles 都要把整包内容物化在 JS 堆里,实测 200 张 ≥2MB 原图峰值 ~979MB;
* 这里改成边读边写 —— 图片 Blob 直接作为最终 Blob 的 part(数据留在浏览器 blob 存储,
* 不进 V8 堆),JS 堆里只有每张 1MB 级的 CRC 分片。
*
* 导出(只暴露外部真正要用的 4 个;CRC 表 / DOS 时间 / 签名常量属内部实现):
* - wZipParseEntries(buf) 解析中央目录 → { entries, u8, dv }
* - wZipReadEntry(zip, entry) 读单条目字节(method 0=STORE 直取 / 8=DEFLATE 走原生解压)
* - wOpenZipBlob(blob) ZIP → { file(name) → 惰性读取器 },接口对齐原 JSZip 用法
* - wCreateStoreZip() ZIP 写入器工厂 → { add(name, blob), finish() }
*
* 零外部依赖(只用 TextEncoder/TextDecoder/Blob/DataView/Uint8Array/DecompressionStream/Response),
* 故**直接对象导出**,不需要 create(deps)。
*
* ⚠️ 非确定性:wCreateStoreZip 用 new Date() 编 DOS 时间 ⇒ 同输入两次输出字节可能不同。
* 测试请走「写 → 读往返」比对条目内容,不要比字节。
*/
const W_ZIP_SIG_EOCD = 0x06054b50
const W_ZIP_SIG_CEN = 0x02014b50
// 解析中央目录 → 文件条目表(offset/方法/压缩后大小/原始大小)
function wZipParseEntries(buf) {
const u8 = new Uint8Array(buf)
const dv = new DataView(buf)
let eocd = -1
const minAt = Math.max(0, u8.length - 22 - 65535)
for (let i = u8.length - 22; i >= minAt; i--) {
if (dv.getUint32(i, true) === W_ZIP_SIG_EOCD) { eocd = i; break }
}
if (eocd < 0) throw new Error('不是有效的 ZIP(找不到中央目录)')
const count = dv.getUint16(eocd + 10, true)
let p = dv.getUint32(eocd + 16, true)
// 2026-10-28 修(BACKLOG §3.0):**必须先判 count**。
// 空 ZIP 总共只有 22 字节(仅 EOCD),中央目录偏移是 0 ⇒ `0 + 46 > 22` 成立,
// 原来会误抛「位置非法」,导致「0 条目的合法 ZIP」读不回来。
// 只在**有条目**时才校验位置;校验本身保留 —— 非空但中央目录非法的 ZIP 仍必须抛错
// (修这个洞时不能顺手把校验去掉,否则损坏的备份会被当成"空备份"静默通过)。
if (count > 0 && p + 46 > u8.length) throw new Error('ZIP 中央目录位置非法')
const dec = new TextDecoder()
const out = []
for (let i = 0; i < count; i++) {
if (p + 46 > u8.length || dv.getUint32(p, true) !== W_ZIP_SIG_CEN) throw new Error('ZIP 中央目录损坏')
const method = dv.getUint16(p + 10, true)
const compSize = dv.getUint32(p + 20, true)
const rawSize = dv.getUint32(p + 24, true)
const nameLen = dv.getUint16(p + 28, true)
const extraLen = dv.getUint16(p + 30, true)
const commentLen = dv.getUint16(p + 32, true)
const relOffset = dv.getUint32(p + 42, true)
const name = dec.decode(u8.subarray(p + 46, p + 46 + nameLen))
out.push({ name, method, compSize, rawSize, relOffset })
p += 46 + nameLen + extraLen + commentLen
}
return { entries: out, u8, dv }
}
// 读一个条目的原始字节(method 0=STORE 直取 / 8=DEFLATE 走原生 DecompressionStream)
async function wZipReadEntry(zip, entry) {
const u8 = zip.u8
const dv = zip.dv
const lh = entry.relOffset
if (lh + 30 > u8.length || dv.getUint32(lh, true) !== 0x04034b50) throw new Error('ZIP 条目头损坏:' + entry.name)
const nameLen = dv.getUint16(lh + 26, true)
const extraLen = dv.getUint16(lh + 28, true)
const dataAt = lh + 30 + nameLen + extraLen
const comp = u8.subarray(dataAt, dataAt + entry.compSize)
if (entry.method === 0) return comp
if (entry.method !== 8) throw new Error('ZIP 压缩方式不支持(method=' + entry.method + '):' + entry.name)
if (typeof DecompressionStream !== 'function') throw new Error('当前浏览器不支持原生解压 DEFLATE,无法读取该 ZIP')
const ds = new DecompressionStream('deflate-raw')
const stream = new Blob([comp]).stream().pipeThrough(ds)
return new Uint8Array(await new Response(stream).arrayBuffer())
}
// ZIP Blob → { file(name) → 惰性读取器 },接口对齐原 JSZip 用法(file()/async()/files)
async function wOpenZipBlob(blob) {
const zip = wZipParseEntries(await blob.arrayBuffer())
const files = {}
for (const e of zip.entries) {
if (e.name.charAt(e.name.length - 1) === '/') continue
files[e.name] = {
name: e.name,
async: async (kind) => {
const bytes = await wZipReadEntry(zip, e)
if (kind === 'string') return new TextDecoder().decode(bytes)
if (kind === 'base64') {
let bin = ''
const CHUNK = 32768
for (let i = 0; i < bytes.length; i += CHUNK) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK))
return btoa(bin)
}
return bytes
},
}
}
return { files, file: (name) => files[name] || null }
}
// ---- 备份 ZIP 写入器(ZIP STORE,零依赖)----
// JSZip 无论是否 streamFiles 都要把整包内容物化在 JS 堆里:实测 200 张 ≥2MB 原图峰值 ~979MB,
// 达不到「<100MB」的目标。这里改成边读边写的 ZIP:图片 Blob 直接作为最终 Blob 的 part
// (数据留在浏览器 blob 存储,不进 V8 堆),JS 堆里只有每张 1MB 级的 CRC 分片。
// 图片本身已是 PNG/JPEG(已压缩),STORE 相比 DEFLATE 体积几乎不变,还能省掉几十秒 CPU。
const W_CRC_TABLE = (() => {
const t = new Uint32Array(256)
for (let i = 0; i < 256; i++) { let c = i; for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1); t[i] = c >>> 0 }
return t
})()
function wCrc32Chunk(bytes, crc) {
let c = (crc ^ 0xFFFFFFFF) >>> 0
for (let i = 0; i < bytes.length; i++) c = (W_CRC_TABLE[(c ^ bytes[i]) & 0xFF] ^ (c >>> 8)) >>> 0
return (c ^ 0xFFFFFFFF) >>> 0
}
function wDosDateTime(d) {
const dt = d || new Date()
const time = ((dt.getHours() & 0x1F) << 11) | ((dt.getMinutes() & 0x3F) << 5) | (Math.floor(dt.getSeconds() / 2) & 0x1F)
const date = (((dt.getFullYear() - 1980) & 0x7F) << 9) | (((dt.getMonth() + 1) & 0x0F) << 5) | (dt.getDate() & 0x1F)
return { time: time & 0xFFFF, date: date & 0xFFFF }
}
function wCreateStoreZip() {
const enc = new TextEncoder()
const parts = []
const central = []
const { time, date } = wDosDateTime(new Date())
let offset = 0
const add = async (name, blob) => {
const nameBytes = enc.encode(String(name))
// 分片算 CRC:堆里只留 ~1MB 分片(整块 arrayBuffer 会把 200 张原图重新堆回 V8 堆)
const CHUNK = 1 << 20
let crc = 0
for (let p = 0; p < blob.size; p += CHUNK) {
const buf = new Uint8Array(await blob.slice(p, Math.min(blob.size, p + CHUNK)).arrayBuffer())
crc = wCrc32Chunk(buf, crc)
}
const size = blob.size
const lh = new Uint8Array(30 + nameBytes.length)
const dv = new DataView(lh.buffer)
dv.setUint32(0, 0x04034b50, true); dv.setUint16(4, 20, true); dv.setUint16(6, 0, true); dv.setUint16(8, 0, true)
dv.setUint16(10, time, true); dv.setUint16(12, date, true)
dv.setUint32(14, crc, true); dv.setUint32(18, size, true); dv.setUint32(22, size, true)
dv.setUint16(26, nameBytes.length, true); dv.setUint16(28, 0, true)
lh.set(nameBytes, 30)
const cd = new Uint8Array(46 + nameBytes.length)
const cv = new DataView(cd.buffer)
cv.setUint32(0, 0x02014b50, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true); cv.setUint16(8, 0, true)
cv.setUint16(10, 0, true); cv.setUint16(12, time, true); cv.setUint16(14, date, true)
cv.setUint32(16, crc, true); cv.setUint32(20, size, true); cv.setUint32(24, size, true)
cv.setUint16(28, nameBytes.length, true); cv.setUint16(30, 0, true); cv.setUint16(32, 0, true)
cv.setUint16(34, 0, true); cv.setUint16(36, 0, true); cv.setUint32(38, 0, true); cv.setUint32(42, offset, true)
cd.set(nameBytes, 46)
parts.push(lh, blob) // blob 原样进 parts:字节留在 blob 存储,不复制进 V8 堆
central.push(cd)
offset += lh.length + size
}
const finish = () => {
let cdSize = 0
for (const c of central) cdSize += c.length
const eocd = new Uint8Array(22)
const ev = new DataView(eocd.buffer)
ev.setUint32(0, 0x06054b50, true); ev.setUint16(4, 0, true); ev.setUint16(6, 0, true)
ev.setUint16(8, central.length, true); ev.setUint16(10, central.length, true)
ev.setUint32(12, cdSize, true); ev.setUint32(16, offset, true); ev.setUint16(20, 0, true)
return new Blob(parts.concat(central, [eocd]), { type: 'application/zip' })
}
return { add, finish }
}
global.IWBStorageZip = Object.freeze({ wZipParseEntries, wZipReadEntry, wOpenZipBlob, wCreateStoreZip })
})(typeof window !== 'undefined' ? window : globalThis)