| 29 | * 避免测试依赖系统 zip 命令或额外生产依赖。 |
| 30 | */ |
| 31 | export function writeZipFixture(filePath: string, entries: ZipFixtureEntry[]): void { |
| 32 | const localParts: Buffer[] = [] |
| 33 | const centralParts: Buffer[] = [] |
| 34 | let localOffset = 0 |
| 35 | |
| 36 | for (const entry of entries) { |
| 37 | const name = Buffer.from(entry.name, 'utf8') |
| 38 | const content = Buffer.isBuffer(entry.content) ? entry.content : Buffer.from(entry.content, 'utf8') |
| 39 | const compressed = deflateRawSync(content) |
| 40 | const flags = 0x0800 | (entry.encrypted ? 0x0001 : 0) |
| 41 | const checksum = crc32(content) |
| 42 | |
| 43 | const localHeader = Buffer.alloc(30) |
| 44 | localHeader.writeUInt32LE(0x04034b50, 0) |
| 45 | localHeader.writeUInt16LE(20, 4) |
| 46 | localHeader.writeUInt16LE(flags, 6) |
| 47 | localHeader.writeUInt16LE(8, 8) |
| 48 | localHeader.writeUInt32LE(checksum, 14) |
| 49 | localHeader.writeUInt32LE(compressed.length, 18) |
| 50 | localHeader.writeUInt32LE(content.length, 22) |
| 51 | localHeader.writeUInt16LE(name.length, 26) |
| 52 | |
| 53 | localParts.push(localHeader, name, compressed) |
| 54 | |
| 55 | const centralHeader = Buffer.alloc(46) |
| 56 | centralHeader.writeUInt32LE(0x02014b50, 0) |
| 57 | centralHeader.writeUInt16LE(20, 4) |
| 58 | centralHeader.writeUInt16LE(20, 6) |
| 59 | centralHeader.writeUInt16LE(flags, 8) |
| 60 | centralHeader.writeUInt16LE(8, 10) |
| 61 | centralHeader.writeUInt32LE(checksum, 16) |
| 62 | centralHeader.writeUInt32LE(compressed.length, 20) |
| 63 | centralHeader.writeUInt32LE(content.length, 24) |
| 64 | centralHeader.writeUInt16LE(name.length, 28) |
| 65 | centralHeader.writeUInt32LE(localOffset, 42) |
| 66 | centralParts.push(centralHeader, name) |
| 67 | |
| 68 | localOffset += localHeader.length + name.length + compressed.length |
| 69 | } |
| 70 | |
| 71 | const centralSize = centralParts.reduce((size, part) => size + part.length, 0) |
| 72 | const end = Buffer.alloc(22) |
| 73 | end.writeUInt32LE(0x06054b50, 0) |
| 74 | end.writeUInt16LE(entries.length, 8) |
| 75 | end.writeUInt16LE(entries.length, 10) |
| 76 | end.writeUInt32LE(centralSize, 12) |
| 77 | end.writeUInt32LE(localOffset, 16) |
| 78 | |
| 79 | writeFileSync(filePath, Buffer.concat([...localParts, ...centralParts, end])) |
| 80 | } |