@zumer/snapdom-pdf 1.0.1 → 1.0.2

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,589 @@
1
+ /**
2
+ * A Brotli decoder (RFC 7932), decode only.
3
+ *
4
+ * It is here for one caller: `woff2.js`. WOFF2 is the format nearly every web font
5
+ * is served in, its tables sit behind ONE Brotli stream, and no browser hands a
6
+ * page a Brotli decoder — `DecompressionStream` does gzip and deflate, and
7
+ * `'brotli'` threw in Chromium 140 when this was written (2026-11-22). Without
8
+ * this, a font the page itself is drawn with could not travel in the file.
9
+ *
10
+ * It is loaded lazily (`writer/font.js` imports `woff2.js` with `import()` and only
11
+ * when a WOFF2 arrives), so an export that never meets one never pays for it.
12
+ *
13
+ * Shape, on purpose:
14
+ *
15
+ * - **The whole output is one growing array.** A back-reference is then a plain
16
+ * read `distance` bytes behind the write position; the window only bounds how
17
+ * far back the stream may ask for, it is not a ring to maintain.
18
+ * - **Prefix codes are decoded bit by bit** from a canonical table (the `puff.c`
19
+ * method). A font is a few hundred kB; MEASURED on the 37 kB Roboto latin
20
+ * subset this decodes in a few milliseconds, and a lookup table would be more
21
+ * code to get wrong for nothing a capture would notice.
22
+ * - **The static dictionary is not loaded until a stream asks for it.** It is
23
+ * 122,784 bytes (58 kB deflated, in `brotli-dictionary.js`). Binary tables
24
+ * almost never match English words, but a `name` table's copyright line can, so
25
+ * the decoder runs without it first and only on a dictionary reference inflates
26
+ * it and starts again.
27
+ *
28
+ * Checked against Node's own `zlib.brotliDecompressSync` (the reference C decoder):
29
+ * every quality and window size on text, binary and mixed input, and one
30
+ * hand-built stream per dictionary transform, all 121 (`test/verify-woff2.mjs`).
31
+ */
32
+
33
+ /** The order code-length code lengths arrive in (RFC 7932 §3.5). */
34
+ const CODE_LENGTH_ORDER = [1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15]
35
+
36
+ /** Block count code -> [base, extra bits] (§6). */
37
+ const BLOCK_BASE = [1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625]
38
+ const BLOCK_BITS = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24]
39
+
40
+ /** Insert length code -> [base, extra bits] (§5). */
41
+ const INSERT_BASE = [0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594]
42
+ const INSERT_BITS = [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24]
43
+
44
+ /** Copy length code -> [base, extra bits] (§5). */
45
+ const COPY_BASE = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118]
46
+ const COPY_BITS = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24]
47
+
48
+ /** Which third of the insert and of the copy codes each 64-symbol range of a command uses. */
49
+ const INSERT_RANGE = [0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16]
50
+ const COPY_RANGE = [0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16]
51
+
52
+ /** Distance codes 0..15: which past distance, and how far off it (§4). */
53
+ const SHORT_INDEX = [3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
54
+ const SHORT_OFFSET = [0, 0, 0, 0, -1, 1, -2, 2, -3, 3, -1, 1, -2, 2, -3, 3]
55
+
56
+ /** Static dictionary: bits of word index per word length, and where each length starts. */
57
+ const DICT_BITS = [0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5]
58
+ const DICT_OFFSET = (() => {
59
+ const at = new Array(25).fill(0)
60
+ for (let len = 4; len < 24; len++) at[len + 1] = at[len] + (len << DICT_BITS[len])
61
+ return at
62
+ })()
63
+ export const DICTIONARY_SIZE = DICT_OFFSET[24] + (24 << DICT_BITS[24]) // 122784
64
+
65
+ // ——— literal context lookup (§7.1) ———
66
+
67
+ const LUT0 = new Uint8Array(256)
68
+ const LUT1 = new Uint8Array(256)
69
+ const LUT2 = new Uint8Array(256)
70
+ ;(() => {
71
+ const row = [
72
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 4, 0, 0,
73
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74
+ 8, 12, 16, 12, 12, 20, 12, 16, 24, 28, 12, 12, 32, 12, 36, 12,
75
+ 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 32, 32, 24, 40, 28, 12,
76
+ 12, 48, 52, 52, 52, 48, 52, 52, 52, 48, 52, 52, 52, 52, 52, 48,
77
+ 52, 52, 52, 52, 52, 48, 52, 52, 52, 52, 52, 24, 12, 28, 12, 12,
78
+ 12, 56, 60, 60, 60, 56, 60, 60, 60, 56, 60, 60, 60, 60, 60, 56,
79
+ 60, 60, 60, 60, 60, 56, 60, 60, 60, 60, 60, 24, 12, 28, 12, 0,
80
+ ]
81
+ for (let i = 0; i < 128; i++) LUT0[i] = row[i]
82
+ for (let i = 128; i < 192; i++) LUT0[i] = i & 1
83
+ for (let i = 192; i < 256; i++) LUT0[i] = 2 + (i & 1)
84
+
85
+ const second = [
86
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
89
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1,
90
+ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
91
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1,
92
+ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
93
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 0,
94
+ ]
95
+ for (let i = 0; i < 128; i++) LUT1[i] = second[i]
96
+ // Lead bytes of two-byte sequences (192..223) are 0; only three- and four-byte leads are 2.
97
+ for (let i = 224; i < 256; i++) LUT1[i] = 2
98
+
99
+ for (let i = 1; i < 16; i++) LUT2[i] = 1
100
+ for (let i = 16; i < 64; i++) LUT2[i] = 2
101
+ for (let i = 64; i < 128; i++) LUT2[i] = 3
102
+ for (let i = 128; i < 192; i++) LUT2[i] = 4
103
+ for (let i = 192; i < 240; i++) LUT2[i] = 5
104
+ for (let i = 240; i < 255; i++) LUT2[i] = 6
105
+ LUT2[255] = 7
106
+ })()
107
+
108
+ // ——— dictionary transforms (Appendix B) ———
109
+
110
+ const ID = 0 // identity; 1..9 = omit last N; 12..20 = omit first N (N = type - 11)
111
+ const UF = 10 // uppercase first
112
+ const UA = 11 // uppercase all
113
+ const OL = (n) => n
114
+ const OF = (n) => 11 + n
115
+
116
+ /** [prefix, type, suffix], in the order of RFC 7932 Appendix B. */
117
+ const TRANSFORMS = [
118
+ ['', ID, ''], ['', ID, ' '], [' ', ID, ' '], ['', OF(1), ''], ['', UF, ' '],
119
+ ['', ID, ' the '], [' ', ID, ''], ['s ', ID, ' '], ['', ID, ' of '], ['', UF, ''],
120
+ ['', ID, ' and '], ['', OF(2), ''], ['', OL(1), ''], [', ', ID, ' '], ['', ID, ', '],
121
+ [' ', UF, ' '], ['', ID, ' in '], ['', ID, ' to '], ['e ', ID, ' '], ['', ID, '"'],
122
+ ['', ID, '.'], ['', ID, '">'], ['', ID, '\n'], ['', OL(3), ''], ['', ID, ']'],
123
+ ['', ID, ' for '], ['', OF(3), ''], ['', OL(2), ''], ['', ID, ' a '], ['', ID, ' that '],
124
+ [' ', UF, ''], ['', ID, '. '], ['.', ID, ''], [' ', ID, ', '], ['', OF(4), ''],
125
+ ['', ID, ' with '], ['', ID, "'"], ['', ID, ' from '], ['', ID, ' by '], ['', OF(5), ''],
126
+ ['', OF(6), ''], [' the ', ID, ''], ['', OL(4), ''], ['', ID, '. The '], ['', UA, ''],
127
+ ['', ID, ' on '], ['', ID, ' as '], ['', ID, ' is '], ['', OL(7), ''], ['', OL(1), 'ing '],
128
+ ['', ID, '\n\t'], ['', ID, ':'], [' ', ID, '. '], ['', ID, 'ed '], ['', OF(9), ''],
129
+ ['', OF(7), ''], ['', OL(6), ''], ['', ID, '('], ['', UF, ', '], ['', OL(8), ''],
130
+ ['', ID, ' at '], ['', ID, 'ly '], [' the ', ID, ' of '], ['', OL(5), ''], ['', OL(9), ''],
131
+ [' ', UF, ', '], ['', UF, '"'], ['.', ID, '('], ['', UA, ' '], ['', UF, '">'],
132
+ ['', ID, '="'], [' ', ID, '.'], ['.com/', ID, ''], [' the ', ID, ' of the '], ['', UF, "'"],
133
+ ['', ID, '. This '], ['', ID, ','], ['.', ID, ' '], ['', UF, '('], ['', UF, '.'],
134
+ ['', ID, ' not '], [' ', ID, '="'], ['', ID, 'er '], [' ', UA, ' '], ['', ID, 'al '],
135
+ [' ', UA, ''], ['', ID, "='"], ['', UA, '"'], ['', UF, '. '], [' ', ID, '('],
136
+ ['', ID, 'ful '], [' ', UF, '. '], ['', ID, 'ive '], ['', ID, 'less '], ['', UA, "'"],
137
+ ['', ID, 'est '], [' ', UF, '.'], ['', UA, '">'], [' ', ID, "='"], ['', UF, ','],
138
+ ['', ID, 'ize '], ['', UA, '.'], [' ', ID, ''], [' ', ID, ','], ['', UF, '="'],
139
+ ['', UA, '="'], ['', ID, 'ous '], ['', UA, ', '], ['', UF, "='"], [' ', UF, ','],
140
+ [' ', UA, '="'], [' ', UA, ', '], ['', UA, ','], ['', UA, '('], ['', UA, '. '],
141
+ [' ', UA, '.'], ['', UA, "='"], [' ', UA, '. '], [' ', UF, '="'], [' ', UA, "='"],
142
+ [' ', UF, "='"],
143
+ ].map(([prefix, type, suffix]) => ({
144
+ prefix: Uint8Array.from(prefix, (c) => c.charCodeAt(0)),
145
+ type,
146
+ suffix: Uint8Array.from(suffix, (c) => c.charCodeAt(0)),
147
+ }))
148
+
149
+ /** Brotli's own notion of upper case, on UTF-8 bytes in place. Returns how many it consumed. */
150
+ function upperCase (out, at) {
151
+ const c = out[at]
152
+ if (c < 0xc0) {
153
+ if (c >= 97 && c <= 122) out[at] ^= 32
154
+ return 1
155
+ }
156
+ if (c < 0xe0) {
157
+ out[at + 1] ^= 32
158
+ return 2
159
+ }
160
+ out[at + 2] ^= 5
161
+ return 3
162
+ }
163
+
164
+ // ——— the decoder ———
165
+
166
+ /** Raised when a stream reaches into the static dictionary and none was given. */
167
+ export class NeedsDictionary extends Error {}
168
+
169
+ class Decoder {
170
+ constructor (input, dictionary, sizeHint) {
171
+ this.input = input
172
+ this.at = 0
173
+ this.acc = 0
174
+ this.have = 0
175
+ this.dictionary = dictionary || null
176
+ this.out = new Uint8Array(Math.max(1024, sizeHint || input.length * 4))
177
+ this.pos = 0
178
+ }
179
+
180
+ /** `n` bits (0..24), the first one read in the lowest position. */
181
+ bits (n) {
182
+ if (n === 0) return 0
183
+ while (this.have < n) {
184
+ if (this.at >= this.input.length) {
185
+ // A stream may end mid-byte; reading PAST its last byte is corruption.
186
+ if (this.at > this.input.length + 3) throw new Error('brotli: the stream ends before its data does')
187
+ this.at++
188
+ this.have += 8
189
+ continue
190
+ }
191
+ this.acc = (this.acc | (this.input[this.at++] << this.have)) >>> 0
192
+ this.have += 8
193
+ }
194
+ const value = this.acc & ((1 << n) - 1)
195
+ this.acc >>>= n
196
+ this.have -= n
197
+ return value
198
+ }
199
+
200
+ alignToByte () {
201
+ const drop = this.have & 7
202
+ if (drop) this.bits(drop)
203
+ }
204
+
205
+ room (n) {
206
+ if (this.pos + n <= this.out.length) return
207
+ let size = this.out.length * 2
208
+ while (size < this.pos + n) size *= 2
209
+ const grown = new Uint8Array(size)
210
+ grown.set(this.out.subarray(0, this.pos))
211
+ this.out = grown
212
+ }
213
+
214
+ /** A canonical prefix code over `lengths` (0 = symbol unused). */
215
+ build (lengths) {
216
+ const count = new Uint16Array(16)
217
+ let used = 0
218
+ let only = -1
219
+ for (let s = 0; s < lengths.length; s++) {
220
+ if (lengths[s]) { count[lengths[s]]++; used++; only = s }
221
+ }
222
+ if (used === 0) throw new Error('brotli: a prefix code with no symbols')
223
+ if (used === 1) return { single: only }
224
+ const offset = new Uint16Array(16)
225
+ for (let len = 1; len < 15; len++) offset[len + 1] = offset[len] + count[len]
226
+ const symbol = new Uint16Array(used)
227
+ for (let s = 0; s < lengths.length; s++) {
228
+ if (lengths[s]) symbol[offset[lengths[s]]++] = s
229
+ }
230
+ return { single: -1, count, symbol }
231
+ }
232
+
233
+ /** One symbol of `code`, most significant code bit first. */
234
+ symbol (code) {
235
+ if (code.single >= 0) return code.single
236
+ let value = 0
237
+ let first = 0
238
+ let index = 0
239
+ for (let len = 1; len <= 15; len++) {
240
+ value |= this.bits(1)
241
+ const n = code.count[len]
242
+ if (value - n < first) return code.symbol[index + (value - first)]
243
+ index += n
244
+ first = (first + n) << 1
245
+ value <<= 1
246
+ }
247
+ throw new Error('brotli: a code longer than 15 bits')
248
+ }
249
+
250
+ /** §3.4 / §3.5: a prefix code description for an alphabet of `size` symbols. */
251
+ prefixCode (size) {
252
+ const skip = this.bits(2)
253
+ const lengths = new Uint8Array(size)
254
+ if (skip === 1) {
255
+ const n = this.bits(2) + 1
256
+ let width = 0
257
+ for (let v = size - 1; v; v >>= 1) width++
258
+ const symbols = []
259
+ for (let i = 0; i < n; i++) {
260
+ const s = this.bits(width)
261
+ if (s >= size || symbols.includes(s)) throw new Error('brotli: a simple prefix code names a symbol twice or out of range')
262
+ symbols.push(s)
263
+ }
264
+ if (n === 1) return { single: symbols[0] }
265
+ if (n === 2) { lengths[symbols[0]] = 1; lengths[symbols[1]] = 1 }
266
+ if (n === 3) { lengths[symbols[0]] = 1; lengths[symbols[1]] = 2; lengths[symbols[2]] = 2 }
267
+ if (n === 4) {
268
+ if (this.bits(1)) { lengths[symbols[0]] = 1; lengths[symbols[1]] = 2; lengths[symbols[2]] = 3; lengths[symbols[3]] = 3 } else for (const s of symbols) lengths[s] = 2
269
+ }
270
+ return this.build(lengths)
271
+ }
272
+
273
+ const codeLengths = new Uint8Array(18)
274
+ let space = 32
275
+ let nonZero = 0
276
+ for (let i = skip; i < 18 && space > 0; i++) {
277
+ let v
278
+ if (!this.bits(1)) v = this.bits(1) ? 3 : 0
279
+ else if (!this.bits(1)) v = 4
280
+ else if (!this.bits(1)) v = 2
281
+ else v = this.bits(1) ? 5 : 1
282
+ codeLengths[CODE_LENGTH_ORDER[i]] = v
283
+ if (v) { space -= 32 >> v; nonZero++ }
284
+ }
285
+ if (nonZero !== 1 && space !== 0) throw new Error('brotli: the code-length code is not a complete prefix code')
286
+ const lengthCode = this.build(codeLengths)
287
+
288
+ let i = 0
289
+ let previous = 8
290
+ let repeat = 0
291
+ let repeated = 0
292
+ let left = 32768
293
+ while (i < size && left > 0) {
294
+ const s = this.symbol(lengthCode)
295
+ if (s < 16) {
296
+ lengths[i++] = s
297
+ repeat = 0
298
+ if (s) { previous = s; left -= 32768 >> s }
299
+ continue
300
+ }
301
+ const extra = s === 16 ? 2 : 3
302
+ const value = s === 16 ? previous : 0
303
+ if (repeated !== value) { repeat = 0; repeated = value }
304
+ const before = repeat
305
+ if (repeat > 0) repeat = (repeat - 2) << extra
306
+ repeat += this.bits(extra) + 3
307
+ const more = repeat - before
308
+ if (i + more > size) throw new Error('brotli: a code-length run passes the end of its alphabet')
309
+ for (let k = 0; k < more; k++) lengths[i++] = value
310
+ if (value) left -= more << (15 - value)
311
+ }
312
+ if (left !== 0) throw new Error('brotli: a prefix code is not complete')
313
+ return this.build(lengths)
314
+ }
315
+
316
+ /** §9.2: 1..256, in 1 to 11 bits. */
317
+ count256 () {
318
+ if (!this.bits(1)) return 1
319
+ const n = this.bits(3)
320
+ return (1 << n) + 1 + this.bits(n)
321
+ }
322
+
323
+ blockCount (code) {
324
+ const c = this.symbol(code)
325
+ return BLOCK_BASE[c] + this.bits(BLOCK_BITS[c])
326
+ }
327
+
328
+ /** §7.3. */
329
+ contextMap (size, trees) {
330
+ const map = new Uint8Array(size)
331
+ if (trees < 2) return map
332
+ const runMax = this.bits(1) ? this.bits(4) + 1 : 0
333
+ const code = this.prefixCode(trees + runMax)
334
+ for (let i = 0; i < size;) {
335
+ const s = this.symbol(code)
336
+ if (s === 0) { map[i++] = 0; continue }
337
+ if (s <= runMax) {
338
+ const run = (1 << s) + this.bits(s)
339
+ if (i + run > size) throw new Error('brotli: a context map run passes its end')
340
+ i += run // already zero
341
+ continue
342
+ }
343
+ map[i++] = s - runMax
344
+ }
345
+ if (this.bits(1)) {
346
+ // inverse move-to-front
347
+ const order = new Uint8Array(256)
348
+ for (let k = 0; k < 256; k++) order[k] = k
349
+ for (let k = 0; k < size; k++) {
350
+ const index = map[k]
351
+ const value = order[index]
352
+ map[k] = value
353
+ for (let j = index; j > 0; j--) order[j] = order[j - 1]
354
+ order[0] = value
355
+ }
356
+ }
357
+ return map
358
+ }
359
+
360
+ /** One block category (literals, commands or distances): its type and count codes and state. */
361
+ category () {
362
+ const types = this.count256()
363
+ const state = { types, type: 0, previous: 1, typeCode: null, countCode: null, left: 16777216 }
364
+ if (types >= 2) {
365
+ state.typeCode = this.prefixCode(types + 2)
366
+ state.countCode = this.prefixCode(26)
367
+ state.left = this.blockCount(state.countCode)
368
+ }
369
+ return state
370
+ }
371
+
372
+ switchBlock (state) {
373
+ const s = this.symbol(state.typeCode)
374
+ let next
375
+ if (s === 0) next = state.previous
376
+ else if (s === 1) next = state.type + 1
377
+ else next = s - 2
378
+ if (next >= state.types) next -= state.types
379
+ state.previous = state.type
380
+ state.type = next
381
+ state.left = this.blockCount(state.countCode)
382
+ }
383
+
384
+ run () {
385
+ // §9.1: the window
386
+ let wbits
387
+ if (!this.bits(1)) wbits = 16
388
+ else {
389
+ const n = this.bits(3)
390
+ if (n) wbits = 17 + n
391
+ else {
392
+ const m = this.bits(3)
393
+ if (m === 0) wbits = 17
394
+ else if (m === 1) throw new Error('brotli: large-window streams are not WOFF2')
395
+ else wbits = 8 + m
396
+ }
397
+ }
398
+ const window = (1 << wbits) - 16
399
+ const ring = [16, 15, 11, 4]
400
+ let ringAt = 0
401
+
402
+ for (;;) {
403
+ const last = this.bits(1)
404
+ if (last && this.bits(1)) break // ISLASTEMPTY
405
+ const nibbleCode = this.bits(2)
406
+ if (nibbleCode === 3) {
407
+ // a metadata block: skipped
408
+ if (this.bits(1)) throw new Error('brotli: a reserved bit is set')
409
+ const skipBytes = this.bits(2)
410
+ let skip = 0
411
+ for (let i = 0; i < skipBytes; i++) skip |= this.bits(8) << (8 * i)
412
+ if (skipBytes) skip += 1
413
+ this.alignToByte()
414
+ for (let i = 0; i < skip; i++) this.bits(8)
415
+ if (last) break
416
+ continue
417
+ }
418
+ let left = 0
419
+ const nibbles = nibbleCode + 4
420
+ for (let i = 0; i < nibbles; i++) left |= this.bits(4) << (4 * i)
421
+ left += 1
422
+
423
+ if (!last && this.bits(1)) {
424
+ // uncompressed
425
+ this.alignToByte()
426
+ this.room(left)
427
+ for (let i = 0; i < left; i++) this.out[this.pos++] = this.bits(8)
428
+ continue
429
+ }
430
+
431
+ const L = this.category()
432
+ const I = this.category()
433
+ const D = this.category()
434
+ const postfix = this.bits(2)
435
+ const direct = this.bits(4) << postfix
436
+ const postfixMask = (1 << postfix) - 1
437
+ const modes = new Uint8Array(L.types)
438
+ for (let i = 0; i < L.types; i++) modes[i] = this.bits(2)
439
+ const literalTrees = this.count256()
440
+ const literalMap = this.contextMap(64 * L.types, literalTrees)
441
+ const distanceTrees = this.count256()
442
+ const distanceMap = this.contextMap(4 * D.types, distanceTrees)
443
+ const literalCodes = []
444
+ for (let i = 0; i < literalTrees; i++) literalCodes.push(this.prefixCode(256))
445
+ const commandCodes = []
446
+ for (let i = 0; i < I.types; i++) commandCodes.push(this.prefixCode(704))
447
+ const distanceCodes = []
448
+ for (let i = 0; i < distanceTrees; i++) distanceCodes.push(this.prefixCode(16 + direct + (48 << postfix)))
449
+
450
+ while (left > 0) {
451
+ if (I.left === 0) this.switchBlock(I)
452
+ I.left--
453
+ const command = this.symbol(commandCodes[I.type])
454
+ const range = command >> 6
455
+ const insertCode = INSERT_RANGE[range] + ((command >> 3) & 7)
456
+ const copyCode = COPY_RANGE[range] + (command & 7)
457
+ const insert = INSERT_BASE[insertCode] + this.bits(INSERT_BITS[insertCode])
458
+ const copy = COPY_BASE[copyCode] + this.bits(COPY_BITS[copyCode])
459
+
460
+ if (insert > left) throw new Error('brotli: more literals than the meta-block has left')
461
+ this.room(insert)
462
+ for (let k = 0; k < insert; k++) {
463
+ if (L.left === 0) this.switchBlock(L)
464
+ L.left--
465
+ const p1 = this.pos > 0 ? this.out[this.pos - 1] : 0
466
+ const p2 = this.pos > 1 ? this.out[this.pos - 2] : 0
467
+ const mode = modes[L.type]
468
+ let context
469
+ if (mode === 0) context = p1 & 0x3f
470
+ else if (mode === 1) context = p1 >> 2
471
+ else if (mode === 2) context = LUT0[p1] | LUT1[p2]
472
+ else context = (LUT2[p1] << 3) | LUT2[p2]
473
+ this.out[this.pos++] = this.symbol(literalCodes[literalMap[L.type * 64 + context]])
474
+ }
475
+ left -= insert
476
+ if (left === 0) break
477
+
478
+ let distance
479
+ let push = true
480
+ if (command < 128) {
481
+ distance = ring[(ringAt + 3) & 3]
482
+ push = false
483
+ } else {
484
+ if (D.left === 0) this.switchBlock(D)
485
+ D.left--
486
+ const context = copy > 4 ? 3 : copy - 2
487
+ const code = this.symbol(distanceCodes[distanceMap[D.type * 4 + context]])
488
+ if (code < 16) {
489
+ distance = ring[(ringAt + SHORT_INDEX[code]) & 3] + SHORT_OFFSET[code]
490
+ if (code === 0) push = false
491
+ } else if (code < 16 + direct) {
492
+ distance = code - 15
493
+ } else {
494
+ const v = code - direct - 16
495
+ const nbits = 1 + (v >> (postfix + 1))
496
+ const extra = this.bits(nbits)
497
+ const high = v >> postfix
498
+ const low = v & postfixMask
499
+ const offset = ((2 + (high & 1)) << nbits) - 4
500
+ distance = ((offset + extra) << postfix) + low + direct + 1
501
+ }
502
+ }
503
+ if (!(distance > 0)) throw new Error('brotli: a distance of zero or less')
504
+
505
+ const reach = Math.min(window, this.pos)
506
+ if (distance > reach) {
507
+ // §8: a word of the static dictionary, transformed
508
+ if (copy < 4 || copy > 24) throw new Error('brotli: a dictionary reference of impossible length')
509
+ if (!this.dictionary) throw new NeedsDictionary('brotli: the stream uses the static dictionary')
510
+ const id = distance - reach - 1
511
+ const shift = DICT_BITS[copy]
512
+ const index = id & ((1 << shift) - 1)
513
+ const transform = TRANSFORMS[id >> shift]
514
+ if (!transform) throw new Error('brotli: a dictionary transform that does not exist')
515
+ const from = DICT_OFFSET[copy] + index * copy
516
+ let start = from
517
+ let length = copy
518
+ const t = transform.type
519
+ if (t >= 1 && t <= 9) length = Math.max(0, length - t)
520
+ else if (t >= 12) { const cut = Math.min(length, t - 11); start += cut; length -= cut }
521
+ this.room(transform.prefix.length + length + transform.suffix.length)
522
+ this.out.set(transform.prefix, this.pos)
523
+ let at = this.pos + transform.prefix.length
524
+ const word = at
525
+ for (let k = 0; k < length; k++) this.out[at++] = this.dictionary[start + k]
526
+ if (t === UF && length > 0) upperCase(this.out, word)
527
+ else if (t === UA) {
528
+ for (let k = 0; k < length;) k += upperCase(this.out, word + k)
529
+ }
530
+ this.out.set(transform.suffix, at)
531
+ at += transform.suffix.length
532
+ const written = at - this.pos
533
+ this.pos = at
534
+ left -= written
535
+ if (left < 0) throw new Error('brotli: a dictionary word runs past the meta-block')
536
+ continue
537
+ }
538
+
539
+ if (push) { ring[ringAt & 3] = distance; ringAt++ }
540
+ if (copy > left) throw new Error('brotli: a copy runs past the meta-block')
541
+ this.room(copy)
542
+ // Byte by byte on purpose: an overlapping copy repeats what it has just written.
543
+ for (let k = 0; k < copy; k++) { this.out[this.pos] = this.out[this.pos - distance]; this.pos++ }
544
+ left -= copy
545
+ }
546
+ if (last) break
547
+ }
548
+ return this.out.subarray(0, this.pos)
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Decode one Brotli stream.
554
+ *
555
+ * @param {Uint8Array} input
556
+ * @param {object} [options]
557
+ * @param {Uint8Array|null} [options.dictionary] the 122,784-byte static dictionary.
558
+ * Without it a stream that references it throws `NeedsDictionary`.
559
+ * @param {number} [options.sizeHint] the decoded size when the caller knows it
560
+ * @returns {Uint8Array}
561
+ */
562
+ export function brotliDecodeSync (input, { dictionary = null, sizeHint = 0 } = {}) {
563
+ if (dictionary && dictionary.length !== DICTIONARY_SIZE) {
564
+ throw new Error(`brotli: the static dictionary is ${dictionary.length} bytes, not ${DICTIONARY_SIZE}`)
565
+ }
566
+ return new Decoder(input, dictionary, sizeHint).run()
567
+ }
568
+
569
+ /**
570
+ * Decode one Brotli stream, fetching the static dictionary only if the stream
571
+ * turns out to need it.
572
+ *
573
+ * @param {Uint8Array} input
574
+ * @param {object} [options]
575
+ * @param {number} [options.sizeHint]
576
+ * @param {() => Promise<Uint8Array>} [options.loadDictionary]
577
+ * @returns {Promise<Uint8Array>}
578
+ */
579
+ export async function brotliDecode (input, { sizeHint = 0, loadDictionary } = {}) {
580
+ try {
581
+ return brotliDecodeSync(input, { sizeHint })
582
+ } catch (error) {
583
+ if (!(error instanceof NeedsDictionary)) throw error
584
+ const load = loadDictionary || (await import('./brotli-dictionary.js')).loadBrotliDictionary
585
+ return brotliDecodeSync(input, { sizeHint, dictionary: await load() })
586
+ }
587
+ }
588
+
589
+ export default brotliDecode
@@ -49,17 +49,24 @@ async function inflate(bytes) {
49
49
  * Whatever arrived → a plain sfnt, or a refusal that names its reason.
50
50
  *
51
51
  * WOFF1 is a zip of the same tables and is rebuilt losslessly. WOFF2 is a
52
- * different font (glyf transformed, brotli-compressed) and reconstructing it IS
53
- * subsetter-grade surgery, so it is declined. A TrueType collection shares
54
- * tables between faces behind absolute offsets; embedding the whole file would
55
- * make every viewer guess which face was meant, so it is declined too.
52
+ * different font on the wire (glyf transformed, everything behind Brotli) and is
53
+ * rebuilt by `woff2.js` — the same outlines and metrics, not the same bytes. A
54
+ * TrueType collection shares tables between faces behind absolute offsets;
55
+ * embedding the whole file would make every viewer guess which face was meant,
56
+ * so it is declined.
56
57
  *
57
58
  * @returns {Promise<{sfnt: Uint8Array}|{error: string}>}
58
59
  */
59
60
  export async function sfntFromBytes(bytes) {
60
61
  if (!bytes || bytes.length < 12) return { error: 'not a font: shorter than an sfnt header' }
61
62
  const tag = TAG(bytes, 0)
62
- if (tag === 'wOF2') return { error: 'WOFF2 stores transformed tables behind Brotli; rebuilding the original font is a decompiler this exporter refuses to half-do' }
63
+ if (tag === 'wOF2') {
64
+ // Brotli plus the inverse of the glyf/loca/hmtx transforms: `woff2.js`. Imported
65
+ // here and not at the top so that an export which never meets a WOFF2 never
66
+ // loads the decoder, or the 58 kB dictionary behind it.
67
+ const { woff2ToSfnt } = await import('./woff2.js')
68
+ return woff2ToSfnt(bytes)
69
+ }
63
70
  if (tag === 'ttcf') return { error: 'a TrueType collection shares tables between several faces; embedding it whole would leave the face choice to the viewer' }
64
71
  if (tag === 'wOFF') {
65
72
  if (typeof DecompressionStream !== 'function') {
@@ -11,11 +11,11 @@
11
11
  * needs to know who called it, it belongs in the caller. That line is what keeps
12
12
  * the writer testable on its own and the exporter free to change above it.
13
13
  *
14
- * It began life as `@zumer/pdf-writer`, a package shared with the sibling vector
15
- * product inside a monorepo. This repository owns its copy outright: the two
16
- * are free to diverge, and neither can break the other. `setWarnPrefix` survives
17
- * from that arrangement and is still worth having — it is what puts the product's
18
- * own name in front of a warning.
14
+ * There is one copy of it, this one. For a while the vector engine kept a copy
15
+ * of its own for a PDF backend nothing exported, and the copies drifted on the
16
+ * one file where drift is a defect, `encrypt.js`; that copy and that backend are
17
+ * gone. `setWarnPrefix` survives from the shared-package days and is still
18
+ * worth having — it is what puts the product's own name in front of a warning.
19
19
  *
20
20
  * createPdfDoc itself never compresses: it builds dictionaries and counts
21
21
  * /Length over whatever bytes it is handed, which is what keeps it synchronous