function crc32(data: Uint8Array): number { let c = 0xffffffff; for (let i = 0; i < data.length; i += 1) { c ^= data[i]; for (let k = 0; k < 8; k += 1) { c = (c >>> 1) ^ (0xedb88320 & -(c & 1)); } } return (c ^ 0xffffffff) >>> 0; } function u16(n: number): Uint8Array { const b = new Uint8Array(2); new DataView(b.buffer).setUint16(0, n, true); return b; } function u32(n: number): Uint8Array { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n, true); return b; } function concat(parts: Uint8Array[]): Uint8Array { const total = parts.reduce((n, p) => n + p.length, 0); const out = new Uint8Array(total); let offset = 0; for (const p of parts) { out.set(p, offset); offset += p.length; } return out; } export function sanitizeZipEntryName(name: string): string { const base = String(name || 'invoice') .replace(/[\\/:*?"<>|]+/g, '_') .replace(/\s+/g, '_') .slice(0, 80); return base || 'invoice'; } /** 不压缩 zip(STORE)。下载后解压即相当于一个文件夹。 */ export function buildZipStore(entries: Array<{ name: string; data: Uint8Array }>): Blob { const used = new Set(); const files = entries.map((entry, index) => { let name = sanitizeZipEntryName(entry.name); if (used.has(name)) name = `${index}_${name}`; used.add(name); const nameBytes = new TextEncoder().encode(name); const crc = crc32(entry.data); return { nameBytes, data: entry.data, crc }; }); const locals: Uint8Array[] = []; const centrals: Uint8Array[] = []; let offset = 0; for (const file of files) { const local = concat([ new Uint8Array([0x50, 0x4b, 0x03, 0x04]), u16(20), u16(0x0800), u16(0), u16(0), u16(0), u32(file.crc), u32(file.data.length), u32(file.data.length), u16(file.nameBytes.length), u16(0), file.nameBytes, file.data, ]); const central = concat([ new Uint8Array([0x50, 0x4b, 0x01, 0x02]), u16(20), u16(20), u16(0x0800), u16(0), u16(0), u16(0), u32(file.crc), u32(file.data.length), u32(file.data.length), u16(file.nameBytes.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(offset), file.nameBytes, ]); locals.push(local); centrals.push(central); offset += local.length; } const centralDir = concat(centrals); const eocd = concat([ new Uint8Array([0x50, 0x4b, 0x05, 0x06]), u16(0), u16(0), u16(files.length), u16(files.length), u32(centralDir.length), u32(offset), u16(0), ]); return new Blob([concat([...locals, centralDir, eocd]) as unknown as BlobPart], { type: 'application/zip' }); } export function triggerBlobDownload(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); }