document-bytes 2.0.1 → 2.0.3

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/dist/index.js CHANGED
@@ -102,6 +102,15 @@ const DECODE = (() => {
102
102
  })();
103
103
  /** Output characters converted by one `String.fromCharCode.apply` call: half of MAX_CALL_ARGUMENTS, which is also the quantum MDN's own chunked-apply example uses, leaving the engine room for whatever else it puts on its argument stack. It is divisible by four, so every chunk holds whole four-character groups. Exported so the tests can place inputs on and around a chunk boundary without repeating the figure. */
104
104
  const BASE64_ENCODE_CHUNK_CHARS = 32768;
105
+ const BASE64_GROUP_INPUT_BYTES = 3;
106
+ const BASE64_GROUP_OUTPUT_CHARS = 4;
107
+ const BASE64_GROUP_LAST_CHAR_OFFSET = 3;
108
+ const TWO_BIT_SHIFT = 2;
109
+ const FOUR_BIT_SHIFT = 4;
110
+ const SIX_BIT_SHIFT = 6;
111
+ const LOW_TWO_BITS_MASK = 3;
112
+ const LOW_FOUR_BITS_MASK = 15;
113
+ const LOW_SIX_BITS_MASK = 63;
105
114
  /**
106
115
  * Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
107
116
  *
@@ -112,19 +121,19 @@ const BASE64_ENCODE_CHUNK_CHARS = 32768;
112
121
  function bytesToBase64(bytes) {
113
122
  const len = bytes.length;
114
123
  const codes = new Array(BASE64_ENCODE_CHUNK_CHARS);
115
- const chunkBytes = codes.length / 4 * 3;
124
+ const chunkBytes = codes.length / BASE64_GROUP_OUTPUT_CHARS * BASE64_GROUP_INPUT_BYTES;
116
125
  return Array.from({ length: Math.ceil(len / chunkBytes) }, (_unused, chunk) => {
117
126
  const start = chunk * chunkBytes;
118
127
  const end = Math.min(start + chunkBytes, len);
119
128
  let filled = 0;
120
- for (let index = start; index < end; index += 3) {
129
+ for (let index = start; index < end; index += BASE64_GROUP_INPUT_BYTES) {
121
130
  const b0 = bytes[index] ?? 0;
122
131
  const b1 = bytes[index + 1] ?? 0;
123
132
  const b2 = bytes[index + 2] ?? 0;
124
- codes[filled++] = TABLE.charCodeAt(b0 >> 2);
125
- codes[filled++] = TABLE.charCodeAt((b0 & 3) << 4 | b1 >> 4);
126
- codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 & 15) << 2 | b2 >> 6) : PADDING_CODE;
127
- codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 & 63) : PADDING_CODE;
133
+ codes[filled++] = TABLE.charCodeAt(b0 >> TWO_BIT_SHIFT);
134
+ codes[filled++] = TABLE.charCodeAt((b0 & LOW_TWO_BITS_MASK) << FOUR_BIT_SHIFT | b1 >> FOUR_BIT_SHIFT);
135
+ codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 & LOW_FOUR_BITS_MASK) << TWO_BIT_SHIFT | b2 >> SIX_BIT_SHIFT) : PADDING_CODE;
136
+ codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 & LOW_SIX_BITS_MASK) : PADDING_CODE;
128
137
  }
129
138
  return String.fromCharCode.apply(null, codes.slice(0, filled));
130
139
  }).join("");
@@ -140,19 +149,19 @@ function bytesToBase64(bytes) {
140
149
  function base64ToBytes(base64) {
141
150
  const clean = base64.replace(/[^A-Za-z0-9+/=]/g, "");
142
151
  const out = [];
143
- for (let index = 0; index < clean.length; index += 4) {
152
+ for (let index = 0; index < clean.length; index += BASE64_GROUP_OUTPUT_CHARS) {
144
153
  const c0 = DECODE[clean.charCodeAt(index)] ?? DECODE_MISS;
145
154
  const c1 = DECODE[clean.charCodeAt(index + 1)] ?? DECODE_MISS;
146
155
  const c2 = clean.charCodeAt(index + 2);
147
- const c3 = clean.charCodeAt(index + 3);
156
+ const c3 = clean.charCodeAt(index + BASE64_GROUP_LAST_CHAR_OFFSET);
148
157
  if (c0 === DECODE_MISS || c1 === DECODE_MISS) throw new Error("invalid base64 input");
149
- out.push(c0 << 2 | c1 >> 4);
158
+ out.push(c0 << TWO_BIT_SHIFT | c1 >> FOUR_BIT_SHIFT);
150
159
  if (c2 !== PADDING_CODE) {
151
160
  const d2 = DECODE[c2] ?? DECODE_MISS;
152
- out.push((c1 & 15) << 4 | d2 >> 2);
161
+ out.push((c1 & LOW_FOUR_BITS_MASK) << FOUR_BIT_SHIFT | d2 >> TWO_BIT_SHIFT);
153
162
  if (c3 !== PADDING_CODE) {
154
163
  const d3 = DECODE[c3] ?? DECODE_MISS;
155
- out.push((d2 & 3) << 6 | d3);
164
+ out.push((d2 & LOW_TWO_BITS_MASK) << SIX_BIT_SHIFT | d3);
156
165
  }
157
166
  }
158
167
  }
@@ -162,23 +171,23 @@ function base64ToBytes(base64) {
162
171
  //#region src/bytes/crc32.ts
163
172
  const CRC32_POLYNOMIAL = 3988292384;
164
173
  const BYTE_VALUES = 256;
165
- const BITS_PER_BYTE = 8;
174
+ const BITS_PER_BYTE$2 = 8;
175
+ const BYTE_MASK$1 = 255;
176
+ const CRC32_ALL_ONES = 4294967295;
166
177
  const CRC32_TABLE = (() => {
167
178
  const table = new Uint32Array(BYTE_VALUES);
168
179
  for (let n = 0; n < BYTE_VALUES; n++) {
169
180
  let c = n;
170
- for (let k = 0; k < BITS_PER_BYTE; k++) c = (c & 1) === 1 ? CRC32_POLYNOMIAL ^ c >>> 1 : c >>> 1;
181
+ for (let k = 0; k < BITS_PER_BYTE$2; k++) c = (c & 1) === 1 ? CRC32_POLYNOMIAL ^ c >>> 1 : c >>> 1;
171
182
  table[n] = c >>> 0;
172
183
  }
173
184
  return table;
174
185
  })();
175
186
  function crc32(bytes) {
176
- let crc = 4294967295;
177
- for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
178
- return (crc ^ 4294967295) >>> 0;
187
+ let crc = CRC32_ALL_ONES;
188
+ for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$1] ^ crc >>> BITS_PER_BYTE$2;
189
+ return (crc ^ CRC32_ALL_ONES) >>> 0;
179
190
  }
180
- //#endregion
181
- //#region src/bytes/flate.ts
182
191
  const MAX_INFLATE_OUTPUT_BYTES = 536870912;
183
192
  function deflate(data, level) {
184
193
  return zlibSync(data, level === void 0 ? void 0 : { level });
@@ -255,6 +264,10 @@ const GB18030_RANGES = pairs("[[0,128],[36,165],[38,169],[45,178],[50,184],[81,2
255
264
  const REPLACEMENT_CHARACTER_CODE_UNIT = 65533;
256
265
  /** The last byte value the Encoding Standard's own "ASCII byte" term covers (0x00 to 0x7F inclusive) in every one of these encodings: below this, and outside each encoding's own designated multi-byte lead range, a byte is its own code point unchanged. */
257
266
  const ASCII_BYTE_MAX = 127;
267
+ const HEX_RADIX$2 = 16;
268
+ /** The halfwidth-katakana byte range JIS X 0201 shares across Shift_JIS and EUC-JP's own single-byte katakana forms, and the Unicode block it maps onto directly (0xFF61 plus the byte's own offset from the range's first value). */
269
+ const KATAKANA_BYTE_START = 161;
270
+ const KATAKANA_BYTE_END = 223;
258
271
  /**
259
272
  * The Unicode code point {@link JIS0208}, {@link JIS0212}, {@link BIG5}, {@link EUC_KR} or {@link GB18030} holds at `pointer` — the Encoding Standard's own "index code point" (https://encoding.spec.whatwg.org/#index-code-point) operation — or `undefined` when `pointer` lands on the table's own gap marker, needs disambiguating against `astral` and turns out to have no entry there either, or falls outside the table entirely.
260
273
  *
@@ -277,13 +290,23 @@ function truncated$1(label) {
277
290
  /**
278
291
  * Big5's own four hardcoded pointer exceptions where a single lead/trail byte pair decodes to *two* Unicode code points rather than one — combining-diacritic spellings of vowels HKSCS adds that Big5's own index, limited like every WHATWG index to single code points, cannot hold directly (https://encoding.spec.whatwg.org/#big5-decoder, the table immediately under "If there is a row in the table below whose first column is pointer"). Checked before the general {@link BIG5} lookup, exactly as the standard's own decoder algorithm does.
279
292
  */
293
+ const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON = 1133;
294
+ const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON = 1135;
295
+ const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON_LOWER = 1164;
296
+ const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON_LOWER = 1166;
297
+ const LATIN_E_CIRCUMFLEX = 202;
298
+ const LATIN_E_CIRCUMFLEX_LOWER = 234;
299
+ const COMBINING_MACRON = 772;
300
+ const COMBINING_CARON = 780;
280
301
  const BIG5_DOUBLE_CODE_POINT_POINTERS = /* @__PURE__ */ new Map([
281
- [1133, [202, 772]],
282
- [1135, [202, 780]],
283
- [1164, [234, 772]],
284
- [1166, [234, 780]]
302
+ [BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON, [LATIN_E_CIRCUMFLEX, COMBINING_MACRON]],
303
+ [BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON, [LATIN_E_CIRCUMFLEX, COMBINING_CARON]],
304
+ [BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON_LOWER, [LATIN_E_CIRCUMFLEX_LOWER, COMBINING_MACRON]],
305
+ [BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON_LOWER, [LATIN_E_CIRCUMFLEX_LOWER, COMBINING_CARON]]
285
306
  ]);
286
307
  /** The number of columns Shift_JIS, Big5 and gb18030 all give their shared low trailing-byte band, 0x40-0x7E — named so {@link twoByteTrailColumn}'s high-band column reads as "continuing on from the low band" rather than restating this same derived count as an unexplained literal. */
308
+ const LOW_TRAIL_BYTE_START = 64;
309
+ const LOW_TRAIL_BYTE_END = 126;
287
310
  const LOW_TRAIL_BYTE_COUNT = 63;
288
311
  /**
289
312
  * The pointer column a trailing byte contributes for Shift_JIS, Big5 and gb18030's own two-byte forms, whose trailing-byte range always splits into the same low band (0x40-0x7E) plus an encoding-specific high band (`highBandStart` to `highBandEnd`) — or `undefined` when `byte` falls in neither. Shared here rather than reimplemented per decoder specifically so every boundary comparison is written against a byte value the range can actually reach (0x40, 0x7E, and each caller's own high-band ends), never a threshold sitting in a gap no valid byte ever lands in: a decoder written the Encoding Standard's own way, subtracting a byte-range-specific "offset" chosen so a boundary byte and its threshold happen to coincide, has no way to make a boundary comparison mutation observable when the coincidence itself is what the surrounding range check already guarantees — this instead keys every column directly off the low band's own reachable extremes, so a single off-by-one in any comparison here changes a real byte's result rather than only a value that string of range checks already ruled out beforehand.
@@ -293,7 +316,7 @@ const LOW_TRAIL_BYTE_COUNT = 63;
293
316
  * @returns The pointer column `byte` contributes, or `undefined` when it names neither band.
294
317
  */
295
318
  function twoByteTrailColumn(byte, highBandStart, highBandEnd) {
296
- if (byte >= 64 && byte <= 126) return byte - 64;
319
+ if (byte >= LOW_TRAIL_BYTE_START && byte <= LOW_TRAIL_BYTE_END) return byte - LOW_TRAIL_BYTE_START;
297
320
  if (byte >= highBandStart && byte <= highBandEnd) return byte - highBandStart + LOW_TRAIL_BYTE_COUNT;
298
321
  }
299
322
  /**
@@ -304,6 +327,16 @@ function twoByteTrailColumn(byte, highBandStart, highBandEnd) {
304
327
  * @returns The decoded text.
305
328
  * @throws UndecodableTextError When the bytes contain a byte or byte pair Shift_JIS leaves undefined, or end with an incomplete two-byte sequence.
306
329
  */
330
+ const SHIFT_JIS_LOW_LEAD_START = 129;
331
+ const SHIFT_JIS_LOW_LEAD_END = 159;
332
+ const SHIFT_JIS_HIGH_LEAD_DETECT_START = 224;
333
+ const SHIFT_JIS_HIGH_LEAD_OFFSET_ANCHOR = 193;
334
+ const SHIFT_JIS_TRAIL_HIGH_START = 128;
335
+ const SHIFT_JIS_TRAIL_HIGH_END = 252;
336
+ const SHIFT_JIS_COLUMNS = 188;
337
+ const SHIFT_JIS_EUDC_POINTER_START = 8836;
338
+ const SHIFT_JIS_EUDC_POINTER_END = 10715;
339
+ const SHIFT_JIS_SINGLE_BYTE_EXTRA = 128;
307
340
  function decodeShiftJis(bytes) {
308
341
  const sink = { units: [] };
309
342
  let leading = 0;
@@ -311,22 +344,22 @@ function decodeShiftJis(bytes) {
311
344
  if (leading !== 0) {
312
345
  const leadingByte = leading;
313
346
  leading = 0;
314
- const leadingOffset = leadingByte <= 159 ? 129 : 193;
315
- const column = twoByteTrailColumn(byte, 128, 252);
316
- const pointer = column === void 0 ? void 0 : (leadingByte - leadingOffset) * 188 + column;
317
- if (pointer !== void 0 && pointer >= 8836 && pointer <= 10715) {
347
+ const leadingOffset = leadingByte <= SHIFT_JIS_LOW_LEAD_END ? SHIFT_JIS_LOW_LEAD_START : SHIFT_JIS_HIGH_LEAD_OFFSET_ANCHOR;
348
+ const column = twoByteTrailColumn(byte, SHIFT_JIS_TRAIL_HIGH_START, SHIFT_JIS_TRAIL_HIGH_END);
349
+ const pointer = column === void 0 ? void 0 : (leadingByte - leadingOffset) * SHIFT_JIS_COLUMNS + column;
350
+ if (pointer !== void 0 && pointer >= SHIFT_JIS_EUDC_POINTER_START && pointer <= SHIFT_JIS_EUDC_POINTER_END) {
318
351
  appendCodePoint(sink, 48508 + pointer);
319
352
  continue;
320
353
  }
321
354
  const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(JIS0208, pointer);
322
- if (codePoint === void 0) malformed$1("Shift_JIS", `has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
355
+ if (codePoint === void 0) malformed$1("Shift_JIS", `has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$2)} trail byte 0x${byte.toString(HEX_RADIX$2)}`);
323
356
  appendCodePoint(sink, codePoint);
324
357
  continue;
325
358
  }
326
- if (byte <= ASCII_BYTE_MAX || byte === 128) sink.units.push(byte);
327
- else if (byte >= 161 && byte <= 223) appendCodePoint(sink, 65216 + byte);
328
- else if (byte <= 159 || byte >= 224 && byte <= 252) leading = byte;
329
- else malformed$1("Shift_JIS", `has no character for byte 0x${byte.toString(16)}`);
359
+ if (byte <= ASCII_BYTE_MAX || byte === SHIFT_JIS_SINGLE_BYTE_EXTRA) sink.units.push(byte);
360
+ else if (byte >= KATAKANA_BYTE_START && byte <= KATAKANA_BYTE_END) appendCodePoint(sink, 65216 + byte);
361
+ else if (byte <= SHIFT_JIS_LOW_LEAD_END || byte >= SHIFT_JIS_HIGH_LEAD_DETECT_START && byte <= SHIFT_JIS_TRAIL_HIGH_END) leading = byte;
362
+ else malformed$1("Shift_JIS", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
330
363
  }
331
364
  if (leading !== 0) truncated$1("Shift_JIS");
332
365
  return fromCodeUnits(sink.units);
@@ -339,17 +372,22 @@ function decodeShiftJis(bytes) {
339
372
  * @returns The decoded text.
340
373
  * @throws UndecodableTextError When the bytes contain a byte or byte pair EUC-JP leaves undefined, or end with an incomplete multi-byte sequence.
341
374
  */
375
+ const EUC_JP_KATAKANA_LEAD = 142;
376
+ const EUC_JP_JIS0212_LEAD = 143;
377
+ const EUC_JP_INDEX_BYTE_MIN = 161;
378
+ const EUC_JP_INDEX_BYTE_MAX = 254;
379
+ const EUC_JIS_COLUMNS = 94;
342
380
  function decodeEucJp(bytes) {
343
381
  const sink = { units: [] };
344
382
  let leading = 0;
345
383
  let jis0212 = false;
346
384
  for (const byte of bytes) {
347
- if (leading === 142 && byte >= 161 && byte <= 223) {
385
+ if (leading === EUC_JP_KATAKANA_LEAD && byte >= KATAKANA_BYTE_START && byte <= KATAKANA_BYTE_END) {
348
386
  leading = 0;
349
387
  appendCodePoint(sink, 65216 + byte);
350
388
  continue;
351
389
  }
352
- if (leading === 143 && byte >= 161 && byte <= 254) {
390
+ if (leading === EUC_JP_JIS0212_LEAD && byte >= EUC_JP_INDEX_BYTE_MIN && byte <= EUC_JP_INDEX_BYTE_MAX) {
353
391
  jis0212 = true;
354
392
  leading = byte;
355
393
  continue;
@@ -359,14 +397,14 @@ function decodeEucJp(bytes) {
359
397
  leading = 0;
360
398
  const usedJis0212 = jis0212;
361
399
  jis0212 = false;
362
- const codePoint = byte >= 161 && byte <= 254 ? pointerCodePoint(usedJis0212 ? JIS0212 : JIS0208, (leadingByte - 161) * 94 + byte - 161) : void 0;
363
- if (codePoint === void 0) malformed$1("EUC-JP", `has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
400
+ const codePoint = byte >= EUC_JP_INDEX_BYTE_MIN && byte <= EUC_JP_INDEX_BYTE_MAX ? pointerCodePoint(usedJis0212 ? JIS0212 : JIS0208, (leadingByte - EUC_JP_INDEX_BYTE_MIN) * EUC_JIS_COLUMNS + byte - EUC_JP_INDEX_BYTE_MIN) : void 0;
401
+ if (codePoint === void 0) malformed$1("EUC-JP", `has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$2)} trail byte 0x${byte.toString(HEX_RADIX$2)}`);
364
402
  appendCodePoint(sink, codePoint);
365
403
  continue;
366
404
  }
367
405
  if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
368
- else if (byte === 142 || byte === 143 || byte >= 161 && byte <= 254) leading = byte;
369
- else malformed$1("EUC-JP", `has no character for byte 0x${byte.toString(16)}`);
406
+ else if (byte === EUC_JP_KATAKANA_LEAD || byte === EUC_JP_JIS0212_LEAD || byte >= EUC_JP_INDEX_BYTE_MIN && byte <= EUC_JP_INDEX_BYTE_MAX) leading = byte;
407
+ else malformed$1("EUC-JP", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
370
408
  }
371
409
  if (leading !== 0) truncated$1("EUC-JP");
372
410
  return fromCodeUnits(sink.units);
@@ -379,6 +417,11 @@ function decodeEucJp(bytes) {
379
417
  * @returns The decoded text.
380
418
  * @throws UndecodableTextError When the bytes contain a byte or byte pair EUC-KR leaves undefined, or end with an incomplete two-byte sequence.
381
419
  */
420
+ const EUC_KR_LEAD_START = 129;
421
+ const EUC_KR_LEAD_END = 254;
422
+ const EUC_KR_TRAIL_START = 65;
423
+ const EUC_KR_TRAIL_END = 254;
424
+ const EUC_KR_COLUMNS = 190;
382
425
  function decodeEucKr(bytes) {
383
426
  const sink = { units: [] };
384
427
  let leading = 0;
@@ -386,14 +429,14 @@ function decodeEucKr(bytes) {
386
429
  if (leading !== 0) {
387
430
  const leadingByte = leading;
388
431
  leading = 0;
389
- const codePoint = byte >= 65 && byte <= 254 ? pointerCodePoint(EUC_KR, (leadingByte - 129) * 190 + byte - 65) : void 0;
390
- if (codePoint === void 0) malformed$1("EUC-KR", `has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
432
+ const codePoint = byte >= EUC_KR_TRAIL_START && byte <= EUC_KR_TRAIL_END ? pointerCodePoint(EUC_KR, (leadingByte - EUC_KR_LEAD_START) * EUC_KR_COLUMNS + byte - EUC_KR_TRAIL_START) : void 0;
433
+ if (codePoint === void 0) malformed$1("EUC-KR", `has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$2)} trail byte 0x${byte.toString(HEX_RADIX$2)}`);
391
434
  appendCodePoint(sink, codePoint);
392
435
  continue;
393
436
  }
394
437
  if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
395
- else if (byte >= 129 && byte <= 254) leading = byte;
396
- else malformed$1("EUC-KR", `has no character for byte 0x${byte.toString(16)}`);
438
+ else if (byte >= EUC_KR_LEAD_START && byte <= EUC_KR_LEAD_END) leading = byte;
439
+ else malformed$1("EUC-KR", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
397
440
  }
398
441
  if (leading !== 0) truncated$1("EUC-KR");
399
442
  return fromCodeUnits(sink.units);
@@ -406,6 +449,11 @@ function decodeEucKr(bytes) {
406
449
  * @returns The decoded text.
407
450
  * @throws UndecodableTextError When the bytes contain a byte or byte pair Big5 leaves undefined, or end with an incomplete two-byte sequence.
408
451
  */
452
+ const BIG5_LEAD_START = 129;
453
+ const BIG5_LEAD_END = 254;
454
+ const BIG5_TRAIL_HIGH_START = 161;
455
+ const BIG5_TRAIL_HIGH_END = 254;
456
+ const BIG5_COLUMNS = 157;
409
457
  function decodeBig5(bytes) {
410
458
  const sink = { units: [] };
411
459
  let leading = 0;
@@ -413,8 +461,8 @@ function decodeBig5(bytes) {
413
461
  if (leading !== 0) {
414
462
  const leadingByte = leading;
415
463
  leading = 0;
416
- const column = twoByteTrailColumn(byte, 161, 254);
417
- const pointer = column === void 0 ? void 0 : (leadingByte - 129) * 157 + column;
464
+ const column = twoByteTrailColumn(byte, BIG5_TRAIL_HIGH_START, BIG5_TRAIL_HIGH_END);
465
+ const pointer = column === void 0 ? void 0 : (leadingByte - BIG5_LEAD_START) * BIG5_COLUMNS + column;
418
466
  const doubled = pointer === void 0 ? void 0 : BIG5_DOUBLE_CODE_POINT_POINTERS.get(pointer);
419
467
  if (doubled !== void 0) {
420
468
  appendCodePoint(sink, doubled[0]);
@@ -422,13 +470,13 @@ function decodeBig5(bytes) {
422
470
  continue;
423
471
  }
424
472
  const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(BIG5, pointer);
425
- if (codePoint === void 0) malformed$1("Big5", `has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
473
+ if (codePoint === void 0) malformed$1("Big5", `has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$2)} trail byte 0x${byte.toString(HEX_RADIX$2)}`);
426
474
  appendCodePoint(sink, codePoint);
427
475
  continue;
428
476
  }
429
477
  if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
430
- else if (byte >= 129 && byte <= 254) leading = byte;
431
- else malformed$1("Big5", `has no character for byte 0x${byte.toString(16)}`);
478
+ else if (byte >= BIG5_LEAD_START && byte <= BIG5_LEAD_END) leading = byte;
479
+ else malformed$1("Big5", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
432
480
  }
433
481
  if (leading !== 0) truncated$1("Big5");
434
482
  return fromCodeUnits(sink.units);
@@ -437,6 +485,19 @@ function decodeBig5(bytes) {
437
485
  * The number of distinct values gb18030's own third byte (0x81-0xFE) can take, and the number of distinct values its own second and fourth bytes (0x30-0x39) can take — the two factors the Encoding Standard's own gb18030 decoder algorithm multiplies together (as `10 × 126` and `10 × 126 × 10`) to place each of the four bytes in a four-byte pointer's own positional value. Named so the arithmetic in {@link decodeGb18030} reads as the byte-range sizes it actually is, rather than as two bare products of unexplained digits.
438
486
  */
439
487
  const GB18030_SECOND_FOURTH_BYTE_COUNT = 10;
488
+ /** gb18030's own lead-byte band for both its two-byte and four-byte forms: a first byte outside 0x00-0x7F ASCII starts a multi-byte sequence only when it falls in 0x81-0xFE (0x80 alone is the fixed Euro-sign exception below). Also the third byte's own valid range in a four-byte sequence. */
489
+ const GB18030_LEAD_START = 129;
490
+ const GB18030_LEAD_END = 254;
491
+ /** The digit-only byte band (ASCII '0'-'9') gb18030 requires of its own second and fourth bytes in a four-byte sequence, and the band that tells the decoder a two-byte lead's second byte is starting a four-byte form rather than a two-byte trail. */
492
+ const GB18030_DIGIT_BYTE_MIN = 48;
493
+ const GB18030_DIGIT_BYTE_MAX = 57;
494
+ /** The trailing-byte band gb18030's own two-byte form shares with Big5 and Shift_JIS (see {@link twoByteTrailColumn}), and the column count that band spans: 190 distinct trail values per lead byte. */
495
+ const GB18030_TRAIL_HIGH_START = 128;
496
+ const GB18030_TRAIL_HIGH_END = 254;
497
+ const GB18030_TWO_BYTE_COLUMNS = 190;
498
+ /** The one single-byte value gb18030 decodes outside plain ASCII: byte 0x80 alone is the Euro sign, U+20AC, a fixed exception the Encoding Standard states directly rather than deriving from any table. */
499
+ const GB18030_SINGLE_BYTE_EURO = 128;
500
+ const EURO_SIGN_CODE_POINT = 8364;
440
501
  /**
441
502
  * The Unicode code point gb18030's own algorithmic four-byte form holds at `pointer` (https://encoding.spec.whatwg.org/#index-gb18030-ranges-code-point), computed from {@link GB18030_RANGES} rather than looked up directly: that table holds only the code point at the *start* of each contiguous range, so the result is that start plus how far `pointer` sits past it.
442
503
  * @param pointer - The four-byte pointer computed from a gb18030 lead, second, third and trailing byte.
@@ -470,43 +531,43 @@ function decodeGb18030(bytes) {
470
531
  let third = 0;
471
532
  for (const byte of bytes) {
472
533
  if (third !== 0) {
473
- if (byte < 48 || byte > 57) malformed$1("gb18030", `has no character for four-byte sequence 0x${first.toString(16)} 0x${second.toString(16)} 0x${third.toString(16)} 0x${byte.toString(16)}: fourth byte is not 0x30-0x39`);
474
- const codePoint = gb18030RangesCodePoint((first - 129) * (1260 * GB18030_SECOND_FOURTH_BYTE_COUNT) + (second - 48) * 1260 + (third - 129) * GB18030_SECOND_FOURTH_BYTE_COUNT + (byte - 48));
534
+ if (byte < GB18030_DIGIT_BYTE_MIN || byte > GB18030_DIGIT_BYTE_MAX) malformed$1("gb18030", `has no character for four-byte sequence 0x${first.toString(HEX_RADIX$2)} 0x${second.toString(HEX_RADIX$2)} 0x${third.toString(HEX_RADIX$2)} 0x${byte.toString(HEX_RADIX$2)}: fourth byte is not 0x30-0x39`);
535
+ const codePoint = gb18030RangesCodePoint((first - GB18030_LEAD_START) * (1260 * GB18030_SECOND_FOURTH_BYTE_COUNT) + (second - GB18030_DIGIT_BYTE_MIN) * 1260 + (third - GB18030_LEAD_START) * GB18030_SECOND_FOURTH_BYTE_COUNT + (byte - GB18030_DIGIT_BYTE_MIN));
475
536
  const failedFirst = first;
476
537
  const failedSecond = second;
477
538
  const failedThird = third;
478
539
  first = 0;
479
540
  second = 0;
480
541
  third = 0;
481
- if (codePoint === void 0) malformed$1("gb18030", `has no character for four-byte sequence 0x${failedFirst.toString(16)} 0x${failedSecond.toString(16)} 0x${failedThird.toString(16)} 0x${byte.toString(16)}`);
542
+ if (codePoint === void 0) malformed$1("gb18030", `has no character for four-byte sequence 0x${failedFirst.toString(HEX_RADIX$2)} 0x${failedSecond.toString(HEX_RADIX$2)} 0x${failedThird.toString(HEX_RADIX$2)} 0x${byte.toString(HEX_RADIX$2)}`);
482
543
  appendCodePoint(sink, codePoint);
483
544
  continue;
484
545
  }
485
546
  if (second !== 0) {
486
- if (byte >= 129 && byte <= 254) {
547
+ if (byte >= GB18030_LEAD_START && byte <= GB18030_LEAD_END) {
487
548
  third = byte;
488
549
  continue;
489
550
  }
490
- malformed$1("gb18030", `has no character for byte sequence 0x${first.toString(16)} 0x${second.toString(16)} 0x${byte.toString(16)}: third byte is not 0x81-0xFE`);
551
+ malformed$1("gb18030", `has no character for byte sequence 0x${first.toString(HEX_RADIX$2)} 0x${second.toString(HEX_RADIX$2)} 0x${byte.toString(HEX_RADIX$2)}: third byte is not 0x81-0xFE`);
491
552
  }
492
553
  if (first !== 0) {
493
- if (byte >= 48 && byte <= 57) {
554
+ if (byte >= GB18030_DIGIT_BYTE_MIN && byte <= GB18030_DIGIT_BYTE_MAX) {
494
555
  second = byte;
495
556
  continue;
496
557
  }
497
558
  const leadingByte = first;
498
559
  first = 0;
499
- const column = twoByteTrailColumn(byte, 128, 254);
500
- const pointer = column === void 0 ? void 0 : (leadingByte - 129) * 190 + column;
560
+ const column = twoByteTrailColumn(byte, GB18030_TRAIL_HIGH_START, GB18030_TRAIL_HIGH_END);
561
+ const pointer = column === void 0 ? void 0 : (leadingByte - GB18030_LEAD_START) * GB18030_TWO_BYTE_COLUMNS + column;
501
562
  const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(GB18030, pointer);
502
- if (codePoint === void 0) malformed$1("gb18030", `has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
563
+ if (codePoint === void 0) malformed$1("gb18030", `has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$2)} trail byte 0x${byte.toString(HEX_RADIX$2)}`);
503
564
  appendCodePoint(sink, codePoint);
504
565
  continue;
505
566
  }
506
567
  if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
507
- else if (byte === 128) sink.units.push(8364);
508
- else if (byte <= 254) first = byte;
509
- else malformed$1("gb18030", `has no character for byte 0x${byte.toString(16)}`);
568
+ else if (byte === GB18030_SINGLE_BYTE_EURO) sink.units.push(EURO_SIGN_CODE_POINT);
569
+ else if (byte <= GB18030_LEAD_END) first = byte;
570
+ else malformed$1("gb18030", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
510
571
  }
511
572
  if (first !== 0) truncated$1("gb18030");
512
573
  return fromCodeUnits(sink.units);
@@ -528,11 +589,25 @@ const KATAKANA_LAST_BYTE = 95;
528
589
  const JIS0208_INDEX_BYTE_MIN = 33;
529
590
  const JIS0208_INDEX_BYTE_MAX = 126;
530
591
  const JIS0208_INDEX_COLUMNS = 94;
592
+ const HEX_RADIX$1 = 16;
593
+ const PLAIN_BYTE_MAX = 127;
594
+ const SHIFT_OUT = 14;
595
+ const SHIFT_IN = 15;
596
+ const ROMAN_YEN_BYTE = 92;
597
+ const ROMAN_YEN_CODEPOINT = 165;
598
+ const ROMAN_OVERLINE_BYTE = 126;
599
+ const ROMAN_OVERLINE_CODEPOINT = 8254;
600
+ const ESCAPE_DESIGNATOR_DOLLAR = 36;
601
+ const ESCAPE_DESIGNATOR_PAREN = 40;
602
+ const ESCAPE_DESIGNATOR_AT = 64;
603
+ const ESCAPE_DESIGNATOR_B = 66;
604
+ const ESCAPE_DESIGNATOR_I = 73;
605
+ const ESCAPE_DESIGNATOR_J = 74;
531
606
  /**
532
607
  * Whether `byte` is one this decoder's ASCII and Roman states pass through unchanged: any byte below 0x80 except the two Shift-Out/Shift-In control codes (0x0E, 0x0F) a different ISO-2022 variant uses for a switching mechanism this decoder does not support. No check for {@link ESCAPE} here: both callers (the "ascii" and "roman" cases below) already intercept it with their own `byte === ESCAPE` branch before ever reaching this function, so `byte` here is never that value in the first place.
533
608
  */
534
609
  function isPlainByte(byte) {
535
- return byte <= 127 && byte !== 14 && byte !== 15;
610
+ return byte <= PLAIN_BYTE_MAX && byte !== SHIFT_OUT && byte !== SHIFT_IN;
536
611
  }
537
612
  /**
538
613
  * Decodes bytes as ISO-2022-JP (https://encoding.spec.whatwg.org/#iso-2022-jp-decoder).
@@ -556,7 +631,7 @@ function decodeIso2022Jp(bytes) {
556
631
  continue;
557
632
  }
558
633
  output = false;
559
- if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(16)} in ASCII mode`);
634
+ if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in ASCII mode`);
560
635
  units.push(byte);
561
636
  continue;
562
637
  case "roman":
@@ -565,15 +640,15 @@ function decodeIso2022Jp(bytes) {
565
640
  continue;
566
641
  }
567
642
  output = false;
568
- if (byte === 92) {
569
- units.push(165);
643
+ if (byte === ROMAN_YEN_BYTE) {
644
+ units.push(ROMAN_YEN_CODEPOINT);
570
645
  continue;
571
646
  }
572
- if (byte === 126) {
573
- units.push(8254);
647
+ if (byte === ROMAN_OVERLINE_BYTE) {
648
+ units.push(ROMAN_OVERLINE_CODEPOINT);
574
649
  continue;
575
650
  }
576
- if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(16)} in Roman mode`);
651
+ if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in Roman mode`);
577
652
  units.push(byte);
578
653
  continue;
579
654
  case "katakana":
@@ -582,7 +657,7 @@ function decodeIso2022Jp(bytes) {
582
657
  continue;
583
658
  }
584
659
  output = false;
585
- if (byte < KATAKANA_FIRST_BYTE || byte > KATAKANA_LAST_BYTE) malformed(`has no character for byte 0x${byte.toString(16)} in Katakana mode`);
660
+ if (byte < KATAKANA_FIRST_BYTE || byte > KATAKANA_LAST_BYTE) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in Katakana mode`);
586
661
  units.push(65344 + byte);
587
662
  continue;
588
663
  case "leadingByte":
@@ -591,34 +666,34 @@ function decodeIso2022Jp(bytes) {
591
666
  continue;
592
667
  }
593
668
  output = false;
594
- if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for byte 0x${byte.toString(16)} as a JIS X 0208 lead byte`);
669
+ if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} as a JIS X 0208 lead byte`);
595
670
  pending = byte;
596
671
  state = "trailingByte";
597
672
  continue;
598
673
  case "trailingByte": {
599
674
  const leadingByte = pending;
600
675
  state = "leadingByte";
601
- if (byte === ESCAPE) malformed(`has an incomplete JIS X 0208 two-byte sequence: lead byte 0x${leadingByte.toString(16)} was interrupted by an escape sequence`);
602
- if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
676
+ if (byte === ESCAPE) malformed(`has an incomplete JIS X 0208 two-byte sequence: lead byte 0x${leadingByte.toString(HEX_RADIX$1)} was interrupted by an escape sequence`);
677
+ if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$1)} trail byte 0x${byte.toString(HEX_RADIX$1)}`);
603
678
  const pointer = (leadingByte - JIS0208_INDEX_BYTE_MIN) * JIS0208_INDEX_COLUMNS + byte - JIS0208_INDEX_BYTE_MIN;
604
679
  const codePoint = pointerCodePoint(JIS0208, pointer);
605
- if (codePoint === void 0) malformed(`has no character for lead byte 0x${leadingByte.toString(16)} trail byte 0x${byte.toString(16)}`);
680
+ if (codePoint === void 0) malformed(`has no character for lead byte 0x${leadingByte.toString(HEX_RADIX$1)} trail byte 0x${byte.toString(HEX_RADIX$1)}`);
606
681
  units.push(codePoint);
607
682
  continue;
608
683
  }
609
684
  case "escapeStart":
610
- if (byte === 36 || byte === 40) {
685
+ if (byte === ESCAPE_DESIGNATOR_DOLLAR || byte === ESCAPE_DESIGNATOR_PAREN) {
611
686
  pending = byte;
612
687
  state = "escape";
613
688
  continue;
614
689
  }
615
- malformed(`has no supported designator starting with escape byte 0x${byte.toString(16)}`);
690
+ malformed(`has no supported designator starting with escape byte 0x${byte.toString(HEX_RADIX$1)}`);
616
691
  continue;
617
692
  case "escape": {
618
693
  const leadingEscapeByte = pending;
619
694
  pending = 0;
620
- const nextState = leadingEscapeByte === 40 && byte === 66 ? "ascii" : leadingEscapeByte === 40 && byte === 74 ? "roman" : leadingEscapeByte === 40 && byte === 73 ? "katakana" : leadingEscapeByte === 36 && (byte === 64 || byte === 66) ? "leadingByte" : void 0;
621
- if (nextState === void 0) malformed(`has an unsupported designator escape sequence 0x1b 0x${leadingEscapeByte.toString(16)} 0x${byte.toString(16)}`);
695
+ const nextState = leadingEscapeByte === ESCAPE_DESIGNATOR_PAREN && byte === ESCAPE_DESIGNATOR_B ? "ascii" : leadingEscapeByte === ESCAPE_DESIGNATOR_PAREN && byte === ESCAPE_DESIGNATOR_J ? "roman" : leadingEscapeByte === ESCAPE_DESIGNATOR_PAREN && byte === ESCAPE_DESIGNATOR_I ? "katakana" : leadingEscapeByte === ESCAPE_DESIGNATOR_DOLLAR && (byte === ESCAPE_DESIGNATOR_AT || byte === ESCAPE_DESIGNATOR_B) ? "leadingByte" : void 0;
696
+ if (nextState === void 0) malformed(`has an unsupported designator escape sequence 0x1b 0x${leadingEscapeByte.toString(HEX_RADIX$1)} 0x${byte.toString(HEX_RADIX$1)}`);
622
697
  state = nextState;
623
698
  if (output) malformed("has a redundant designator escape sequence with no characters decoded since the previous one");
624
699
  output = true;
@@ -710,11 +785,6 @@ const SUPPLEMENTARY_PLANE_START = 65536;
710
785
  /** How a supplementary code point splits across a surrogate pair: the ten low bits go to the low half and the rest to the high half, both biased by the start of their own range. */
711
786
  const SURROGATE_BITS = 10;
712
787
  const LOW_SURROGATE_MASK = 1023;
713
- /**
714
- * Code units converted by one `String.fromCharCode.apply` call. JavaScriptCore rejects a call with more than 65536 arguments, a limit MDN documents as hard-coded (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and other engines bound the same thing by stack size, so this is half that stated figure, leaving the engine room for whatever else it puts on its argument stack. The same quantum src/bytes/base64.ts's own chunked encode uses, for the same reason: appending one character at a time to a string is what made converting a few megabytes take seconds under instrumentation.
715
- *
716
- * Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
717
- */
718
788
  const TEXT_DECODE_CHUNK_CODE_UNITS = 32768;
719
789
  /**
720
790
  * Splits `codePoint` into one or two UTF-16 code units and pushes them onto `sink.units`: the code point itself below the supplementary plane, a surrogate pair biased by {@link SURROGATE_BITS} and {@link LOW_SURROGATE_MASK} above it. Shared by every decoder here that can produce a code point outside the Basic Multilingual Plane — {@link decodeUtf32} for UTF-32's own scalar values, and decode-dbcs.ts's decoders for the WHATWG index tables' own supplementary-plane entries (Big5's CJK Compatibility Ideographs Supplement pointers, gb18030's final algorithmic range) — so the split happens in exactly one place rather than once per caller.
@@ -741,6 +811,8 @@ function fromCodeUnits(units) {
741
811
  return String.fromCharCode.apply(null, units.slice(start, start + TEXT_DECODE_CHUNK_CODE_UNITS));
742
812
  }).join("");
743
813
  }
814
+ const BOM_FE = 254;
815
+ const BOM_FF = 255;
744
816
  /** Every byte order mark, longest first: UTF-32LE's begins with UTF-16LE's, so the four-byte marks have to be tested before the two-byte ones. Unicode resolves that overlap the same way, the alternative reading being a UTF-16LE file whose first character is U+0000, which is not a file that occurs. */
745
817
  const BOM_SIGNATURES = [
746
818
  {
@@ -748,15 +820,15 @@ const BOM_SIGNATURES = [
748
820
  bytes: [
749
821
  0,
750
822
  0,
751
- 254,
752
- 255
823
+ BOM_FE,
824
+ BOM_FF
753
825
  ]
754
826
  },
755
827
  {
756
828
  encoding: "utf-32le",
757
829
  bytes: [
758
- 255,
759
- 254,
830
+ BOM_FF,
831
+ BOM_FE,
760
832
  0,
761
833
  0
762
834
  ]
@@ -771,11 +843,11 @@ const BOM_SIGNATURES = [
771
843
  },
772
844
  {
773
845
  encoding: "utf-16be",
774
- bytes: [254, 255]
846
+ bytes: [BOM_FE, BOM_FF]
775
847
  },
776
848
  {
777
849
  encoding: "utf-16le",
778
- bytes: [255, 254]
850
+ bytes: [BOM_FF, BOM_FE]
779
851
  }
780
852
  ];
781
853
  function findBom(bytes) {
@@ -830,11 +902,12 @@ function tryDecodeUtf16(bytes, littleEndian) {
830
902
  return;
831
903
  }
832
904
  }
905
+ const BYTES_PER_UTF32_CODE_UNIT = 4;
833
906
  function decodeUtf32(bytes, littleEndian) {
834
- if (bytes.byteLength % 4 !== 0) throw new UndecodableTextError("malformed", "UTF-32 text must hold a whole number of 32-bit code units");
907
+ if (bytes.byteLength % BYTES_PER_UTF32_CODE_UNIT !== 0) throw new UndecodableTextError("malformed", "UTF-32 text must hold a whole number of 32-bit code units");
835
908
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
836
909
  const sink = { units: [] };
837
- for (let offset = 0; offset < bytes.byteLength; offset += 4) {
910
+ for (let offset = 0; offset < bytes.byteLength; offset += BYTES_PER_UTF32_CODE_UNIT) {
838
911
  const codePoint = view.getUint32(offset, littleEndian);
839
912
  if (codePoint > MAX_CODE_POINT || codePoint >= HIGH_SURROGATE_START && codePoint <= LOW_SURROGATE_END) throw new UndecodableTextError("malformed", "UTF-32 text must hold only Unicode scalar values");
840
913
  appendCodePoint(sink, codePoint);
@@ -853,6 +926,7 @@ function decodeUtf8(bytes) {
853
926
  }
854
927
  /** The code unit {@link LEGACY_SINGLE_BYTE_TABLES} holds for a byte its encoding leaves without a character of its own. No legacy single-byte encoding maps a real byte to the replacement character, which is what makes it safe to use as that table's own gap marker. */
855
928
  const LEGACY_SINGLE_BYTE_GAP_CODE = 65533;
929
+ const HEX_RADIX = 16;
856
930
  /** Decodes bytes under a {@link LegacySingleByteEncodingLabel}, using `table` (128 code units, one per byte from {@link FIRST_HIGH_BYTE} to 0xFF) for the high half and ASCII identity for the low half, exactly as {@link decodeWindows1252} already does with its own hand-picked table. Unlike windows-1252, a byte these encodings leave without a character throws rather than decoding to a C1 control: windows-1252's own gaps are given C1 controls by the Encoding Standard itself so that its decoder is total, but the standard leaves every other legacy single-byte encoding's gaps genuinely undefined, so a caller naming one of these for bytes that hit a gap gets a loud, actionable refusal instead of a silently wrong character. */
857
931
  function decodeLegacySingleByte(bytes, table, label) {
858
932
  const units = [];
@@ -862,7 +936,7 @@ function decodeLegacySingleByte(bytes, table, label) {
862
936
  continue;
863
937
  }
864
938
  const unit = table.charCodeAt(byte - FIRST_HIGH_BYTE);
865
- if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(16)}`);
939
+ if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(HEX_RADIX)}`);
866
940
  units.push(unit);
867
941
  }
868
942
  return fromCodeUnits(units);
@@ -1264,6 +1338,13 @@ function resolveEncodingLabel(label) {
1264
1338
  }
1265
1339
  //#endregion
1266
1340
  //#region src/image/png-filter.ts
1341
+ const PNG_FILTER_NONE = 0;
1342
+ const PNG_FILTER_SUB = 1;
1343
+ const PNG_FILTER_UP = 2;
1344
+ const PNG_FILTER_AVERAGE = 3;
1345
+ const PNG_FILTER_PAETH = 4;
1346
+ const BYTE_MASK = 255;
1347
+ const BYTE_MODULUS = 256;
1267
1348
  function paethPredictor(a, b, c) {
1268
1349
  const p = a + b - c;
1269
1350
  const pa = Math.abs(p - a);
@@ -1275,13 +1356,13 @@ function paethPredictor(a, b, c) {
1275
1356
  return c;
1276
1357
  }
1277
1358
  function isPngFilterType(value) {
1278
- return value === 0 || value === 1 || value === 2 || value === 3 || value === 4;
1359
+ return value === PNG_FILTER_NONE || value === PNG_FILTER_SUB || value === PNG_FILTER_UP || value === PNG_FILTER_AVERAGE || value === PNG_FILTER_PAETH;
1279
1360
  }
1280
1361
  function predictorValue(filterType, a, b, c) {
1281
- if (filterType === 1) return a;
1282
- if (filterType === 2) return b;
1283
- if (filterType === 3) return Math.floor((a + b) / 2);
1284
- if (filterType === 4) return paethPredictor(a, b, c);
1362
+ if (filterType === PNG_FILTER_SUB) return a;
1363
+ if (filterType === PNG_FILTER_UP) return b;
1364
+ if (filterType === PNG_FILTER_AVERAGE) return Math.floor((a + b) / 2);
1365
+ if (filterType === PNG_FILTER_PAETH) return paethPredictor(a, b, c);
1285
1366
  return 0;
1286
1367
  }
1287
1368
  function unfilterScanlines(data, height, bytesPerRow, bpp) {
@@ -1299,7 +1380,7 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
1299
1380
  const a = x >= bpp ? out[outRowStart + x - bpp] : 0;
1300
1381
  const b = prevOutRowStart === void 0 ? 0 : out[prevOutRowStart + x];
1301
1382
  const c = x >= bpp && prevOutRowStart !== void 0 ? out[prevOutRowStart + x - bpp] : 0;
1302
- out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & 255;
1383
+ out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK;
1303
1384
  });
1304
1385
  }
1305
1386
  return out;
@@ -1307,48 +1388,48 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
1307
1388
  function filterRowInto(current, previous, bpp, filterType, target) {
1308
1389
  let sum = 0;
1309
1390
  switch (filterType) {
1310
- case 1:
1391
+ case PNG_FILTER_SUB:
1311
1392
  target.forEach((_byte, x) => {
1312
- const filtered = current[x + bpp] - current[x] & 255;
1393
+ const filtered = current[x + bpp] - current[x] & BYTE_MASK;
1313
1394
  target[x] = filtered;
1314
- sum += Math.min(filtered, 256 - filtered);
1395
+ sum += Math.min(filtered, BYTE_MODULUS - filtered);
1315
1396
  });
1316
1397
  break;
1317
- case 2:
1398
+ case PNG_FILTER_UP:
1318
1399
  target.forEach((_byte, x) => {
1319
- const filtered = current[x + bpp] - previous[x + bpp] & 255;
1400
+ const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK;
1320
1401
  target[x] = filtered;
1321
- sum += Math.min(filtered, 256 - filtered);
1402
+ sum += Math.min(filtered, BYTE_MODULUS - filtered);
1322
1403
  });
1323
1404
  break;
1324
- case 3:
1405
+ case PNG_FILTER_AVERAGE:
1325
1406
  target.forEach((_byte, x) => {
1326
- const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & 255;
1407
+ const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK;
1327
1408
  target[x] = filtered;
1328
- sum += Math.min(filtered, 256 - filtered);
1409
+ sum += Math.min(filtered, BYTE_MODULUS - filtered);
1329
1410
  });
1330
1411
  break;
1331
- case 4:
1412
+ case PNG_FILTER_PAETH:
1332
1413
  target.forEach((_byte, x) => {
1333
- const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & 255;
1414
+ const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK;
1334
1415
  target[x] = filtered;
1335
- sum += Math.min(filtered, 256 - filtered);
1416
+ sum += Math.min(filtered, BYTE_MODULUS - filtered);
1336
1417
  });
1337
1418
  break;
1338
- case 0: target.forEach((_byte, x) => {
1419
+ case PNG_FILTER_NONE: target.forEach((_byte, x) => {
1339
1420
  const filtered = current[x + bpp];
1340
1421
  target[x] = filtered;
1341
- sum += Math.min(filtered, 256 - filtered);
1422
+ sum += Math.min(filtered, BYTE_MODULUS - filtered);
1342
1423
  });
1343
1424
  }
1344
1425
  return sum;
1345
1426
  }
1346
1427
  const ALL_FILTER_TYPES = [
1347
- 0,
1348
- 1,
1349
- 2,
1350
- 3,
1351
- 4
1428
+ PNG_FILTER_NONE,
1429
+ PNG_FILTER_SUB,
1430
+ PNG_FILTER_UP,
1431
+ PNG_FILTER_AVERAGE,
1432
+ PNG_FILTER_PAETH
1352
1433
  ];
1353
1434
  function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1354
1435
  const stride = bytesPerRow + 1;
@@ -1357,10 +1438,10 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1357
1438
  let previous = new Uint8Array(bytesPerRow + bpp);
1358
1439
  let candidate = new Uint8Array(bytesPerRow);
1359
1440
  let best = new Uint8Array(bytesPerRow);
1360
- const filterTypes = strategy === "none" ? [0] : ALL_FILTER_TYPES;
1441
+ const filterTypes = strategy === "none" ? [PNG_FILTER_NONE] : ALL_FILTER_TYPES;
1361
1442
  Array.from({ length: height }).forEach((_row, y) => {
1362
1443
  current.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow), bpp);
1363
- let bestType = 0;
1444
+ let bestType = PNG_FILTER_NONE;
1364
1445
  let bestSum = Number.POSITIVE_INFINITY;
1365
1446
  for (const filterType of filterTypes) {
1366
1447
  const sum = filterRowInto(current, previous, bpp, filterType, candidate);
@@ -1378,24 +1459,44 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1378
1459
  }
1379
1460
  //#endregion
1380
1461
  //#region src/image/png-encode.ts
1462
+ const PNG_SIG_HIGH_BIT_MARKER$1 = 137;
1463
+ const PNG_SIG_P$1 = 80;
1464
+ const PNG_SIG_N$1 = 78;
1465
+ const PNG_SIG_G$1 = 71;
1466
+ const PNG_SIG_CR$1 = 13;
1467
+ const PNG_SIG_LF$1 = 10;
1381
1468
  const PNG_SIGNATURE$1 = new Uint8Array([
1382
- 137,
1383
- 80,
1384
- 78,
1385
- 71,
1386
- 13,
1387
- 10,
1469
+ PNG_SIG_HIGH_BIT_MARKER$1,
1470
+ PNG_SIG_P$1,
1471
+ PNG_SIG_N$1,
1472
+ PNG_SIG_G$1,
1473
+ PNG_SIG_CR$1,
1474
+ PNG_SIG_LF$1,
1388
1475
  26,
1389
- 10
1476
+ PNG_SIG_LF$1
1390
1477
  ]);
1391
1478
  const MAX_PALETTE_ENTRIES = 256;
1479
+ const BYTES_PER_UINT32 = 4;
1480
+ const IHDR_BYTE_LENGTH = 13;
1481
+ const IHDR_HEIGHT_OFFSET$1 = 4;
1482
+ const PNG_BIT_DEPTH_8 = 8;
1483
+ const PNG_COLOR_TYPE_GRAY = 0;
1484
+ const PNG_COLOR_TYPE_RGB = 2;
1485
+ const PNG_COLOR_TYPE_INDEXED$1 = 3;
1486
+ const PNG_COLOR_TYPE_GRAY_ALPHA$1 = 4;
1487
+ const PNG_COLOR_TYPE_RGBA$1 = 6;
1488
+ const RGB_CHANNELS$1 = 3;
1489
+ const OPAQUE_ALPHA$1 = 255;
1490
+ const GREEN_SHIFT = 8;
1491
+ const BLUE_SHIFT = 16;
1492
+ const ALPHA_SHIFT = 24;
1392
1493
  const PNG_MAX_DIMENSION = 2147483647;
1393
1494
  const PNG_MAX_PIXELS = 1e8;
1394
1495
  function exceedsMaxPixelCount(pixelCount) {
1395
1496
  return pixelCount > PNG_MAX_PIXELS;
1396
1497
  }
1397
1498
  function u32be(value) {
1398
- const bytes = /* @__PURE__ */ new Uint8Array(4);
1499
+ const bytes = new Uint8Array(BYTES_PER_UINT32);
1399
1500
  new DataView(bytes.buffer).setUint32(0, value);
1400
1501
  return bytes;
1401
1502
  }
@@ -1407,11 +1508,11 @@ function writeChunk(writer, type, data) {
1407
1508
  writer.writeBytes(u32be(crc32(concatBytes([typeBytes, data]))));
1408
1509
  }
1409
1510
  function writeIhdr(writer, width, height, colorType) {
1410
- const ihdr = /* @__PURE__ */ new Uint8Array(13);
1511
+ const ihdr = new Uint8Array(IHDR_BYTE_LENGTH);
1411
1512
  const ihdrView = new DataView(ihdr.buffer);
1412
1513
  ihdrView.setUint32(0, width);
1413
- ihdrView.setUint32(4, height);
1414
- ihdr[8] = 8;
1514
+ ihdrView.setUint32(IHDR_HEIGHT_OFFSET$1, height);
1515
+ ihdr[8] = PNG_BIT_DEPTH_8;
1415
1516
  ihdr[9] = colorType;
1416
1517
  ihdr[10] = 0;
1417
1518
  ihdr[11] = 0;
@@ -1419,8 +1520,8 @@ function writeIhdr(writer, width, height, colorType) {
1419
1520
  writeChunk(writer, "IHDR", ihdr);
1420
1521
  }
1421
1522
  function colorTypeFor(image) {
1422
- if (image.channels === 1) return image.alpha === void 0 ? 0 : 4;
1423
- return image.alpha === void 0 ? 2 : 6;
1523
+ if (image.channels === 1) return image.alpha === void 0 ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA$1;
1524
+ return image.alpha === void 0 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGBA$1;
1424
1525
  }
1425
1526
  function detectPalette(image) {
1426
1527
  const { width, height, data, alpha } = image;
@@ -1430,12 +1531,12 @@ function detectPalette(image) {
1430
1531
  const paletteRgb = [];
1431
1532
  const paletteAlpha = [];
1432
1533
  for (let i = 0; i < pixelCount; i++) {
1433
- const base = i * 3;
1534
+ const base = i * RGB_CHANNELS$1;
1434
1535
  const r = data[base] ?? 0;
1435
1536
  const g = data[base + 1] ?? 0;
1436
1537
  const b = data[base + 2] ?? 0;
1437
- const a = alpha === void 0 ? 255 : alpha[i] ?? 0;
1438
- const key = r | g << 8 | b << 16 | a << 24;
1538
+ const a = alpha === void 0 ? OPAQUE_ALPHA$1 : alpha[i] ?? 0;
1539
+ const key = r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
1439
1540
  let index = colorToIndex.get(key);
1440
1541
  if (index === void 0) {
1441
1542
  if (colorToIndex.size >= MAX_PALETTE_ENTRIES) return;
@@ -1452,7 +1553,7 @@ function detectPalette(image) {
1452
1553
  palette
1453
1554
  };
1454
1555
  let trnsLength = paletteAlpha.length;
1455
- while (trnsLength > 1 && paletteAlpha[trnsLength - 1] === 255) trnsLength--;
1556
+ while (trnsLength > 1 && paletteAlpha[trnsLength - 1] === OPAQUE_ALPHA$1) trnsLength--;
1456
1557
  return {
1457
1558
  indices,
1458
1559
  palette,
@@ -1467,7 +1568,7 @@ function buildPng(writeBody) {
1467
1568
  return writer.toBytes();
1468
1569
  }
1469
1570
  function writeIndexedPng(writer, width, height, encoding, options) {
1470
- writeIhdr(writer, width, height, 3);
1571
+ writeIhdr(writer, width, height, PNG_COLOR_TYPE_INDEXED$1);
1471
1572
  writeChunk(writer, "PLTE", encoding.palette);
1472
1573
  if (encoding.trns !== void 0) writeChunk(writer, "tRNS", encoding.trns);
1473
1574
  writeChunk(writer, "IDAT", deflate(filterScanlines(encoding.indices, height, width, 1, options.filter ?? "adaptive")));
@@ -1490,7 +1591,7 @@ function encodePng(image, options = {}) {
1490
1591
  if (!Number.isInteger(image.width) || image.width <= 0 || image.width > 2147483647 || !Number.isInteger(image.height) || image.height <= 0 || image.height > 2147483647) throw new Error(`cannot encode a PNG with an invalid dimension (width=${image.width}, height=${image.height}); the PNG spec's IHDR section requires both width and height to be positive integers no greater than ${PNG_MAX_DIMENSION}`);
1491
1592
  const pixelCount = image.width * image.height;
1492
1593
  if (exceedsMaxPixelCount(pixelCount)) throw new Error(`cannot encode a PNG with ${pixelCount} pixels (width=${image.width}, height=${image.height}); each dimension is individually within the PNG spec's own limit, but this encoder bounds their product to ${PNG_MAX_PIXELS} to avoid an unbounded per-pixel scan and allocation`);
1493
- const paletteEncoding = image.channels === 3 ? detectPalette(image) : void 0;
1594
+ const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
1494
1595
  if (paletteEncoding === void 0) return buildPng((writer) => {
1495
1596
  writeTruecolorPng(writer, image, options);
1496
1597
  });
@@ -1504,16 +1605,38 @@ function encodePng(image, options = {}) {
1504
1605
  }
1505
1606
  //#endregion
1506
1607
  //#region src/image/png-decode.ts
1608
+ const PNG_SIG_HIGH_BIT_MARKER = 137;
1609
+ const PNG_SIG_P = 80;
1610
+ const PNG_SIG_N = 78;
1611
+ const PNG_SIG_G = 71;
1612
+ const PNG_SIG_CR = 13;
1613
+ const PNG_SIG_LF = 10;
1507
1614
  const PNG_SIGNATURE = [
1508
- 137,
1509
- 80,
1510
- 78,
1511
- 71,
1512
- 13,
1513
- 10,
1615
+ PNG_SIG_HIGH_BIT_MARKER,
1616
+ PNG_SIG_P,
1617
+ PNG_SIG_N,
1618
+ PNG_SIG_G,
1619
+ PNG_SIG_CR,
1620
+ PNG_SIG_LF,
1514
1621
  26,
1515
- 10
1622
+ PNG_SIG_LF
1516
1623
  ];
1624
+ const CHUNK_LENGTH_FIELD_BYTES = 4;
1625
+ const CHUNK_HEADER_BYTES = 8;
1626
+ const CHUNK_CRC_FIELD_BYTES = 4;
1627
+ const IHDR_HEIGHT_OFFSET = 4;
1628
+ const RGB_CHANNELS = 3;
1629
+ const RGBA_CHANNELS = 4;
1630
+ const ALPHA_CHANNEL_OFFSET = 3;
1631
+ const BITS_PER_BYTE$1 = 8;
1632
+ const BYTE_SHIFT = 3;
1633
+ const BYTE_BIT_MASK = 7;
1634
+ const MAX_SAMPLE_VALUE = 255;
1635
+ const OPAQUE_ALPHA = 255;
1636
+ const PNG_BIT_DEPTH_16 = 16;
1637
+ const PNG_COLOR_TYPE_INDEXED = 3;
1638
+ const PNG_COLOR_TYPE_GRAY_ALPHA = 4;
1639
+ const PNG_COLOR_TYPE_RGBA = 6;
1517
1640
  function requireDataView(bytes) {
1518
1641
  return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1519
1642
  }
@@ -1521,13 +1644,13 @@ function readChunks(bytes, onWarning) {
1521
1644
  const chunks = [];
1522
1645
  const view = requireDataView(bytes);
1523
1646
  let offset = PNG_SIGNATURE.length;
1524
- while (offset + 8 <= bytes.length) {
1647
+ while (offset + CHUNK_HEADER_BYTES <= bytes.length) {
1525
1648
  const length = view.getUint32(offset);
1526
- const typeBytes = bytes.subarray(offset + 4, offset + 8);
1649
+ const typeBytes = bytes.subarray(offset + CHUNK_LENGTH_FIELD_BYTES, offset + CHUNK_HEADER_BYTES);
1527
1650
  const type = new TextDecoder("latin1").decode(typeBytes);
1528
- const dataStart = offset + 8;
1651
+ const dataStart = offset + CHUNK_HEADER_BYTES;
1529
1652
  const dataEnd = dataStart + length;
1530
- if (dataEnd + 4 > bytes.length) throw new Error(`PNG chunk '${type}' declares a length that runs past the end of the file`);
1653
+ if (dataEnd + CHUNK_CRC_FIELD_BYTES > bytes.length) throw new Error(`PNG chunk '${type}' declares a length that runs past the end of the file`);
1531
1654
  const data = bytes.subarray(dataStart, dataEnd);
1532
1655
  if (onWarning !== void 0) {
1533
1656
  if (view.getUint32(dataEnd) !== crc32(concatBytes([typeBytes, data]))) onWarning(`PNG chunk '${type}' failed its CRC32 check`);
@@ -1536,7 +1659,7 @@ function readChunks(bytes, onWarning) {
1536
1659
  type,
1537
1660
  data
1538
1661
  });
1539
- offset = dataEnd + 4;
1662
+ offset = dataEnd + CHUNK_CRC_FIELD_BYTES;
1540
1663
  if (type === "IEND") break;
1541
1664
  }
1542
1665
  return chunks;
@@ -1545,7 +1668,7 @@ function parseIhdr(data) {
1545
1668
  const view = requireDataView(data);
1546
1669
  return {
1547
1670
  width: view.getUint32(0),
1548
- height: view.getUint32(4),
1671
+ height: view.getUint32(IHDR_HEIGHT_OFFSET),
1549
1672
  bitDepth: data[8],
1550
1673
  colorType: data[9],
1551
1674
  interlace: data[12]
@@ -1553,17 +1676,17 @@ function parseIhdr(data) {
1553
1676
  }
1554
1677
  function channelsForColorType(colorType) {
1555
1678
  if (colorType === 0) return 1;
1556
- if (colorType === 2) return 3;
1557
- if (colorType === 3) return 1;
1558
- if (colorType === 4) return 2;
1559
- if (colorType === 6) return 4;
1679
+ if (colorType === 2) return RGB_CHANNELS;
1680
+ if (colorType === PNG_COLOR_TYPE_INDEXED) return 1;
1681
+ if (colorType === PNG_COLOR_TYPE_GRAY_ALPHA) return 2;
1682
+ if (colorType === PNG_COLOR_TYPE_RGBA) return RGBA_CHANNELS;
1560
1683
  throw new Error(`unsupported PNG colour type: ${colorType}`);
1561
1684
  }
1562
1685
  function filterBpp(bitDepth, channels) {
1563
- return Math.max(1, Math.ceil(bitDepth * channels / 8));
1686
+ return Math.max(1, Math.ceil(bitDepth * channels / BITS_PER_BYTE$1));
1564
1687
  }
1565
1688
  function unpackRow(rowBytes, samples, bitDepth) {
1566
- if (bitDepth === 16) {
1689
+ if (bitDepth === PNG_BIT_DEPTH_16) {
1567
1690
  samples.forEach((_sample, i) => {
1568
1691
  samples[i] = rowBytes[i * 2];
1569
1692
  });
@@ -1572,8 +1695,8 @@ function unpackRow(rowBytes, samples, bitDepth) {
1572
1695
  const mask = (1 << bitDepth) - 1;
1573
1696
  samples.forEach((_sample, i) => {
1574
1697
  const bitOffset = i * bitDepth;
1575
- const byteIndex = bitOffset >> 3;
1576
- const shift = 8 - bitDepth - (bitOffset & 7);
1698
+ const byteIndex = bitOffset >> BYTE_SHIFT;
1699
+ const shift = BITS_PER_BYTE$1 - bitDepth - (bitOffset & BYTE_BIT_MASK);
1577
1700
  samples[i] = rowBytes[byteIndex] >> shift & mask;
1578
1701
  });
1579
1702
  }
@@ -1585,13 +1708,13 @@ function readTrnsRgbKey(trns) {
1585
1708
  return [
1586
1709
  view.getUint16(0),
1587
1710
  view.getUint16(2),
1588
- view.getUint16(4)
1711
+ view.getUint16(IHDR_HEIGHT_OFFSET)
1589
1712
  ];
1590
1713
  }
1591
1714
  function scaleToByte(sample, bitDepth) {
1592
- if (bitDepth === 16) return sample;
1715
+ if (bitDepth === PNG_BIT_DEPTH_16) return sample;
1593
1716
  const maxSample = (1 << bitDepth) - 1;
1594
- return Math.round(sample * 255 / maxSample);
1717
+ return Math.round(sample * MAX_SAMPLE_VALUE / maxSample);
1595
1718
  }
1596
1719
  function decodePng(bytes, options = {}) {
1597
1720
  for (let i = 0; i < PNG_SIGNATURE.length; i++) if (bytes[i] !== PNG_SIGNATURE[i]) throw new Error("not a valid PNG file: bad signature");
@@ -1602,22 +1725,22 @@ function decodePng(bytes, options = {}) {
1602
1725
  if (ihdr.interlace !== 0) throw new Error("Adam7-interlaced PNG images are not supported");
1603
1726
  const channels = channelsForColorType(ihdr.colorType);
1604
1727
  const bpp = filterBpp(ihdr.bitDepth, channels);
1605
- const bytesPerRow = Math.ceil(ihdr.width * channels * ihdr.bitDepth / 8);
1728
+ const bytesPerRow = Math.ceil(ihdr.width * channels * ihdr.bitDepth / BITS_PER_BYTE$1);
1606
1729
  const idatChunks = chunks.filter((c) => c.type === "IDAT").map((c) => c.data);
1607
1730
  if (idatChunks.length === 0) throw new Error("PNG file has no IDAT chunks");
1608
1731
  const { bytes: inflated, recovered } = inflateTolerant(concatBytes(idatChunks));
1609
1732
  if (recovered && options.onWarning !== void 0) options.onWarning("PNG IDAT stream required tolerant recovery (truncated or malformed)");
1610
1733
  const unfiltered = unfilterScanlines(inflated, ihdr.height, bytesPerRow, bpp);
1611
1734
  const palette = chunks.find((c) => c.type === "PLTE")?.data;
1612
- if (ihdr.colorType === 3 && palette === void 0) throw new Error("indexed-colour PNG has no PLTE chunk");
1735
+ if (ihdr.colorType === PNG_COLOR_TYPE_INDEXED && palette === void 0) throw new Error("indexed-colour PNG has no PLTE chunk");
1613
1736
  const trns = chunks.find((c) => c.type === "tRNS")?.data;
1614
1737
  return buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns);
1615
1738
  }
1616
1739
  function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
1617
1740
  const { width, height, bitDepth, colorType } = ihdr;
1618
- const outChannels = colorType === 0 || colorType === 4 ? 1 : 3;
1741
+ const outChannels = colorType === 0 || colorType === PNG_COLOR_TYPE_GRAY_ALPHA ? 1 : RGB_CHANNELS;
1619
1742
  const data = new Uint8Array(width * height * outChannels);
1620
- const alpha = colorType === 4 || colorType === 6 || trns !== void 0 ? new Uint8Array(width * height).fill(255) : void 0;
1743
+ const alpha = colorType === PNG_COLOR_TYPE_GRAY_ALPHA || colorType === PNG_COLOR_TYPE_RGBA || trns !== void 0 ? new Uint8Array(width * height).fill(OPAQUE_ALPHA) : void 0;
1621
1744
  const trnsGray = colorType === 0 && trns !== void 0 ? readTrnsGrayValue(trns) : void 0;
1622
1745
  const trnsRgb = colorType === 2 && trns !== void 0 ? readTrnsRgbKey(trns) : void 0;
1623
1746
  const samples = new Uint8Array(width * channels);
@@ -1632,7 +1755,7 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
1632
1755
  if (colorType === 0) {
1633
1756
  const g = samples[pixelBase];
1634
1757
  data[outBase] = scaleToByte(g, bitDepth);
1635
- if (trnsGray !== void 0) alpha[alphaIndex] = g === trnsGray ? 0 : 255;
1758
+ if (trnsGray !== void 0) alpha[alphaIndex] = g === trnsGray ? 0 : OPAQUE_ALPHA;
1636
1759
  } else if (colorType === 2) {
1637
1760
  const r = samples[pixelBase];
1638
1761
  const g = samples[pixelBase + 1];
@@ -1642,15 +1765,15 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
1642
1765
  data[outBase + 2] = b;
1643
1766
  if (alpha !== void 0 && trnsRgb !== void 0) {
1644
1767
  const [kr, kg, kb] = trnsRgb;
1645
- alpha[alphaIndex] = r === kr && g === kg && b === kb ? 0 : 255;
1768
+ alpha[alphaIndex] = r === kr && g === kg && b === kb ? 0 : OPAQUE_ALPHA;
1646
1769
  }
1647
- } else if (colorType === 3) {
1770
+ } else if (colorType === PNG_COLOR_TYPE_INDEXED) {
1648
1771
  const index = samples[pixelBase];
1649
- data[outBase] = palette[index * 3];
1650
- data[outBase + 1] = palette[index * 3 + 1];
1651
- data[outBase + 2] = palette[index * 3 + 2];
1652
- if (alpha !== void 0 && trns !== void 0) alpha[alphaIndex] = index < trns.length ? trns[index] : 255;
1653
- } else if (colorType === 4) {
1772
+ data[outBase] = palette[index * RGB_CHANNELS];
1773
+ data[outBase + 1] = palette[index * RGB_CHANNELS + 1];
1774
+ data[outBase + 2] = palette[index * RGB_CHANNELS + 2];
1775
+ if (alpha !== void 0 && trns !== void 0) alpha[alphaIndex] = index < trns.length ? trns[index] : OPAQUE_ALPHA;
1776
+ } else if (colorType === PNG_COLOR_TYPE_GRAY_ALPHA) {
1654
1777
  const g = samples[pixelBase];
1655
1778
  const a = samples[pixelBase + 1];
1656
1779
  data[outBase] = scaleToByte(g, bitDepth);
@@ -1659,7 +1782,7 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
1659
1782
  data[outBase] = samples[pixelBase];
1660
1783
  data[outBase + 1] = samples[pixelBase + 1];
1661
1784
  data[outBase + 2] = samples[pixelBase + 2];
1662
- if (alpha !== void 0) alpha[alphaIndex] = samples[pixelBase + 3];
1785
+ if (alpha !== void 0) alpha[alphaIndex] = samples[pixelBase + ALPHA_CHANNEL_OFFSET];
1663
1786
  }
1664
1787
  });
1665
1788
  });
@@ -1681,18 +1804,23 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
1681
1804
  const SOI = 216;
1682
1805
  const EOI = 217;
1683
1806
  const APP14 = 238;
1807
+ const SOF0 = 192;
1808
+ const SOF1 = 193;
1809
+ const SOF2 = 194;
1810
+ const SOF9 = 201;
1811
+ const SOF10 = 202;
1684
1812
  const SOF_MARKERS = /* @__PURE__ */ new Set([
1685
- 192,
1686
- 193,
1687
- 194,
1688
- 201,
1689
- 202
1813
+ SOF0,
1814
+ SOF1,
1815
+ SOF2,
1816
+ SOF9,
1817
+ SOF10
1690
1818
  ]);
1691
- const PROGRESSIVE_SOF_MARKERS = /* @__PURE__ */ new Set([194, 202]);
1819
+ const PROGRESSIVE_SOF_MARKERS = /* @__PURE__ */ new Set([SOF2, SOF10]);
1692
1820
  const NO_PAYLOAD_MARKERS = /* @__PURE__ */ new Set([
1693
1821
  1,
1694
- 216,
1695
- 217,
1822
+ SOI,
1823
+ EOI,
1696
1824
  208,
1697
1825
  209,
1698
1826
  210,
@@ -1702,40 +1830,46 @@ const NO_PAYLOAD_MARKERS = /* @__PURE__ */ new Set([
1702
1830
  214,
1703
1831
  215
1704
1832
  ]);
1833
+ const BITS_PER_BYTE = 8;
1834
+ const JPEG_MARKER_PREFIX = 255;
1835
+ const APP14_MIN_LENGTH_FOR_TRANSFORM = 14;
1836
+ const APP14_TRANSFORM_OFFSET = 11;
1837
+ const SOF_WIDTH_OFFSET = 3;
1838
+ const SOF_COMPONENTS_OFFSET = 5;
1705
1839
  function requireByte(bytes, index) {
1706
1840
  const value = bytes[index];
1707
1841
  if (value === void 0) throw new Error("unexpected end of JPEG data");
1708
1842
  return value;
1709
1843
  }
1710
1844
  function readUint16BE(bytes, offset) {
1711
- return requireByte(bytes, offset) << 8 | requireByte(bytes, offset + 1);
1845
+ return requireByte(bytes, offset) << BITS_PER_BYTE | requireByte(bytes, offset + 1);
1712
1846
  }
1713
1847
  function readJpegInfo(bytes) {
1714
- if (requireByte(bytes, 0) !== 255 || requireByte(bytes, 1) !== SOI) throw new Error("not a valid JPEG file: missing SOI marker");
1848
+ if (requireByte(bytes, 0) !== JPEG_MARKER_PREFIX || requireByte(bytes, 1) !== SOI) throw new Error("not a valid JPEG file: missing SOI marker");
1715
1849
  let offset = 2;
1716
1850
  let adobeTransform;
1717
1851
  while (bytes[offset] !== void 0) {
1718
- if (bytes[offset] !== 255) {
1852
+ if (bytes[offset] !== JPEG_MARKER_PREFIX) {
1719
1853
  offset++;
1720
1854
  continue;
1721
1855
  }
1722
1856
  let markerOffset = offset + 1;
1723
- while (bytes[markerOffset] === 255) markerOffset++;
1857
+ while (bytes[markerOffset] === JPEG_MARKER_PREFIX) markerOffset++;
1724
1858
  const marker = bytes[markerOffset];
1725
1859
  if (marker === void 0) break;
1726
1860
  offset = markerOffset + 1;
1727
1861
  if (marker === EOI) break;
1728
1862
  if (NO_PAYLOAD_MARKERS.has(marker)) continue;
1729
1863
  const segmentLength = readUint16BE(bytes, offset);
1730
- if (marker === APP14 && segmentLength >= 14) adobeTransform = requireByte(bytes, offset + 2 + 11);
1864
+ if (marker === APP14 && segmentLength >= APP14_MIN_LENGTH_FOR_TRANSFORM) adobeTransform = requireByte(bytes, offset + 2 + APP14_TRANSFORM_OFFSET);
1731
1865
  if (SOF_MARKERS.has(marker)) {
1732
1866
  const p = offset + 2;
1733
1867
  const precision = requireByte(bytes, p);
1734
1868
  const height = readUint16BE(bytes, p + 1);
1735
1869
  return {
1736
- width: readUint16BE(bytes, p + 3),
1870
+ width: readUint16BE(bytes, p + SOF_WIDTH_OFFSET),
1737
1871
  height,
1738
- components: requireByte(bytes, p + 5),
1872
+ components: requireByte(bytes, p + SOF_COMPONENTS_OFFSET),
1739
1873
  precision,
1740
1874
  progressive: PROGRESSIVE_SOF_MARKERS.has(marker),
1741
1875
  adobeTransform