@huaqiu/hardware-artifacts 0.7.18 → 0.7.20
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/index.d.mts +61 -8
- package/lib/index.mjs +2610 -6
- package/lib/routes-D78ML_ef.d.mts +438 -0
- package/lib/routes.d.mts +2 -18
- package/lib/routes.mjs +156 -41
- package/lib/{service-CtVn7z8b.d.mts → service-BGecln85.d.mts} +119 -28
- package/lib/{service-Yrc2C_eo.mjs → service-Bo58tzXv.mjs} +570 -167
- package/lib/service.d.mts +1 -1
- package/lib/service.mjs +1 -1
- package/package.json +2 -1
- package/src/index.ts +124 -5
- package/src/order.ts +22 -0
- package/src/package.ts +282 -0
- package/src/routes.ts +127 -48
- package/src/service.ts +1635 -1651
- package/src/toolchain/dialog.ts +240 -0
- package/src/toolchain/discovery.ts +266 -0
- package/src/toolchain/index.ts +36 -0
- package/src/toolchain/install.ts +430 -0
- package/src/toolchain/lzma.ts +384 -0
- package/src/toolchain/manager.ts +596 -0
- package/src/toolchain/manifest.ts +234 -0
- package/src/toolchain/resolve.ts +325 -0
- package/src/toolchain/zip.ts +495 -0
- package/src/tools.ts +470 -0
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal, safe, streaming ZIP reader — the installer's only archive code.
|
|
3
|
+
*
|
|
4
|
+
* Three reasons this is not a dependency: the archive is ~840 MB, so a
|
|
5
|
+
* load-into-memory unzip is not acceptable (§7.5); extraction must be able to
|
|
6
|
+
* *refuse* an entry rather than sanitize it afterwards (§8.4); and every byte it
|
|
7
|
+
* writes has to be observable so the UI can show extraction progress (§7.4).
|
|
8
|
+
* Node ships the two primitives the format needs (`inflateRaw` and file
|
|
9
|
+
* streams), so the reader is a small amount of code instead of a package.
|
|
10
|
+
*
|
|
11
|
+
* Supported: stored (method 0) and deflated (method 8) entries from a classic
|
|
12
|
+
* (non-ZIP64) central directory — what the HuaQiu portable distributions are.
|
|
13
|
+
* Everything else is refused rather than guessed at.
|
|
14
|
+
*
|
|
15
|
+
* @module @huaqiu/hardware-artifacts/toolchain/zip
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const directory = await readZipDirectory('kicad.zip')
|
|
19
|
+
* await extractZip('kicad.zip', staging, { directory, stripPrefix: commonDirectory(directory) })
|
|
20
|
+
*/
|
|
21
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
22
|
+
import { mkdir, stat, writeFile } from 'node:fs/promises'
|
|
23
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
24
|
+
import { Transform } from 'node:stream'
|
|
25
|
+
import { pipeline } from 'node:stream/promises'
|
|
26
|
+
import { createInflateRaw } from 'node:zlib'
|
|
27
|
+
import { decodeLzma, readZipLzmaHeader } from './lzma.js'
|
|
28
|
+
|
|
29
|
+
const EOCD_SIGNATURE = 0x06054b50
|
|
30
|
+
const ZIP64_LOCATOR_SIGNATURE = 0x07064b50
|
|
31
|
+
const ZIP64_EOCD_SIGNATURE = 0x06064b50
|
|
32
|
+
const CENTRAL_SIGNATURE = 0x02014b50
|
|
33
|
+
const LOCAL_SIGNATURE = 0x04034b50
|
|
34
|
+
/** ZIP compression method 14 (LZMA) — the KiCad distribution's dominant method. */
|
|
35
|
+
const LZMA_METHOD = 14
|
|
36
|
+
const EOCD_SEARCH_BYTES = 66_000
|
|
37
|
+
const MAX_CENTRAL_DIRECTORY_BYTES = 64 * 1024 * 1024
|
|
38
|
+
|
|
39
|
+
/** One file (or directory) the archive declares. */
|
|
40
|
+
export interface ZipEntry {
|
|
41
|
+
/** Archive path as written, with `\` normalised to `/`. */
|
|
42
|
+
readonly name: string
|
|
43
|
+
/** Bytes the entry occupies inside the archive. */
|
|
44
|
+
readonly compressedSize: number
|
|
45
|
+
/** Bytes the entry expands to. */
|
|
46
|
+
readonly uncompressedSize: number
|
|
47
|
+
/** Compression method (0 stored, 8 deflated). */
|
|
48
|
+
readonly method: number
|
|
49
|
+
/** Absolute byte offset of the entry's local header. */
|
|
50
|
+
readonly headerOffset: number
|
|
51
|
+
/** True for a directory entry. */
|
|
52
|
+
readonly directory: boolean
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The archive's table of contents. */
|
|
56
|
+
export interface ZipDirectory {
|
|
57
|
+
readonly entries: readonly ZipEntry[]
|
|
58
|
+
/** Sum of every entry's uncompressed size — the extraction budget. */
|
|
59
|
+
readonly totalUncompressed: number
|
|
60
|
+
/** Bytes the archive file itself occupies. */
|
|
61
|
+
readonly archiveBytes: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Limits that turn a hostile or corrupt archive into a refusal. */
|
|
65
|
+
export interface ZipLimits {
|
|
66
|
+
/** Largest single extracted file. */
|
|
67
|
+
readonly maxEntryBytes: number
|
|
68
|
+
/** Largest total extracted size. */
|
|
69
|
+
readonly maxTotalBytes: number
|
|
70
|
+
/** Largest number of entries. */
|
|
71
|
+
readonly maxEntries: number
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Defaults sized for the real distributions (~840 MB archive, ~2 GiB extracted). */
|
|
75
|
+
export const DEFAULT_ZIP_LIMITS: ZipLimits = Object.freeze({
|
|
76
|
+
maxEntryBytes: 3 * 1024 * 1024 * 1024,
|
|
77
|
+
maxTotalBytes: 16 * 1024 * 1024 * 1024,
|
|
78
|
+
maxEntries: 400_000,
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
/** A structural problem with the archive; never repaired, always refused. */
|
|
82
|
+
export class ZipError extends Error {
|
|
83
|
+
constructor(readonly code: string, message: string) {
|
|
84
|
+
super(message)
|
|
85
|
+
this.name = 'ZipError'
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Progress of one extraction run. */
|
|
90
|
+
export interface ExtractProgress {
|
|
91
|
+
/** Bytes written so far. */
|
|
92
|
+
readonly written: number
|
|
93
|
+
/** Total bytes the directory declared. */
|
|
94
|
+
readonly total: number
|
|
95
|
+
/** Entries completed. */
|
|
96
|
+
readonly entries: number
|
|
97
|
+
/** Entries declared in total. */
|
|
98
|
+
readonly totalEntries: number
|
|
99
|
+
/** Archive path of the file being written. */
|
|
100
|
+
readonly current: string
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** What one extraction run produced. */
|
|
104
|
+
export interface ExtractionResult {
|
|
105
|
+
readonly files: number
|
|
106
|
+
readonly directories: number
|
|
107
|
+
readonly bytes: number
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Injection points so traversal, limits and cancellation are testable. */
|
|
111
|
+
export interface ExtractOptions {
|
|
112
|
+
readonly signal?: AbortSignal
|
|
113
|
+
readonly onProgress?: (progress: ExtractProgress) => void
|
|
114
|
+
/** Pre-read directory, to avoid reading it twice. */
|
|
115
|
+
readonly directory?: ZipDirectory
|
|
116
|
+
/** Entry path prefix to drop (`kicad-huaqiu-…/`), from {@link commonDirectory}. */
|
|
117
|
+
readonly stripPrefix?: string
|
|
118
|
+
readonly limits?: Partial<ZipLimits>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Normalise and validate one archive path.
|
|
123
|
+
*
|
|
124
|
+
* Absolute paths, drive letters, `..` segments, NUL bytes, Windows alternate
|
|
125
|
+
* data streams and reserved device names are all rejected: the first three
|
|
126
|
+
* escape the target directory (§8.4), the rest cannot be safely created on the
|
|
127
|
+
* target platform.
|
|
128
|
+
* @param raw - entry name as the archive stores it.
|
|
129
|
+
* @returns the safe relative path segments.
|
|
130
|
+
*/
|
|
131
|
+
export function safeEntrySegments(raw: string): string[] {
|
|
132
|
+
const name = raw.replaceAll('\\', '/')
|
|
133
|
+
if (name.includes('\u0000')) throw new ZipError('unsafe-entry', `archive entry contains NUL: ${raw}`)
|
|
134
|
+
if (name.startsWith('/')) throw new ZipError('unsafe-entry', `archive entry is absolute: ${raw}`)
|
|
135
|
+
if (/^[A-Za-z]:/u.test(name)) throw new ZipError('unsafe-entry', `archive entry has a drive prefix: ${raw}`)
|
|
136
|
+
const segments = name.split('/').filter(segment => segment !== '' && segment !== '.')
|
|
137
|
+
if (segments.some(segment => segment === '..')) {
|
|
138
|
+
throw new ZipError('unsafe-entry', `archive entry traverses upwards: ${raw}`)
|
|
139
|
+
}
|
|
140
|
+
if (segments.length === 0) throw new ZipError('unsafe-entry', `archive entry has no name: ${raw}`)
|
|
141
|
+
for (const segment of segments) {
|
|
142
|
+
if (segment.includes(':')) throw new ZipError('unsafe-entry', `archive entry has a stream separator: ${raw}`)
|
|
143
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/iu.test(segment)) {
|
|
144
|
+
throw new ZipError('unsafe-entry', `archive entry is a reserved device name: ${raw}`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return segments
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Read exactly `length` bytes at `start` into `target`. */
|
|
151
|
+
async function readRange(archivePath: string, start: number, length: number, target: Buffer): Promise<void> {
|
|
152
|
+
if (length === 0) return
|
|
153
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
154
|
+
const stream = createReadStream(archivePath, { start, end: start + length - 1 })
|
|
155
|
+
let filled = 0
|
|
156
|
+
stream.on('data', (chunk: Buffer | string) => {
|
|
157
|
+
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
|
|
158
|
+
filled += buffer.copy(target, filled)
|
|
159
|
+
})
|
|
160
|
+
stream.on('end', () => {
|
|
161
|
+
if (filled === length) resolvePromise()
|
|
162
|
+
else rejectPromise(new ZipError('invalid-zip', `short read at ${String(start)}`))
|
|
163
|
+
})
|
|
164
|
+
stream.on('error', rejectPromise)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Read an unsigned 64-bit little-endian field as a JS number (exact below 2^53). */
|
|
169
|
+
function u64(buffer: Buffer, offset: number): number {
|
|
170
|
+
const value = buffer.readBigUInt64LE(offset)
|
|
171
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new ZipError('archive-too-large', 'archive declares an unsupported size')
|
|
172
|
+
return Number(value)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Resolve the end-of-central-directory values, following the ZIP64 record when
|
|
177
|
+
* the classic fields are saturated.
|
|
178
|
+
*
|
|
179
|
+
* The HuaQiu KiCad archive is genuinely ZIP64 (its contents exceed the classic
|
|
180
|
+
* 4 GiB uncompressed limit), so this is a real requirement, not a defensive
|
|
181
|
+
* branch: refusing ZIP64 would refuse the primary download (§8.5).
|
|
182
|
+
* @param archivePath - archive being read.
|
|
183
|
+
* @param eocd - tail window containing the classic record.
|
|
184
|
+
* @param eocdOffset - index of the classic record inside `eocd`.
|
|
185
|
+
* @returns the entry count, directory size and directory offset.
|
|
186
|
+
*/
|
|
187
|
+
async function directoryLocation(
|
|
188
|
+
archivePath: string,
|
|
189
|
+
eocd: Buffer,
|
|
190
|
+
eocdOffset: number,
|
|
191
|
+
): Promise<{ entryCount: number; directorySize: number; directoryOffset: number }> {
|
|
192
|
+
const entryCount = eocd.readUInt16LE(eocdOffset + 10)
|
|
193
|
+
const directorySize = eocd.readUInt32LE(eocdOffset + 12)
|
|
194
|
+
const directoryOffset = eocd.readUInt32LE(eocdOffset + 16)
|
|
195
|
+
const zip64 = entryCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff
|
|
196
|
+
if (!zip64) return { entryCount, directorySize, directoryOffset }
|
|
197
|
+
|
|
198
|
+
// The ZIP64 locator sits immediately before the classic record.
|
|
199
|
+
const locatorOffset = eocdOffset - 20
|
|
200
|
+
if (locatorOffset < 0 || eocd.readUInt32LE(locatorOffset) !== ZIP64_LOCATOR_SIGNATURE) {
|
|
201
|
+
throw new ZipError('invalid-zip', 'ZIP64 archive without a ZIP64 locator')
|
|
202
|
+
}
|
|
203
|
+
const recordOffset = u64(eocd, locatorOffset + 8)
|
|
204
|
+
const record = Buffer.alloc(56)
|
|
205
|
+
await readRange(archivePath, recordOffset, 56, record)
|
|
206
|
+
if (record.readUInt32LE(0) !== ZIP64_EOCD_SIGNATURE) {
|
|
207
|
+
throw new ZipError('invalid-zip', 'ZIP64 end-of-central-directory record is missing')
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
entryCount: u64(record, 32),
|
|
211
|
+
directorySize: u64(record, 40),
|
|
212
|
+
directoryOffset: u64(record, 48),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Read one central-directory entry's ZIP64 extended sizes from its extra field.
|
|
218
|
+
*
|
|
219
|
+
* The extra block only carries the values the classic header saturated, in
|
|
220
|
+
* declaration order (uncompressed, compressed, offset) — reading them positionally
|
|
221
|
+
* is what the specification requires.
|
|
222
|
+
* @param extra - the entry's extra-field bytes.
|
|
223
|
+
* @param needs - which classic fields were saturated.
|
|
224
|
+
* @returns the saturated values as numbers.
|
|
225
|
+
*/
|
|
226
|
+
function zip64Sizes(
|
|
227
|
+
extra: Buffer,
|
|
228
|
+
needs: { readonly uncompressed: boolean; readonly compressed: boolean; readonly offset: boolean },
|
|
229
|
+
): { uncompressedSize?: number; compressedSize?: number; headerOffset?: number } {
|
|
230
|
+
if (!needs.uncompressed && !needs.compressed && !needs.offset) return {}
|
|
231
|
+
let cursor = 0
|
|
232
|
+
while (cursor + 4 <= extra.length) {
|
|
233
|
+
const id = extra.readUInt16LE(cursor)
|
|
234
|
+
const size = extra.readUInt16LE(cursor + 2)
|
|
235
|
+
const body = extra.subarray(cursor + 4, cursor + 4 + size)
|
|
236
|
+
cursor += 4 + size + (size % 2)
|
|
237
|
+
if (id !== 0x0001) continue
|
|
238
|
+
let at = 0
|
|
239
|
+
const result: { uncompressedSize?: number; compressedSize?: number; headerOffset?: number } = {}
|
|
240
|
+
const next = (): number => {
|
|
241
|
+
const value = u64(body, at)
|
|
242
|
+
at += 8
|
|
243
|
+
return value
|
|
244
|
+
}
|
|
245
|
+
if (needs.uncompressed) result.uncompressedSize = next()
|
|
246
|
+
if (needs.compressed) result.compressedSize = next()
|
|
247
|
+
if (needs.offset) result.headerOffset = next()
|
|
248
|
+
return result
|
|
249
|
+
}
|
|
250
|
+
throw new ZipError('invalid-zip', 'ZIP64 entry is missing its extended size field')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Locate and parse the central directory.
|
|
255
|
+
* @param archivePath - archive to read.
|
|
256
|
+
* @returns the table of contents.
|
|
257
|
+
*/
|
|
258
|
+
export async function readZipDirectory(archivePath: string): Promise<ZipDirectory> {
|
|
259
|
+
const size = (await stat(archivePath)).size
|
|
260
|
+
const eocdLength = Math.min(size, EOCD_SEARCH_BYTES)
|
|
261
|
+
const eocd = Buffer.alloc(eocdLength)
|
|
262
|
+
await readRange(archivePath, size - eocdLength, eocdLength, eocd)
|
|
263
|
+
|
|
264
|
+
let eocdOffset = -1
|
|
265
|
+
for (let index = eocdLength - 22; index >= 0; index -= 1) {
|
|
266
|
+
if (eocd.readUInt32LE(index) === EOCD_SIGNATURE) {
|
|
267
|
+
eocdOffset = index
|
|
268
|
+
break
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (eocdOffset < 0) throw new ZipError('invalid-zip', 'no end-of-central-directory record')
|
|
272
|
+
|
|
273
|
+
const { entryCount, directorySize, directoryOffset } = await directoryLocation(archivePath, eocd, eocdOffset)
|
|
274
|
+
if (directorySize > MAX_CENTRAL_DIRECTORY_BYTES) {
|
|
275
|
+
throw new ZipError('invalid-zip', `central directory is implausibly large (${String(directorySize)} bytes)`)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const directory = Buffer.alloc(directorySize)
|
|
279
|
+
await readRange(archivePath, directoryOffset, directorySize, directory)
|
|
280
|
+
|
|
281
|
+
const entries: ZipEntry[] = []
|
|
282
|
+
let cursor = 0
|
|
283
|
+
let totalUncompressed = 0
|
|
284
|
+
for (let index = 0; index < entryCount; index += 1) {
|
|
285
|
+
if (cursor + 46 > directory.length || directory.readUInt32LE(cursor) !== CENTRAL_SIGNATURE) {
|
|
286
|
+
throw new ZipError('invalid-zip', `central directory entry ${String(index)} is malformed`)
|
|
287
|
+
}
|
|
288
|
+
const method = directory.readUInt16LE(cursor + 10)
|
|
289
|
+
const compressedField = directory.readUInt32LE(cursor + 20)
|
|
290
|
+
const uncompressedField = directory.readUInt32LE(cursor + 24)
|
|
291
|
+
const nameLength = directory.readUInt16LE(cursor + 28)
|
|
292
|
+
const extraLength = directory.readUInt16LE(cursor + 30)
|
|
293
|
+
const commentLength = directory.readUInt16LE(cursor + 32)
|
|
294
|
+
const offsetField = directory.readUInt32LE(cursor + 42)
|
|
295
|
+
const name = directory.toString('utf8', cursor + 46, cursor + 46 + nameLength)
|
|
296
|
+
const extra = directory.subarray(cursor + 46 + nameLength, cursor + 46 + nameLength + extraLength)
|
|
297
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
298
|
+
|
|
299
|
+
const extended = zip64Sizes(extra, {
|
|
300
|
+
uncompressed: uncompressedField === 0xffffffff,
|
|
301
|
+
compressed: compressedField === 0xffffffff,
|
|
302
|
+
offset: offsetField === 0xffffffff,
|
|
303
|
+
})
|
|
304
|
+
const compressedSize = extended.compressedSize ?? compressedField
|
|
305
|
+
const uncompressedSize = extended.uncompressedSize ?? uncompressedField
|
|
306
|
+
const headerOffset = extended.headerOffset ?? offsetField
|
|
307
|
+
entries.push({
|
|
308
|
+
name: name.replaceAll('\\', '/'),
|
|
309
|
+
compressedSize,
|
|
310
|
+
uncompressedSize,
|
|
311
|
+
method,
|
|
312
|
+
headerOffset,
|
|
313
|
+
directory: name.replaceAll('\\', '/').endsWith('/'),
|
|
314
|
+
})
|
|
315
|
+
totalUncompressed += uncompressedSize
|
|
316
|
+
}
|
|
317
|
+
return { entries, totalUncompressed, archiveBytes: size }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The single wrapper directory an archive extracts into, when it has one.
|
|
322
|
+
*
|
|
323
|
+
* Both HuaQiu distributions ship one (`kicad-huaqiu-…/`, `solidcraft-…/`), and
|
|
324
|
+
* the spec installs the *contents* into a versioned directory (§8.2/§8.3). Only
|
|
325
|
+
* a genuine single root qualifies; an archive with two top-level names keeps
|
|
326
|
+
* its own layout, because guessing would lose files.
|
|
327
|
+
* @param directory - the archive's table of contents.
|
|
328
|
+
* @returns the prefix to strip (with its trailing `/`), or undefined.
|
|
329
|
+
*/
|
|
330
|
+
export function commonDirectory(directory: ZipDirectory): string | undefined {
|
|
331
|
+
const prefixes = new Set<string>()
|
|
332
|
+
for (const entry of directory.entries) {
|
|
333
|
+
const first = entry.name.split('/')[0]
|
|
334
|
+
if (first === undefined || first === '') return undefined
|
|
335
|
+
prefixes.add(first)
|
|
336
|
+
if (prefixes.size > 1) return undefined
|
|
337
|
+
}
|
|
338
|
+
const [prefix] = [...prefixes]
|
|
339
|
+
return prefix === undefined ? undefined : `${prefix}/`
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Resolve one entry's data offset by reading its local header. */
|
|
343
|
+
async function dataOffsetOf(archivePath: string, entry: ZipEntry): Promise<number> {
|
|
344
|
+
const header = Buffer.alloc(30)
|
|
345
|
+
await readRange(archivePath, entry.headerOffset, 30, header)
|
|
346
|
+
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) {
|
|
347
|
+
throw new ZipError('invalid-zip', `local header missing for ${entry.name}`)
|
|
348
|
+
}
|
|
349
|
+
const nameLength = header.readUInt16LE(26)
|
|
350
|
+
const extraLength = header.readUInt16LE(28)
|
|
351
|
+
return entry.headerOffset + 30 + nameLength + extraLength
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Read one entry's bytes without extracting it — the seam diagnostics and
|
|
356
|
+
* targeted verification use.
|
|
357
|
+
* @param archivePath - archive to read.
|
|
358
|
+
* @param entry - entry from {@link readZipDirectory}.
|
|
359
|
+
* @returns the uncompressed entry bytes.
|
|
360
|
+
*/
|
|
361
|
+
export async function readZipEntry(archivePath: string, entry: ZipEntry): Promise<Buffer> {
|
|
362
|
+
const offset = await dataOffsetOf(archivePath, entry)
|
|
363
|
+
const raw = Buffer.alloc(entry.compressedSize)
|
|
364
|
+
await readRange(archivePath, offset, entry.compressedSize, raw)
|
|
365
|
+
if (entry.method === 0) return raw
|
|
366
|
+
if (entry.method === LZMA_METHOD) {
|
|
367
|
+
const { properties, consumed } = readZipLzmaHeader(raw)
|
|
368
|
+
return decodeLzma(raw.subarray(consumed), properties, entry.uncompressedSize)
|
|
369
|
+
}
|
|
370
|
+
if (entry.method === 8) {
|
|
371
|
+
const expanded = await new Promise<Buffer>((resolvePromise, rejectPromise) => {
|
|
372
|
+
const chunks: Buffer[] = []
|
|
373
|
+
const inflate = createInflateRaw()
|
|
374
|
+
inflate.on('data', (chunk: Buffer) => chunks.push(chunk))
|
|
375
|
+
inflate.on('end', () => resolvePromise(Buffer.concat(chunks)))
|
|
376
|
+
inflate.on('error', rejectPromise)
|
|
377
|
+
inflate.end(raw)
|
|
378
|
+
})
|
|
379
|
+
return expanded
|
|
380
|
+
}
|
|
381
|
+
throw new ZipError('unsupported-compression', `archive entry ${entry.name} uses compression method ${String(entry.method)}`)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Extract one archive into a directory that must already be staging.
|
|
386
|
+
*
|
|
387
|
+
* Every entry is validated before its file is created, so a refused archive
|
|
388
|
+
* never leaves a tree that could be mistaken for an installation (§8.4). Writes
|
|
389
|
+
* are streamed, so memory stays bounded regardless of entry size.
|
|
390
|
+
* @param archivePath - archive to read.
|
|
391
|
+
* @param targetDir - staging directory to fill; the caller owns its lifetime.
|
|
392
|
+
* @param options - progress/cancellation/prefix/limits.
|
|
393
|
+
* @returns counts of what was written.
|
|
394
|
+
*/
|
|
395
|
+
export async function extractZip(
|
|
396
|
+
archivePath: string,
|
|
397
|
+
targetDir: string,
|
|
398
|
+
options: ExtractOptions = {},
|
|
399
|
+
): Promise<ExtractionResult> {
|
|
400
|
+
const directory = options.directory ?? await readZipDirectory(archivePath)
|
|
401
|
+
const limits: ZipLimits = { ...DEFAULT_ZIP_LIMITS, ...options.limits }
|
|
402
|
+
const total = directory.totalUncompressed
|
|
403
|
+
if (directory.entries.length > limits.maxEntries) {
|
|
404
|
+
throw new ZipError('archive-too-large', `archive declares ${String(directory.entries.length)} entries`)
|
|
405
|
+
}
|
|
406
|
+
if (total > limits.maxTotalBytes) {
|
|
407
|
+
throw new ZipError('archive-too-large', `archive expands to ${String(total)} bytes`)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const prefix = options.stripPrefix ?? ''
|
|
411
|
+
const seen = new Set<string>()
|
|
412
|
+
const root = resolve(targetDir)
|
|
413
|
+
let written = 0
|
|
414
|
+
let files = 0
|
|
415
|
+
let directories = 0
|
|
416
|
+
let completed = 0
|
|
417
|
+
|
|
418
|
+
for (const entry of directory.entries) {
|
|
419
|
+
if (options.signal?.aborted === true) throw new ZipError('cancelled', 'extraction was cancelled')
|
|
420
|
+
const raw = prefix !== '' && entry.name.startsWith(prefix) ? entry.name.slice(prefix.length) : entry.name
|
|
421
|
+
if (raw === '') continue
|
|
422
|
+
if (entry.uncompressedSize > limits.maxEntryBytes) {
|
|
423
|
+
throw new ZipError('archive-too-large', `archive entry ${entry.name} expands to ${String(entry.uncompressedSize)} bytes`)
|
|
424
|
+
}
|
|
425
|
+
const relative = safeEntrySegments(raw).join(sep)
|
|
426
|
+
if (seen.has(relative)) throw new ZipError('duplicate-entry', `archive repeats the entry ${raw}`)
|
|
427
|
+
seen.add(relative)
|
|
428
|
+
const destination = join(root, relative)
|
|
429
|
+
if (!destination.startsWith(`${root}${sep}`)) {
|
|
430
|
+
throw new ZipError('unsafe-entry', `archive entry escapes the target directory: ${raw}`)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (entry.directory) {
|
|
434
|
+
await mkdir(destination, { recursive: true })
|
|
435
|
+
directories += 1
|
|
436
|
+
completed += 1
|
|
437
|
+
continue
|
|
438
|
+
}
|
|
439
|
+
if (entry.method !== 0 && entry.method !== 8 && entry.method !== LZMA_METHOD) {
|
|
440
|
+
throw new ZipError('unsupported-compression', `archive entry ${entry.name} uses compression method ${String(entry.method)}`)
|
|
441
|
+
}
|
|
442
|
+
await mkdir(dirname(destination), { recursive: true })
|
|
443
|
+
|
|
444
|
+
const offset = await dataOffsetOf(archivePath, entry)
|
|
445
|
+
if (entry.method === LZMA_METHOD) {
|
|
446
|
+
// LZMA is decoded whole-entry by design (the format's dictionary is
|
|
447
|
+
// self-referential); every other method streams.
|
|
448
|
+
const raw = Buffer.alloc(entry.compressedSize)
|
|
449
|
+
await readRange(archivePath, offset, entry.compressedSize, raw)
|
|
450
|
+
const { properties, consumed } = readZipLzmaHeader(raw)
|
|
451
|
+
const expanded = decodeLzma(raw.subarray(consumed), properties, entry.uncompressedSize)
|
|
452
|
+
await writeFile(destination, expanded)
|
|
453
|
+
written += expanded.length
|
|
454
|
+
options.onProgress?.({
|
|
455
|
+
written, total, entries: completed, totalEntries: directory.entries.length, current: entry.name,
|
|
456
|
+
})
|
|
457
|
+
} else if (entry.compressedSize === 0) {
|
|
458
|
+
// A zero-length stream has no valid `{start, end}` pair — the real KiCad
|
|
459
|
+
// archive contains such entries (empty files, method 8), and asking Node to
|
|
460
|
+
// read `end < start` aborts the whole extraction.
|
|
461
|
+
await writeFile(destination, '')
|
|
462
|
+
} else {
|
|
463
|
+
const counter = new Transform({
|
|
464
|
+
transform: (chunk: Buffer, _encoding, callback) => {
|
|
465
|
+
written += chunk.length
|
|
466
|
+
options.onProgress?.({
|
|
467
|
+
written, total, entries: completed, totalEntries: directory.entries.length, current: entry.name,
|
|
468
|
+
})
|
|
469
|
+
callback(null, chunk)
|
|
470
|
+
},
|
|
471
|
+
})
|
|
472
|
+
const source = createReadStream(archivePath, { start: offset, end: offset + entry.compressedSize - 1 })
|
|
473
|
+
const sink = createWriteStream(destination)
|
|
474
|
+
const abort = (): void => { source.destroy(new ZipError('cancelled', 'extraction was cancelled')) }
|
|
475
|
+
options.signal?.addEventListener('abort', abort)
|
|
476
|
+
try {
|
|
477
|
+
if (entry.method === 8) await pipeline(source, createInflateRaw(), counter, sink)
|
|
478
|
+
else await pipeline(source, counter, sink)
|
|
479
|
+
} finally {
|
|
480
|
+
options.signal?.removeEventListener('abort', abort)
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const writtenBytes = await stat(destination).then(value => value.size).catch(() => -1)
|
|
484
|
+
if (writtenBytes !== entry.uncompressedSize) {
|
|
485
|
+
throw new ZipError(
|
|
486
|
+
'invalid-zip',
|
|
487
|
+
`archive entry ${entry.name} expanded to ${String(writtenBytes)} bytes, expected ${String(entry.uncompressedSize)}`,
|
|
488
|
+
)
|
|
489
|
+
}
|
|
490
|
+
files += 1
|
|
491
|
+
completed += 1
|
|
492
|
+
}
|
|
493
|
+
options.onProgress?.({ written, total, entries: completed, totalEntries: directory.entries.length, current: '' })
|
|
494
|
+
return { files, directories, bytes: written }
|
|
495
|
+
}
|