@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.
@@ -0,0 +1,384 @@
1
+ /**
2
+ * LZMA (ZIP compression method 14) decoder.
3
+ *
4
+ * The HuaQiu KiCad distribution is ~84 % LZMA: 83 548 of its 99 460 entries use
5
+ * method 14. Node's zlib has no LZMA, and the alternative — a native addon —
6
+ * cannot be rebuilt for every Electron target the desktop app ships. So the
7
+ * archive format the product actually serves decides this: without a decoder
8
+ * here, the primary download button could never finish (§8.5 steps 3–4).
9
+ *
10
+ * This is the LZMA SDK algorithm (the `LzmaDecode` state machine) specialised to
11
+ * what ZIP needs: raw LZMA1, properties from the entry header, and a known
12
+ * output length. Only the decoder is implemented — the product never writes
13
+ * archives.
14
+ *
15
+ * @module @huaqiu/hardware-artifacts/toolchain/lzma
16
+ */
17
+
18
+ /** Probability model size (11-bit probabilities). */
19
+ const BIT_MODEL_TOTAL = 2048
20
+ const MOVE_BITS = 5
21
+ const TOP_VALUE = 0xFFFFFFFF
22
+ const NORMALIZE_THRESHOLD = 0x01000000
23
+
24
+ const NUM_STATES = 12
25
+ const NUM_POS_BITS_MAX = 4
26
+ const NUM_POS_STATES_MAX = 1 << NUM_POS_BITS_MAX
27
+ const NUM_LEN_TO_POS_STATES = 4
28
+ const NUM_ALIGN_BITS = 4
29
+ const ALIGN_TABLE_SIZE = 1 << NUM_ALIGN_BITS
30
+ const START_POS_MODEL_INDEX = 4
31
+ const END_POS_MODEL_INDEX = 14
32
+ const NUM_FULL_DISTANCES = 1 << (END_POS_MODEL_INDEX / 2)
33
+ const MATCH_MIN_LEN = 2
34
+
35
+ /** LZMA1 properties as the ZIP entry header declares them. */
36
+ export interface LzmaProperties {
37
+ /** Literal context bits. */
38
+ readonly lc: number
39
+ /** Literal position bits. */
40
+ readonly lp: number
41
+ /** Position state bits. */
42
+ readonly pb: number
43
+ /** Dictionary size in bytes. */
44
+ readonly dictSize: number
45
+ }
46
+
47
+ /** A stream this decoder cannot read; never repaired, always refused. */
48
+ export class LzmaError extends Error {
49
+ constructor(readonly code: string, message: string) {
50
+ super(message)
51
+ this.name = 'LzmaError'
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Parse the 5-byte LZMA1 property block ZIP stores after its 4-byte method
57
+ * header.
58
+ * @param bytes - property bytes (usually five).
59
+ * @returns the decoded properties.
60
+ */
61
+ export function parseLzmaProperties(bytes: Buffer): LzmaProperties {
62
+ if (bytes.length < 5) throw new LzmaError('invalid-properties', 'LZMA properties are truncated')
63
+ const first = bytes[0] as number
64
+ const lc = first % 9
65
+ const lp = Math.floor(first / 9) % 5
66
+ const pb = Math.floor(first / 45)
67
+ if (pb >= NUM_POS_BITS_MAX + 1 || lp > 4 || lc > 8) {
68
+ throw new LzmaError('invalid-properties', `unsupported LZMA properties (lc=${String(lc)}, lp=${String(lp)}, pb=${String(pb)})`)
69
+ }
70
+ const dictSize = bytes.readUInt32LE(1)
71
+ return { lc, lp, pb, dictSize }
72
+ }
73
+
74
+ /** Range decoder over the compressed bytes. */
75
+ class RangeDecoder {
76
+ private range = TOP_VALUE
77
+ private code = 0
78
+ private cursor = 0
79
+
80
+ constructor(private readonly input: Buffer) {
81
+ if (input.length === 0 || input[0] !== 0) {
82
+ throw new LzmaError('invalid-stream', 'LZMA stream does not begin with a zero byte')
83
+ }
84
+ for (let index = 0; index < 5; index += 1) {
85
+ const byte = this.readByte()
86
+ this.code = ((this.code * 256) + byte) % 0x100000000
87
+ }
88
+ }
89
+
90
+ private readByte(): number {
91
+ const value = this.input[this.cursor]
92
+ if (value === undefined) {
93
+ // A truncated stream reads as zeros, exactly as the SDK's stream does;
94
+ // the output length check is what turns truncation into an error.
95
+ this.cursor += 1
96
+ return 0
97
+ }
98
+ this.cursor += 1
99
+ return value
100
+ }
101
+
102
+ /**
103
+ * Normalise the range at the *end* of a decode step.
104
+ *
105
+ * The timing matters: `LzmaDecode` scales right after the range update, so
106
+ * the next step always starts with a range of at least 2^24. Normalising at
107
+ * the start instead leaves the *previous* step's value in place, and the
108
+ * `range / 2` of an unmodelled bit then rounds away half a bit that the
109
+ * reference implementation would have kept. That single rounding is enough to
110
+ * desynchronise a real stream after a few hundred symbols — this decoder did
111
+ * exactly that until the normalisation moved here.
112
+ */
113
+ private normalize(): void {
114
+ if (this.range < NORMALIZE_THRESHOLD) {
115
+ // Doubles keep the unsigned 32-bit range exact; `<<` would coerce to int32.
116
+ this.range = (this.range * 256) % 0x100000000
117
+ this.code = ((this.code * 256) + this.readByte()) % 0x100000000
118
+ }
119
+ }
120
+
121
+ /** Decode one modelled bit. */
122
+ decodeBit(probs: Uint16Array, index: number): number {
123
+ const prob = probs[index] as number
124
+ const bound = Math.floor(this.range / 2048) * prob
125
+ let bit: number
126
+ if (this.code < bound) {
127
+ this.range = bound
128
+ probs[index] = prob + ((BIT_MODEL_TOTAL - prob) >> MOVE_BITS)
129
+ bit = 0
130
+ } else {
131
+ this.range -= bound
132
+ this.code -= bound
133
+ probs[index] = prob - (prob >> MOVE_BITS)
134
+ bit = 1
135
+ }
136
+ this.normalize()
137
+ return bit
138
+ }
139
+
140
+ /** Decode one unmodelled bit. */
141
+ decodeDirectBit(): number {
142
+ this.range = Math.floor(this.range / 2)
143
+ let bit = 0
144
+ if (this.code >= this.range) {
145
+ this.code -= this.range
146
+ bit = 1
147
+ }
148
+ this.normalize()
149
+ return bit
150
+ }
151
+
152
+ /** Decode `count` unmodelled bits, most significant first. */
153
+ decodeDirectBits(count: number): number {
154
+ let result = 0
155
+ for (let index = 0; index < count; index += 1) {
156
+ result = result * 2 + this.decodeDirectBit()
157
+ }
158
+ return result
159
+ }
160
+ }
161
+
162
+ /** One length-coder triple (low/mid/high trees behind two choices). */
163
+ class LengthDecoder {
164
+ private readonly choice = new Uint16Array(1)
165
+ private readonly choice2 = new Uint16Array(1)
166
+ private readonly low = new Uint16Array(NUM_POS_STATES_MAX * 8)
167
+ private readonly mid = new Uint16Array(NUM_POS_STATES_MAX * 8)
168
+ private readonly high = new Uint16Array(256)
169
+
170
+ constructor() {
171
+ this.reset()
172
+ }
173
+
174
+ reset(): void {
175
+ for (const table of [this.choice, this.choice2, this.low, this.mid, this.high]) {
176
+ table.fill(BIT_MODEL_TOTAL >> 1)
177
+ }
178
+ }
179
+
180
+ /** Decode one length symbol (0…273). */
181
+ decode(decoder: RangeDecoder, posState: number): number {
182
+ if (decoder.decodeBit(this.choice, 0) === 0) {
183
+ return this.tree(decoder, this.low, posState * 8, 3)
184
+ }
185
+ if (decoder.decodeBit(this.choice2, 0) === 0) {
186
+ return 8 + this.tree(decoder, this.mid, posState * 8, 3)
187
+ }
188
+ return 16 + this.tree(decoder, this.high, 0, 8)
189
+ }
190
+
191
+ private tree(decoder: RangeDecoder, probs: Uint16Array, base: number, bits: number): number {
192
+ let m = 1
193
+ for (let index = 0; index < bits; index += 1) {
194
+ m = (m << 1) + decoder.decodeBit(probs, base + m)
195
+ }
196
+ return m - (1 << bits)
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Decode one raw LZMA1 stream into exactly `outputSize` bytes.
202
+ * @param compressed - stream bytes after the ZIP method header and properties.
203
+ * @param properties - parsed LZMA1 properties.
204
+ * @param outputSize - uncompressed length the central directory declared.
205
+ * @returns the decompressed bytes.
206
+ */
207
+ export function decodeLzma(compressed: Buffer, properties: LzmaProperties, outputSize: number): Buffer {
208
+ const { lc, lp, pb } = properties
209
+ const decoder = new RangeDecoder(compressed)
210
+ const literalProbs = new Uint16Array(0x300 * (1 << (lc + lp)))
211
+ const isMatch = new Uint16Array(NUM_STATES * NUM_POS_STATES_MAX)
212
+ const isRep = new Uint16Array(NUM_STATES)
213
+ const isRepG0 = new Uint16Array(NUM_STATES)
214
+ const isRepG1 = new Uint16Array(NUM_STATES)
215
+ const isRepG2 = new Uint16Array(NUM_STATES)
216
+ const isRep0Long = new Uint16Array(NUM_STATES * NUM_POS_STATES_MAX)
217
+ const posSlot = new Uint16Array(NUM_LEN_TO_POS_STATES * 64)
218
+ const specPos = new Uint16Array(NUM_FULL_DISTANCES - END_POS_MODEL_INDEX)
219
+ const align = new Uint16Array(ALIGN_TABLE_SIZE)
220
+ for (const table of [literalProbs, isMatch, isRep, isRepG0, isRepG1, isRepG2, isRep0Long, posSlot, specPos, align]) {
221
+ table.fill(BIT_MODEL_TOTAL >> 1)
222
+ }
223
+ const lenDecoder = new LengthDecoder()
224
+ const repLenDecoder = new LengthDecoder()
225
+
226
+ const output = Buffer.alloc(outputSize)
227
+ const posStateMask = (1 << pb) - 1
228
+ const literalPosMask = (1 << lp) - 1
229
+
230
+ let state = 0
231
+ let rep0 = 0
232
+ let rep1 = 0
233
+ let rep2 = 0
234
+ let rep3 = 0
235
+ let pos = 0
236
+
237
+ const isMatchIndex = (state_: number, posState: number): number => state_ * NUM_POS_STATES_MAX + posState
238
+
239
+ const decodeLiteral = (): void => {
240
+ const prevByte = pos > 0 ? (output[pos - 1] as number) : 0
241
+ const literalState = (((pos & literalPosMask) << lc) + (prevByte >> (8 - lc))) * 0x300
242
+ let symbol = 1
243
+ if (state >= 7) {
244
+ // A literal in a match state is coded against the byte at the match
245
+ // distance, which narrows the probability context per decoded bit.
246
+ const matchByte = output[pos - rep0 - 1]
247
+ if (matchByte === undefined) throw new LzmaError('invalid-stream', `literal match distance is out of range at pos ${String(pos)}`)
248
+ let match = matchByte
249
+ do {
250
+ const matchBit = (match >> 7) & 1
251
+ match = (match << 1) & 0xFF
252
+ const bit = decoder.decodeBit(literalProbs, literalState + ((1 + matchBit) << 8) + symbol)
253
+ symbol = (symbol << 1) | bit
254
+ if (matchBit !== bit) break
255
+ } while (symbol < 0x100)
256
+ }
257
+ while (symbol < 0x100) {
258
+ symbol = (symbol << 1) | decoder.decodeBit(literalProbs, literalState + symbol)
259
+ }
260
+ output[pos] = symbol & 0xFF
261
+ pos += 1
262
+ state = state < 4 ? 0 : state < 10 ? state - 3 : state - 6
263
+ }
264
+
265
+ /**
266
+ * Decode the distance of a new match.
267
+ *
268
+ * Distances are coded in three bands: slots 0–3 are the distance itself,
269
+ * slots 4–13 use a reverse bit tree whose base depends on the slot, and
270
+ * slots 14+ use unmodelled "direct" bits plus the 4-bit align tree. The align
271
+ * tree is reverse-decoded from index 1 — starting at 16 reads a probability
272
+ * that belongs to another model.
273
+ */
274
+ const decodeDistance = (length: number): number => {
275
+ const lenToPosState = length - MATCH_MIN_LEN < NUM_LEN_TO_POS_STATES ? length - MATCH_MIN_LEN : NUM_LEN_TO_POS_STATES - 1
276
+ const base = lenToPosState * 64
277
+ let m = 1
278
+ for (let index = 0; index < 6; index += 1) m = (m << 1) + decoder.decodeBit(posSlot, base + m)
279
+ const slot = m - 64
280
+ if (slot < START_POS_MODEL_INDEX) return slot
281
+ const directBits = (slot >> 1) - 1
282
+ let distance = (2 | (slot & 1)) * (1 << directBits)
283
+ if (slot < END_POS_MODEL_INDEX) {
284
+ return distance + reverseTree(specPos, distance - slot - 1, directBits)
285
+ }
286
+ distance += decoder.decodeDirectBits(directBits - NUM_ALIGN_BITS) * ALIGN_TABLE_SIZE
287
+ return distance + reverseTree(align, 0, NUM_ALIGN_BITS)
288
+ }
289
+
290
+ /** Reverse bit-tree decode: the first decoded bit is the least significant. */
291
+ const reverseTree = (probs: Uint16Array, base: number, bits: number): number => {
292
+ let m = 1
293
+ let symbol = 0
294
+ for (let index = 0; index < bits; index += 1) {
295
+ const bit = decoder.decodeBit(probs, base + m)
296
+ m = (m << 1) | bit
297
+ symbol |= bit << index
298
+ }
299
+ return symbol
300
+ }
301
+
302
+ while (pos < outputSize) {
303
+ const posState = pos & posStateMask
304
+ if (decoder.decodeBit(isMatch, isMatchIndex(state, posState)) === 0) {
305
+ decodeLiteral()
306
+ continue
307
+ }
308
+ let length: number
309
+ if (decoder.decodeBit(isRep, state) === 0) {
310
+ // A new match: distances shift down the rep chain, then the distance
311
+ // itself is coded with a model selected by the match length.
312
+ rep3 = rep2
313
+ rep2 = rep1
314
+ rep1 = rep0
315
+ length = lenDecoder.decode(decoder, posState) + MATCH_MIN_LEN
316
+ state = state < 7 ? 7 : 10
317
+ rep0 = decodeDistance(length)
318
+ } else {
319
+ if (decoder.decodeBit(isRepG0, state) === 0) {
320
+ if (decoder.decodeBit(isRep0Long, isMatchIndex(state, posState)) === 0) {
321
+ // A "short rep": one byte at the current distance.
322
+ state = state < 7 ? 9 : 11
323
+ const source = output[pos - rep0 - 1]
324
+ if (source === undefined) throw new LzmaError('invalid-stream', `short rep distance is out of range at pos ${String(pos)}`)
325
+ output[pos] = source
326
+ pos += 1
327
+ continue
328
+ }
329
+ } else {
330
+ // A repeated distance: pick one of the three older entries and promote it.
331
+ let distance: number
332
+ if (decoder.decodeBit(isRepG1, state) === 0) {
333
+ distance = rep1
334
+ } else {
335
+ if (decoder.decodeBit(isRepG2, state) === 0) {
336
+ distance = rep2
337
+ } else {
338
+ distance = rep3
339
+ rep3 = rep2
340
+ }
341
+ rep2 = rep1
342
+ }
343
+ rep1 = rep0
344
+ rep0 = distance
345
+ }
346
+ length = repLenDecoder.decode(decoder, posState) + MATCH_MIN_LEN
347
+ state = state < 7 ? 8 : 11
348
+ }
349
+ // Copy the match byte by byte: LZMA allows overlapping copies, so the output
350
+ // may be both source and destination.
351
+ for (let index = 0; index < length && pos < outputSize; index += 1) {
352
+ const source = output[pos - rep0 - 1]
353
+ if (source === undefined) throw new LzmaError('invalid-stream', `match distance is out of range at pos ${String(pos)} (rep0 ${String(rep0)})`)
354
+ output[pos] = source
355
+ pos += 1
356
+ }
357
+ }
358
+ return output
359
+ }
360
+
361
+ /** Size of the method-14 header ZIP puts before its LZMA properties. */
362
+ export const LZMA_ZIP_HEADER_BYTES = 4
363
+
364
+ /**
365
+ * Read an entry's LZMA properties out of its data header.
366
+ * @param header - the first bytes of the entry data.
367
+ * @returns the properties and the number of bytes the header consumed.
368
+ */
369
+ export function readZipLzmaHeader(header: Buffer): { properties: LzmaProperties; consumed: number } {
370
+ if (header.length < LZMA_ZIP_HEADER_BYTES + 5) {
371
+ throw new LzmaError('invalid-stream', 'LZMA entry header is truncated')
372
+ }
373
+ const propertiesSize = header.readUInt16LE(2)
374
+ if (propertiesSize < 5 || propertiesSize > 64) {
375
+ throw new LzmaError('invalid-stream', `LZMA properties size ${String(propertiesSize)} is not supported`)
376
+ }
377
+ if (header.length < LZMA_ZIP_HEADER_BYTES + propertiesSize) {
378
+ throw new LzmaError('invalid-stream', 'LZMA properties are truncated')
379
+ }
380
+ return {
381
+ properties: parseLzmaProperties(header.subarray(LZMA_ZIP_HEADER_BYTES, LZMA_ZIP_HEADER_BYTES + propertiesSize)),
382
+ consumed: LZMA_ZIP_HEADER_BYTES + propertiesSize,
383
+ }
384
+ }