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/README.md +1 -1
- package/dist/index.cjs +321 -187
- package/dist/index.d.cts +2 -6
- package/dist/index.d.ts +2 -6
- package/dist/index.js +321 -187
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -103,6 +103,15 @@ const DECODE = (() => {
|
|
|
103
103
|
})();
|
|
104
104
|
/** 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. */
|
|
105
105
|
const BASE64_ENCODE_CHUNK_CHARS = 32768;
|
|
106
|
+
const BASE64_GROUP_INPUT_BYTES = 3;
|
|
107
|
+
const BASE64_GROUP_OUTPUT_CHARS = 4;
|
|
108
|
+
const BASE64_GROUP_LAST_CHAR_OFFSET = 3;
|
|
109
|
+
const TWO_BIT_SHIFT = 2;
|
|
110
|
+
const FOUR_BIT_SHIFT = 4;
|
|
111
|
+
const SIX_BIT_SHIFT = 6;
|
|
112
|
+
const LOW_TWO_BITS_MASK = 3;
|
|
113
|
+
const LOW_FOUR_BITS_MASK = 15;
|
|
114
|
+
const LOW_SIX_BITS_MASK = 63;
|
|
106
115
|
/**
|
|
107
116
|
* Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
|
|
108
117
|
*
|
|
@@ -113,19 +122,19 @@ const BASE64_ENCODE_CHUNK_CHARS = 32768;
|
|
|
113
122
|
function bytesToBase64(bytes) {
|
|
114
123
|
const len = bytes.length;
|
|
115
124
|
const codes = new Array(BASE64_ENCODE_CHUNK_CHARS);
|
|
116
|
-
const chunkBytes = codes.length /
|
|
125
|
+
const chunkBytes = codes.length / BASE64_GROUP_OUTPUT_CHARS * BASE64_GROUP_INPUT_BYTES;
|
|
117
126
|
return Array.from({ length: Math.ceil(len / chunkBytes) }, (_unused, chunk) => {
|
|
118
127
|
const start = chunk * chunkBytes;
|
|
119
128
|
const end = Math.min(start + chunkBytes, len);
|
|
120
129
|
let filled = 0;
|
|
121
|
-
for (let index = start; index < end; index +=
|
|
130
|
+
for (let index = start; index < end; index += BASE64_GROUP_INPUT_BYTES) {
|
|
122
131
|
const b0 = bytes[index] ?? 0;
|
|
123
132
|
const b1 = bytes[index + 1] ?? 0;
|
|
124
133
|
const b2 = bytes[index + 2] ?? 0;
|
|
125
|
-
codes[filled++] = TABLE.charCodeAt(b0 >>
|
|
126
|
-
codes[filled++] = TABLE.charCodeAt((b0 &
|
|
127
|
-
codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 &
|
|
128
|
-
codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 &
|
|
134
|
+
codes[filled++] = TABLE.charCodeAt(b0 >> TWO_BIT_SHIFT);
|
|
135
|
+
codes[filled++] = TABLE.charCodeAt((b0 & LOW_TWO_BITS_MASK) << FOUR_BIT_SHIFT | b1 >> FOUR_BIT_SHIFT);
|
|
136
|
+
codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 & LOW_FOUR_BITS_MASK) << TWO_BIT_SHIFT | b2 >> SIX_BIT_SHIFT) : PADDING_CODE;
|
|
137
|
+
codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 & LOW_SIX_BITS_MASK) : PADDING_CODE;
|
|
129
138
|
}
|
|
130
139
|
return String.fromCharCode.apply(null, codes.slice(0, filled));
|
|
131
140
|
}).join("");
|
|
@@ -141,19 +150,19 @@ function bytesToBase64(bytes) {
|
|
|
141
150
|
function base64ToBytes(base64) {
|
|
142
151
|
const clean = base64.replace(/[^A-Za-z0-9+/=]/g, "");
|
|
143
152
|
const out = [];
|
|
144
|
-
for (let index = 0; index < clean.length; index +=
|
|
153
|
+
for (let index = 0; index < clean.length; index += BASE64_GROUP_OUTPUT_CHARS) {
|
|
145
154
|
const c0 = DECODE[clean.charCodeAt(index)] ?? DECODE_MISS;
|
|
146
155
|
const c1 = DECODE[clean.charCodeAt(index + 1)] ?? DECODE_MISS;
|
|
147
156
|
const c2 = clean.charCodeAt(index + 2);
|
|
148
|
-
const c3 = clean.charCodeAt(index +
|
|
157
|
+
const c3 = clean.charCodeAt(index + BASE64_GROUP_LAST_CHAR_OFFSET);
|
|
149
158
|
if (c0 === DECODE_MISS || c1 === DECODE_MISS) throw new Error("invalid base64 input");
|
|
150
|
-
out.push(c0 <<
|
|
159
|
+
out.push(c0 << TWO_BIT_SHIFT | c1 >> FOUR_BIT_SHIFT);
|
|
151
160
|
if (c2 !== PADDING_CODE) {
|
|
152
161
|
const d2 = DECODE[c2] ?? DECODE_MISS;
|
|
153
|
-
out.push((c1 &
|
|
162
|
+
out.push((c1 & LOW_FOUR_BITS_MASK) << FOUR_BIT_SHIFT | d2 >> TWO_BIT_SHIFT);
|
|
154
163
|
if (c3 !== PADDING_CODE) {
|
|
155
164
|
const d3 = DECODE[c3] ?? DECODE_MISS;
|
|
156
|
-
out.push((d2 &
|
|
165
|
+
out.push((d2 & LOW_TWO_BITS_MASK) << SIX_BIT_SHIFT | d3);
|
|
157
166
|
}
|
|
158
167
|
}
|
|
159
168
|
}
|
|
@@ -163,23 +172,23 @@ function base64ToBytes(base64) {
|
|
|
163
172
|
//#region src/bytes/crc32.ts
|
|
164
173
|
const CRC32_POLYNOMIAL = 3988292384;
|
|
165
174
|
const BYTE_VALUES = 256;
|
|
166
|
-
const BITS_PER_BYTE = 8;
|
|
175
|
+
const BITS_PER_BYTE$2 = 8;
|
|
176
|
+
const BYTE_MASK$1 = 255;
|
|
177
|
+
const CRC32_ALL_ONES = 4294967295;
|
|
167
178
|
const CRC32_TABLE = (() => {
|
|
168
179
|
const table = new Uint32Array(BYTE_VALUES);
|
|
169
180
|
for (let n = 0; n < BYTE_VALUES; n++) {
|
|
170
181
|
let c = n;
|
|
171
|
-
for (let k = 0; k < BITS_PER_BYTE; k++) c = (c & 1) === 1 ? CRC32_POLYNOMIAL ^ c >>> 1 : c >>> 1;
|
|
182
|
+
for (let k = 0; k < BITS_PER_BYTE$2; k++) c = (c & 1) === 1 ? CRC32_POLYNOMIAL ^ c >>> 1 : c >>> 1;
|
|
172
183
|
table[n] = c >>> 0;
|
|
173
184
|
}
|
|
174
185
|
return table;
|
|
175
186
|
})();
|
|
176
187
|
function crc32(bytes) {
|
|
177
|
-
let crc =
|
|
178
|
-
for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) &
|
|
179
|
-
return (crc ^
|
|
188
|
+
let crc = CRC32_ALL_ONES;
|
|
189
|
+
for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$1] ^ crc >>> BITS_PER_BYTE$2;
|
|
190
|
+
return (crc ^ CRC32_ALL_ONES) >>> 0;
|
|
180
191
|
}
|
|
181
|
-
//#endregion
|
|
182
|
-
//#region src/bytes/flate.ts
|
|
183
192
|
const MAX_INFLATE_OUTPUT_BYTES = 536870912;
|
|
184
193
|
function deflate(data, level) {
|
|
185
194
|
return (0, fflate.zlibSync)(data, level === void 0 ? void 0 : { level });
|
|
@@ -256,6 +265,10 @@ const GB18030_RANGES = pairs("[[0,128],[36,165],[38,169],[45,178],[50,184],[81,2
|
|
|
256
265
|
const REPLACEMENT_CHARACTER_CODE_UNIT = 65533;
|
|
257
266
|
/** 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. */
|
|
258
267
|
const ASCII_BYTE_MAX = 127;
|
|
268
|
+
const HEX_RADIX$2 = 16;
|
|
269
|
+
/** 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). */
|
|
270
|
+
const KATAKANA_BYTE_START = 161;
|
|
271
|
+
const KATAKANA_BYTE_END = 223;
|
|
259
272
|
/**
|
|
260
273
|
* 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.
|
|
261
274
|
*
|
|
@@ -278,13 +291,23 @@ function truncated$1(label) {
|
|
|
278
291
|
/**
|
|
279
292
|
* 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.
|
|
280
293
|
*/
|
|
294
|
+
const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON = 1133;
|
|
295
|
+
const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON = 1135;
|
|
296
|
+
const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON_LOWER = 1164;
|
|
297
|
+
const BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON_LOWER = 1166;
|
|
298
|
+
const LATIN_E_CIRCUMFLEX = 202;
|
|
299
|
+
const LATIN_E_CIRCUMFLEX_LOWER = 234;
|
|
300
|
+
const COMBINING_MACRON = 772;
|
|
301
|
+
const COMBINING_CARON = 780;
|
|
281
302
|
const BIG5_DOUBLE_CODE_POINT_POINTERS = /* @__PURE__ */ new Map([
|
|
282
|
-
[
|
|
283
|
-
[
|
|
284
|
-
[
|
|
285
|
-
[
|
|
303
|
+
[BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON, [LATIN_E_CIRCUMFLEX, COMBINING_MACRON]],
|
|
304
|
+
[BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON, [LATIN_E_CIRCUMFLEX, COMBINING_CARON]],
|
|
305
|
+
[BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_MACRON_LOWER, [LATIN_E_CIRCUMFLEX_LOWER, COMBINING_MACRON]],
|
|
306
|
+
[BIG5_DOUBLE_POINTER_E_CIRCUMFLEX_CARON_LOWER, [LATIN_E_CIRCUMFLEX_LOWER, COMBINING_CARON]]
|
|
286
307
|
]);
|
|
287
308
|
/** 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. */
|
|
309
|
+
const LOW_TRAIL_BYTE_START = 64;
|
|
310
|
+
const LOW_TRAIL_BYTE_END = 126;
|
|
288
311
|
const LOW_TRAIL_BYTE_COUNT = 63;
|
|
289
312
|
/**
|
|
290
313
|
* 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.
|
|
@@ -294,7 +317,7 @@ const LOW_TRAIL_BYTE_COUNT = 63;
|
|
|
294
317
|
* @returns The pointer column `byte` contributes, or `undefined` when it names neither band.
|
|
295
318
|
*/
|
|
296
319
|
function twoByteTrailColumn(byte, highBandStart, highBandEnd) {
|
|
297
|
-
if (byte >=
|
|
320
|
+
if (byte >= LOW_TRAIL_BYTE_START && byte <= LOW_TRAIL_BYTE_END) return byte - LOW_TRAIL_BYTE_START;
|
|
298
321
|
if (byte >= highBandStart && byte <= highBandEnd) return byte - highBandStart + LOW_TRAIL_BYTE_COUNT;
|
|
299
322
|
}
|
|
300
323
|
/**
|
|
@@ -305,6 +328,16 @@ function twoByteTrailColumn(byte, highBandStart, highBandEnd) {
|
|
|
305
328
|
* @returns The decoded text.
|
|
306
329
|
* @throws UndecodableTextError When the bytes contain a byte or byte pair Shift_JIS leaves undefined, or end with an incomplete two-byte sequence.
|
|
307
330
|
*/
|
|
331
|
+
const SHIFT_JIS_LOW_LEAD_START = 129;
|
|
332
|
+
const SHIFT_JIS_LOW_LEAD_END = 159;
|
|
333
|
+
const SHIFT_JIS_HIGH_LEAD_DETECT_START = 224;
|
|
334
|
+
const SHIFT_JIS_HIGH_LEAD_OFFSET_ANCHOR = 193;
|
|
335
|
+
const SHIFT_JIS_TRAIL_HIGH_START = 128;
|
|
336
|
+
const SHIFT_JIS_TRAIL_HIGH_END = 252;
|
|
337
|
+
const SHIFT_JIS_COLUMNS = 188;
|
|
338
|
+
const SHIFT_JIS_EUDC_POINTER_START = 8836;
|
|
339
|
+
const SHIFT_JIS_EUDC_POINTER_END = 10715;
|
|
340
|
+
const SHIFT_JIS_SINGLE_BYTE_EXTRA = 128;
|
|
308
341
|
function decodeShiftJis(bytes) {
|
|
309
342
|
const sink = { units: [] };
|
|
310
343
|
let leading = 0;
|
|
@@ -312,22 +345,22 @@ function decodeShiftJis(bytes) {
|
|
|
312
345
|
if (leading !== 0) {
|
|
313
346
|
const leadingByte = leading;
|
|
314
347
|
leading = 0;
|
|
315
|
-
const leadingOffset = leadingByte <=
|
|
316
|
-
const column = twoByteTrailColumn(byte,
|
|
317
|
-
const pointer = column === void 0 ? void 0 : (leadingByte - leadingOffset) *
|
|
318
|
-
if (pointer !== void 0 && pointer >=
|
|
348
|
+
const leadingOffset = leadingByte <= SHIFT_JIS_LOW_LEAD_END ? SHIFT_JIS_LOW_LEAD_START : SHIFT_JIS_HIGH_LEAD_OFFSET_ANCHOR;
|
|
349
|
+
const column = twoByteTrailColumn(byte, SHIFT_JIS_TRAIL_HIGH_START, SHIFT_JIS_TRAIL_HIGH_END);
|
|
350
|
+
const pointer = column === void 0 ? void 0 : (leadingByte - leadingOffset) * SHIFT_JIS_COLUMNS + column;
|
|
351
|
+
if (pointer !== void 0 && pointer >= SHIFT_JIS_EUDC_POINTER_START && pointer <= SHIFT_JIS_EUDC_POINTER_END) {
|
|
319
352
|
appendCodePoint(sink, 48508 + pointer);
|
|
320
353
|
continue;
|
|
321
354
|
}
|
|
322
355
|
const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(JIS0208, pointer);
|
|
323
|
-
if (codePoint === void 0) malformed$1("Shift_JIS", `has no character for lead byte 0x${leadingByte.toString(
|
|
356
|
+
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)}`);
|
|
324
357
|
appendCodePoint(sink, codePoint);
|
|
325
358
|
continue;
|
|
326
359
|
}
|
|
327
|
-
if (byte <= ASCII_BYTE_MAX || byte ===
|
|
328
|
-
else if (byte >=
|
|
329
|
-
else if (byte <=
|
|
330
|
-
else malformed$1("Shift_JIS", `has no character for byte 0x${byte.toString(
|
|
360
|
+
if (byte <= ASCII_BYTE_MAX || byte === SHIFT_JIS_SINGLE_BYTE_EXTRA) sink.units.push(byte);
|
|
361
|
+
else if (byte >= KATAKANA_BYTE_START && byte <= KATAKANA_BYTE_END) appendCodePoint(sink, 65216 + byte);
|
|
362
|
+
else if (byte <= SHIFT_JIS_LOW_LEAD_END || byte >= SHIFT_JIS_HIGH_LEAD_DETECT_START && byte <= SHIFT_JIS_TRAIL_HIGH_END) leading = byte;
|
|
363
|
+
else malformed$1("Shift_JIS", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
|
|
331
364
|
}
|
|
332
365
|
if (leading !== 0) truncated$1("Shift_JIS");
|
|
333
366
|
return fromCodeUnits(sink.units);
|
|
@@ -340,17 +373,22 @@ function decodeShiftJis(bytes) {
|
|
|
340
373
|
* @returns The decoded text.
|
|
341
374
|
* @throws UndecodableTextError When the bytes contain a byte or byte pair EUC-JP leaves undefined, or end with an incomplete multi-byte sequence.
|
|
342
375
|
*/
|
|
376
|
+
const EUC_JP_KATAKANA_LEAD = 142;
|
|
377
|
+
const EUC_JP_JIS0212_LEAD = 143;
|
|
378
|
+
const EUC_JP_INDEX_BYTE_MIN = 161;
|
|
379
|
+
const EUC_JP_INDEX_BYTE_MAX = 254;
|
|
380
|
+
const EUC_JIS_COLUMNS = 94;
|
|
343
381
|
function decodeEucJp(bytes) {
|
|
344
382
|
const sink = { units: [] };
|
|
345
383
|
let leading = 0;
|
|
346
384
|
let jis0212 = false;
|
|
347
385
|
for (const byte of bytes) {
|
|
348
|
-
if (leading ===
|
|
386
|
+
if (leading === EUC_JP_KATAKANA_LEAD && byte >= KATAKANA_BYTE_START && byte <= KATAKANA_BYTE_END) {
|
|
349
387
|
leading = 0;
|
|
350
388
|
appendCodePoint(sink, 65216 + byte);
|
|
351
389
|
continue;
|
|
352
390
|
}
|
|
353
|
-
if (leading ===
|
|
391
|
+
if (leading === EUC_JP_JIS0212_LEAD && byte >= EUC_JP_INDEX_BYTE_MIN && byte <= EUC_JP_INDEX_BYTE_MAX) {
|
|
354
392
|
jis0212 = true;
|
|
355
393
|
leading = byte;
|
|
356
394
|
continue;
|
|
@@ -360,14 +398,14 @@ function decodeEucJp(bytes) {
|
|
|
360
398
|
leading = 0;
|
|
361
399
|
const usedJis0212 = jis0212;
|
|
362
400
|
jis0212 = false;
|
|
363
|
-
const codePoint = byte >=
|
|
364
|
-
if (codePoint === void 0) malformed$1("EUC-JP", `has no character for lead byte 0x${leadingByte.toString(
|
|
401
|
+
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;
|
|
402
|
+
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)}`);
|
|
365
403
|
appendCodePoint(sink, codePoint);
|
|
366
404
|
continue;
|
|
367
405
|
}
|
|
368
406
|
if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
|
|
369
|
-
else if (byte ===
|
|
370
|
-
else malformed$1("EUC-JP", `has no character for byte 0x${byte.toString(
|
|
407
|
+
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;
|
|
408
|
+
else malformed$1("EUC-JP", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
|
|
371
409
|
}
|
|
372
410
|
if (leading !== 0) truncated$1("EUC-JP");
|
|
373
411
|
return fromCodeUnits(sink.units);
|
|
@@ -380,6 +418,11 @@ function decodeEucJp(bytes) {
|
|
|
380
418
|
* @returns The decoded text.
|
|
381
419
|
* @throws UndecodableTextError When the bytes contain a byte or byte pair EUC-KR leaves undefined, or end with an incomplete two-byte sequence.
|
|
382
420
|
*/
|
|
421
|
+
const EUC_KR_LEAD_START = 129;
|
|
422
|
+
const EUC_KR_LEAD_END = 254;
|
|
423
|
+
const EUC_KR_TRAIL_START = 65;
|
|
424
|
+
const EUC_KR_TRAIL_END = 254;
|
|
425
|
+
const EUC_KR_COLUMNS = 190;
|
|
383
426
|
function decodeEucKr(bytes) {
|
|
384
427
|
const sink = { units: [] };
|
|
385
428
|
let leading = 0;
|
|
@@ -387,14 +430,14 @@ function decodeEucKr(bytes) {
|
|
|
387
430
|
if (leading !== 0) {
|
|
388
431
|
const leadingByte = leading;
|
|
389
432
|
leading = 0;
|
|
390
|
-
const codePoint = byte >=
|
|
391
|
-
if (codePoint === void 0) malformed$1("EUC-KR", `has no character for lead byte 0x${leadingByte.toString(
|
|
433
|
+
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;
|
|
434
|
+
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)}`);
|
|
392
435
|
appendCodePoint(sink, codePoint);
|
|
393
436
|
continue;
|
|
394
437
|
}
|
|
395
438
|
if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
|
|
396
|
-
else if (byte >=
|
|
397
|
-
else malformed$1("EUC-KR", `has no character for byte 0x${byte.toString(
|
|
439
|
+
else if (byte >= EUC_KR_LEAD_START && byte <= EUC_KR_LEAD_END) leading = byte;
|
|
440
|
+
else malformed$1("EUC-KR", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
|
|
398
441
|
}
|
|
399
442
|
if (leading !== 0) truncated$1("EUC-KR");
|
|
400
443
|
return fromCodeUnits(sink.units);
|
|
@@ -407,6 +450,11 @@ function decodeEucKr(bytes) {
|
|
|
407
450
|
* @returns The decoded text.
|
|
408
451
|
* @throws UndecodableTextError When the bytes contain a byte or byte pair Big5 leaves undefined, or end with an incomplete two-byte sequence.
|
|
409
452
|
*/
|
|
453
|
+
const BIG5_LEAD_START = 129;
|
|
454
|
+
const BIG5_LEAD_END = 254;
|
|
455
|
+
const BIG5_TRAIL_HIGH_START = 161;
|
|
456
|
+
const BIG5_TRAIL_HIGH_END = 254;
|
|
457
|
+
const BIG5_COLUMNS = 157;
|
|
410
458
|
function decodeBig5(bytes) {
|
|
411
459
|
const sink = { units: [] };
|
|
412
460
|
let leading = 0;
|
|
@@ -414,8 +462,8 @@ function decodeBig5(bytes) {
|
|
|
414
462
|
if (leading !== 0) {
|
|
415
463
|
const leadingByte = leading;
|
|
416
464
|
leading = 0;
|
|
417
|
-
const column = twoByteTrailColumn(byte,
|
|
418
|
-
const pointer = column === void 0 ? void 0 : (leadingByte -
|
|
465
|
+
const column = twoByteTrailColumn(byte, BIG5_TRAIL_HIGH_START, BIG5_TRAIL_HIGH_END);
|
|
466
|
+
const pointer = column === void 0 ? void 0 : (leadingByte - BIG5_LEAD_START) * BIG5_COLUMNS + column;
|
|
419
467
|
const doubled = pointer === void 0 ? void 0 : BIG5_DOUBLE_CODE_POINT_POINTERS.get(pointer);
|
|
420
468
|
if (doubled !== void 0) {
|
|
421
469
|
appendCodePoint(sink, doubled[0]);
|
|
@@ -423,13 +471,13 @@ function decodeBig5(bytes) {
|
|
|
423
471
|
continue;
|
|
424
472
|
}
|
|
425
473
|
const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(BIG5, pointer);
|
|
426
|
-
if (codePoint === void 0) malformed$1("Big5", `has no character for lead byte 0x${leadingByte.toString(
|
|
474
|
+
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)}`);
|
|
427
475
|
appendCodePoint(sink, codePoint);
|
|
428
476
|
continue;
|
|
429
477
|
}
|
|
430
478
|
if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
|
|
431
|
-
else if (byte >=
|
|
432
|
-
else malformed$1("Big5", `has no character for byte 0x${byte.toString(
|
|
479
|
+
else if (byte >= BIG5_LEAD_START && byte <= BIG5_LEAD_END) leading = byte;
|
|
480
|
+
else malformed$1("Big5", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
|
|
433
481
|
}
|
|
434
482
|
if (leading !== 0) truncated$1("Big5");
|
|
435
483
|
return fromCodeUnits(sink.units);
|
|
@@ -438,6 +486,19 @@ function decodeBig5(bytes) {
|
|
|
438
486
|
* 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.
|
|
439
487
|
*/
|
|
440
488
|
const GB18030_SECOND_FOURTH_BYTE_COUNT = 10;
|
|
489
|
+
/** 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. */
|
|
490
|
+
const GB18030_LEAD_START = 129;
|
|
491
|
+
const GB18030_LEAD_END = 254;
|
|
492
|
+
/** 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. */
|
|
493
|
+
const GB18030_DIGIT_BYTE_MIN = 48;
|
|
494
|
+
const GB18030_DIGIT_BYTE_MAX = 57;
|
|
495
|
+
/** 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. */
|
|
496
|
+
const GB18030_TRAIL_HIGH_START = 128;
|
|
497
|
+
const GB18030_TRAIL_HIGH_END = 254;
|
|
498
|
+
const GB18030_TWO_BYTE_COLUMNS = 190;
|
|
499
|
+
/** 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. */
|
|
500
|
+
const GB18030_SINGLE_BYTE_EURO = 128;
|
|
501
|
+
const EURO_SIGN_CODE_POINT = 8364;
|
|
441
502
|
/**
|
|
442
503
|
* 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.
|
|
443
504
|
* @param pointer - The four-byte pointer computed from a gb18030 lead, second, third and trailing byte.
|
|
@@ -471,43 +532,43 @@ function decodeGb18030(bytes) {
|
|
|
471
532
|
let third = 0;
|
|
472
533
|
for (const byte of bytes) {
|
|
473
534
|
if (third !== 0) {
|
|
474
|
-
if (byte <
|
|
475
|
-
const codePoint = gb18030RangesCodePoint((first -
|
|
535
|
+
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`);
|
|
536
|
+
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));
|
|
476
537
|
const failedFirst = first;
|
|
477
538
|
const failedSecond = second;
|
|
478
539
|
const failedThird = third;
|
|
479
540
|
first = 0;
|
|
480
541
|
second = 0;
|
|
481
542
|
third = 0;
|
|
482
|
-
if (codePoint === void 0) malformed$1("gb18030", `has no character for four-byte sequence 0x${failedFirst.toString(
|
|
543
|
+
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)}`);
|
|
483
544
|
appendCodePoint(sink, codePoint);
|
|
484
545
|
continue;
|
|
485
546
|
}
|
|
486
547
|
if (second !== 0) {
|
|
487
|
-
if (byte >=
|
|
548
|
+
if (byte >= GB18030_LEAD_START && byte <= GB18030_LEAD_END) {
|
|
488
549
|
third = byte;
|
|
489
550
|
continue;
|
|
490
551
|
}
|
|
491
|
-
malformed$1("gb18030", `has no character for byte sequence 0x${first.toString(
|
|
552
|
+
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`);
|
|
492
553
|
}
|
|
493
554
|
if (first !== 0) {
|
|
494
|
-
if (byte >=
|
|
555
|
+
if (byte >= GB18030_DIGIT_BYTE_MIN && byte <= GB18030_DIGIT_BYTE_MAX) {
|
|
495
556
|
second = byte;
|
|
496
557
|
continue;
|
|
497
558
|
}
|
|
498
559
|
const leadingByte = first;
|
|
499
560
|
first = 0;
|
|
500
|
-
const column = twoByteTrailColumn(byte,
|
|
501
|
-
const pointer = column === void 0 ? void 0 : (leadingByte -
|
|
561
|
+
const column = twoByteTrailColumn(byte, GB18030_TRAIL_HIGH_START, GB18030_TRAIL_HIGH_END);
|
|
562
|
+
const pointer = column === void 0 ? void 0 : (leadingByte - GB18030_LEAD_START) * GB18030_TWO_BYTE_COLUMNS + column;
|
|
502
563
|
const codePoint = pointer === void 0 ? void 0 : pointerCodePoint(GB18030, pointer);
|
|
503
|
-
if (codePoint === void 0) malformed$1("gb18030", `has no character for lead byte 0x${leadingByte.toString(
|
|
564
|
+
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)}`);
|
|
504
565
|
appendCodePoint(sink, codePoint);
|
|
505
566
|
continue;
|
|
506
567
|
}
|
|
507
568
|
if (byte <= ASCII_BYTE_MAX) sink.units.push(byte);
|
|
508
|
-
else if (byte ===
|
|
509
|
-
else if (byte <=
|
|
510
|
-
else malformed$1("gb18030", `has no character for byte 0x${byte.toString(
|
|
569
|
+
else if (byte === GB18030_SINGLE_BYTE_EURO) sink.units.push(EURO_SIGN_CODE_POINT);
|
|
570
|
+
else if (byte <= GB18030_LEAD_END) first = byte;
|
|
571
|
+
else malformed$1("gb18030", `has no character for byte 0x${byte.toString(HEX_RADIX$2)}`);
|
|
511
572
|
}
|
|
512
573
|
if (first !== 0) truncated$1("gb18030");
|
|
513
574
|
return fromCodeUnits(sink.units);
|
|
@@ -529,11 +590,25 @@ const KATAKANA_LAST_BYTE = 95;
|
|
|
529
590
|
const JIS0208_INDEX_BYTE_MIN = 33;
|
|
530
591
|
const JIS0208_INDEX_BYTE_MAX = 126;
|
|
531
592
|
const JIS0208_INDEX_COLUMNS = 94;
|
|
593
|
+
const HEX_RADIX$1 = 16;
|
|
594
|
+
const PLAIN_BYTE_MAX = 127;
|
|
595
|
+
const SHIFT_OUT = 14;
|
|
596
|
+
const SHIFT_IN = 15;
|
|
597
|
+
const ROMAN_YEN_BYTE = 92;
|
|
598
|
+
const ROMAN_YEN_CODEPOINT = 165;
|
|
599
|
+
const ROMAN_OVERLINE_BYTE = 126;
|
|
600
|
+
const ROMAN_OVERLINE_CODEPOINT = 8254;
|
|
601
|
+
const ESCAPE_DESIGNATOR_DOLLAR = 36;
|
|
602
|
+
const ESCAPE_DESIGNATOR_PAREN = 40;
|
|
603
|
+
const ESCAPE_DESIGNATOR_AT = 64;
|
|
604
|
+
const ESCAPE_DESIGNATOR_B = 66;
|
|
605
|
+
const ESCAPE_DESIGNATOR_I = 73;
|
|
606
|
+
const ESCAPE_DESIGNATOR_J = 74;
|
|
532
607
|
/**
|
|
533
608
|
* 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.
|
|
534
609
|
*/
|
|
535
610
|
function isPlainByte(byte) {
|
|
536
|
-
return byte <=
|
|
611
|
+
return byte <= PLAIN_BYTE_MAX && byte !== SHIFT_OUT && byte !== SHIFT_IN;
|
|
537
612
|
}
|
|
538
613
|
/**
|
|
539
614
|
* Decodes bytes as ISO-2022-JP (https://encoding.spec.whatwg.org/#iso-2022-jp-decoder).
|
|
@@ -557,7 +632,7 @@ function decodeIso2022Jp(bytes) {
|
|
|
557
632
|
continue;
|
|
558
633
|
}
|
|
559
634
|
output = false;
|
|
560
|
-
if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(
|
|
635
|
+
if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in ASCII mode`);
|
|
561
636
|
units.push(byte);
|
|
562
637
|
continue;
|
|
563
638
|
case "roman":
|
|
@@ -566,15 +641,15 @@ function decodeIso2022Jp(bytes) {
|
|
|
566
641
|
continue;
|
|
567
642
|
}
|
|
568
643
|
output = false;
|
|
569
|
-
if (byte ===
|
|
570
|
-
units.push(
|
|
644
|
+
if (byte === ROMAN_YEN_BYTE) {
|
|
645
|
+
units.push(ROMAN_YEN_CODEPOINT);
|
|
571
646
|
continue;
|
|
572
647
|
}
|
|
573
|
-
if (byte ===
|
|
574
|
-
units.push(
|
|
648
|
+
if (byte === ROMAN_OVERLINE_BYTE) {
|
|
649
|
+
units.push(ROMAN_OVERLINE_CODEPOINT);
|
|
575
650
|
continue;
|
|
576
651
|
}
|
|
577
|
-
if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(
|
|
652
|
+
if (!isPlainByte(byte)) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in Roman mode`);
|
|
578
653
|
units.push(byte);
|
|
579
654
|
continue;
|
|
580
655
|
case "katakana":
|
|
@@ -583,7 +658,7 @@ function decodeIso2022Jp(bytes) {
|
|
|
583
658
|
continue;
|
|
584
659
|
}
|
|
585
660
|
output = false;
|
|
586
|
-
if (byte < KATAKANA_FIRST_BYTE || byte > KATAKANA_LAST_BYTE) malformed(`has no character for byte 0x${byte.toString(
|
|
661
|
+
if (byte < KATAKANA_FIRST_BYTE || byte > KATAKANA_LAST_BYTE) malformed(`has no character for byte 0x${byte.toString(HEX_RADIX$1)} in Katakana mode`);
|
|
587
662
|
units.push(65344 + byte);
|
|
588
663
|
continue;
|
|
589
664
|
case "leadingByte":
|
|
@@ -592,34 +667,34 @@ function decodeIso2022Jp(bytes) {
|
|
|
592
667
|
continue;
|
|
593
668
|
}
|
|
594
669
|
output = false;
|
|
595
|
-
if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for byte 0x${byte.toString(
|
|
670
|
+
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`);
|
|
596
671
|
pending = byte;
|
|
597
672
|
state = "trailingByte";
|
|
598
673
|
continue;
|
|
599
674
|
case "trailingByte": {
|
|
600
675
|
const leadingByte = pending;
|
|
601
676
|
state = "leadingByte";
|
|
602
|
-
if (byte === ESCAPE) malformed(`has an incomplete JIS X 0208 two-byte sequence: lead byte 0x${leadingByte.toString(
|
|
603
|
-
if (byte < JIS0208_INDEX_BYTE_MIN || byte > JIS0208_INDEX_BYTE_MAX) malformed(`has no character for lead byte 0x${leadingByte.toString(
|
|
677
|
+
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`);
|
|
678
|
+
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)}`);
|
|
604
679
|
const pointer = (leadingByte - JIS0208_INDEX_BYTE_MIN) * JIS0208_INDEX_COLUMNS + byte - JIS0208_INDEX_BYTE_MIN;
|
|
605
680
|
const codePoint = pointerCodePoint(JIS0208, pointer);
|
|
606
|
-
if (codePoint === void 0) malformed(`has no character for lead byte 0x${leadingByte.toString(
|
|
681
|
+
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)}`);
|
|
607
682
|
units.push(codePoint);
|
|
608
683
|
continue;
|
|
609
684
|
}
|
|
610
685
|
case "escapeStart":
|
|
611
|
-
if (byte ===
|
|
686
|
+
if (byte === ESCAPE_DESIGNATOR_DOLLAR || byte === ESCAPE_DESIGNATOR_PAREN) {
|
|
612
687
|
pending = byte;
|
|
613
688
|
state = "escape";
|
|
614
689
|
continue;
|
|
615
690
|
}
|
|
616
|
-
malformed(`has no supported designator starting with escape byte 0x${byte.toString(
|
|
691
|
+
malformed(`has no supported designator starting with escape byte 0x${byte.toString(HEX_RADIX$1)}`);
|
|
617
692
|
continue;
|
|
618
693
|
case "escape": {
|
|
619
694
|
const leadingEscapeByte = pending;
|
|
620
695
|
pending = 0;
|
|
621
|
-
const nextState = leadingEscapeByte ===
|
|
622
|
-
if (nextState === void 0) malformed(`has an unsupported designator escape sequence 0x1b 0x${leadingEscapeByte.toString(
|
|
696
|
+
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;
|
|
697
|
+
if (nextState === void 0) malformed(`has an unsupported designator escape sequence 0x1b 0x${leadingEscapeByte.toString(HEX_RADIX$1)} 0x${byte.toString(HEX_RADIX$1)}`);
|
|
623
698
|
state = nextState;
|
|
624
699
|
if (output) malformed("has a redundant designator escape sequence with no characters decoded since the previous one");
|
|
625
700
|
output = true;
|
|
@@ -711,11 +786,6 @@ const SUPPLEMENTARY_PLANE_START = 65536;
|
|
|
711
786
|
/** 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. */
|
|
712
787
|
const SURROGATE_BITS = 10;
|
|
713
788
|
const LOW_SURROGATE_MASK = 1023;
|
|
714
|
-
/**
|
|
715
|
-
* 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.
|
|
716
|
-
*
|
|
717
|
-
* Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
|
|
718
|
-
*/
|
|
719
789
|
const TEXT_DECODE_CHUNK_CODE_UNITS = 32768;
|
|
720
790
|
/**
|
|
721
791
|
* 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.
|
|
@@ -742,6 +812,8 @@ function fromCodeUnits(units) {
|
|
|
742
812
|
return String.fromCharCode.apply(null, units.slice(start, start + TEXT_DECODE_CHUNK_CODE_UNITS));
|
|
743
813
|
}).join("");
|
|
744
814
|
}
|
|
815
|
+
const BOM_FE = 254;
|
|
816
|
+
const BOM_FF = 255;
|
|
745
817
|
/** 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. */
|
|
746
818
|
const BOM_SIGNATURES = [
|
|
747
819
|
{
|
|
@@ -749,15 +821,15 @@ const BOM_SIGNATURES = [
|
|
|
749
821
|
bytes: [
|
|
750
822
|
0,
|
|
751
823
|
0,
|
|
752
|
-
|
|
753
|
-
|
|
824
|
+
BOM_FE,
|
|
825
|
+
BOM_FF
|
|
754
826
|
]
|
|
755
827
|
},
|
|
756
828
|
{
|
|
757
829
|
encoding: "utf-32le",
|
|
758
830
|
bytes: [
|
|
759
|
-
|
|
760
|
-
|
|
831
|
+
BOM_FF,
|
|
832
|
+
BOM_FE,
|
|
761
833
|
0,
|
|
762
834
|
0
|
|
763
835
|
]
|
|
@@ -772,11 +844,11 @@ const BOM_SIGNATURES = [
|
|
|
772
844
|
},
|
|
773
845
|
{
|
|
774
846
|
encoding: "utf-16be",
|
|
775
|
-
bytes: [
|
|
847
|
+
bytes: [BOM_FE, BOM_FF]
|
|
776
848
|
},
|
|
777
849
|
{
|
|
778
850
|
encoding: "utf-16le",
|
|
779
|
-
bytes: [
|
|
851
|
+
bytes: [BOM_FF, BOM_FE]
|
|
780
852
|
}
|
|
781
853
|
];
|
|
782
854
|
function findBom(bytes) {
|
|
@@ -831,11 +903,12 @@ function tryDecodeUtf16(bytes, littleEndian) {
|
|
|
831
903
|
return;
|
|
832
904
|
}
|
|
833
905
|
}
|
|
906
|
+
const BYTES_PER_UTF32_CODE_UNIT = 4;
|
|
834
907
|
function decodeUtf32(bytes, littleEndian) {
|
|
835
|
-
if (bytes.byteLength %
|
|
908
|
+
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");
|
|
836
909
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
837
910
|
const sink = { units: [] };
|
|
838
|
-
for (let offset = 0; offset < bytes.byteLength; offset +=
|
|
911
|
+
for (let offset = 0; offset < bytes.byteLength; offset += BYTES_PER_UTF32_CODE_UNIT) {
|
|
839
912
|
const codePoint = view.getUint32(offset, littleEndian);
|
|
840
913
|
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");
|
|
841
914
|
appendCodePoint(sink, codePoint);
|
|
@@ -854,6 +927,7 @@ function decodeUtf8(bytes) {
|
|
|
854
927
|
}
|
|
855
928
|
/** 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. */
|
|
856
929
|
const LEGACY_SINGLE_BYTE_GAP_CODE = 65533;
|
|
930
|
+
const HEX_RADIX = 16;
|
|
857
931
|
/** 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. */
|
|
858
932
|
function decodeLegacySingleByte(bytes, table, label) {
|
|
859
933
|
const units = [];
|
|
@@ -863,7 +937,7 @@ function decodeLegacySingleByte(bytes, table, label) {
|
|
|
863
937
|
continue;
|
|
864
938
|
}
|
|
865
939
|
const unit = table.charCodeAt(byte - FIRST_HIGH_BYTE);
|
|
866
|
-
if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(
|
|
940
|
+
if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(HEX_RADIX)}`);
|
|
867
941
|
units.push(unit);
|
|
868
942
|
}
|
|
869
943
|
return fromCodeUnits(units);
|
|
@@ -1265,6 +1339,13 @@ function resolveEncodingLabel(label) {
|
|
|
1265
1339
|
}
|
|
1266
1340
|
//#endregion
|
|
1267
1341
|
//#region src/image/png-filter.ts
|
|
1342
|
+
const PNG_FILTER_NONE = 0;
|
|
1343
|
+
const PNG_FILTER_SUB = 1;
|
|
1344
|
+
const PNG_FILTER_UP = 2;
|
|
1345
|
+
const PNG_FILTER_AVERAGE = 3;
|
|
1346
|
+
const PNG_FILTER_PAETH = 4;
|
|
1347
|
+
const BYTE_MASK = 255;
|
|
1348
|
+
const BYTE_MODULUS = 256;
|
|
1268
1349
|
function paethPredictor(a, b, c) {
|
|
1269
1350
|
const p = a + b - c;
|
|
1270
1351
|
const pa = Math.abs(p - a);
|
|
@@ -1276,13 +1357,13 @@ function paethPredictor(a, b, c) {
|
|
|
1276
1357
|
return c;
|
|
1277
1358
|
}
|
|
1278
1359
|
function isPngFilterType(value) {
|
|
1279
|
-
return value ===
|
|
1360
|
+
return value === PNG_FILTER_NONE || value === PNG_FILTER_SUB || value === PNG_FILTER_UP || value === PNG_FILTER_AVERAGE || value === PNG_FILTER_PAETH;
|
|
1280
1361
|
}
|
|
1281
1362
|
function predictorValue(filterType, a, b, c) {
|
|
1282
|
-
if (filterType ===
|
|
1283
|
-
if (filterType ===
|
|
1284
|
-
if (filterType ===
|
|
1285
|
-
if (filterType ===
|
|
1363
|
+
if (filterType === PNG_FILTER_SUB) return a;
|
|
1364
|
+
if (filterType === PNG_FILTER_UP) return b;
|
|
1365
|
+
if (filterType === PNG_FILTER_AVERAGE) return Math.floor((a + b) / 2);
|
|
1366
|
+
if (filterType === PNG_FILTER_PAETH) return paethPredictor(a, b, c);
|
|
1286
1367
|
return 0;
|
|
1287
1368
|
}
|
|
1288
1369
|
function unfilterScanlines(data, height, bytesPerRow, bpp) {
|
|
@@ -1300,7 +1381,7 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
|
|
|
1300
1381
|
const a = x >= bpp ? out[outRowStart + x - bpp] : 0;
|
|
1301
1382
|
const b = prevOutRowStart === void 0 ? 0 : out[prevOutRowStart + x];
|
|
1302
1383
|
const c = x >= bpp && prevOutRowStart !== void 0 ? out[prevOutRowStart + x - bpp] : 0;
|
|
1303
|
-
out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) &
|
|
1384
|
+
out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK;
|
|
1304
1385
|
});
|
|
1305
1386
|
}
|
|
1306
1387
|
return out;
|
|
@@ -1308,48 +1389,48 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
|
|
|
1308
1389
|
function filterRowInto(current, previous, bpp, filterType, target) {
|
|
1309
1390
|
let sum = 0;
|
|
1310
1391
|
switch (filterType) {
|
|
1311
|
-
case
|
|
1392
|
+
case PNG_FILTER_SUB:
|
|
1312
1393
|
target.forEach((_byte, x) => {
|
|
1313
|
-
const filtered = current[x + bpp] - current[x] &
|
|
1394
|
+
const filtered = current[x + bpp] - current[x] & BYTE_MASK;
|
|
1314
1395
|
target[x] = filtered;
|
|
1315
|
-
sum += Math.min(filtered,
|
|
1396
|
+
sum += Math.min(filtered, BYTE_MODULUS - filtered);
|
|
1316
1397
|
});
|
|
1317
1398
|
break;
|
|
1318
|
-
case
|
|
1399
|
+
case PNG_FILTER_UP:
|
|
1319
1400
|
target.forEach((_byte, x) => {
|
|
1320
|
-
const filtered = current[x + bpp] - previous[x + bpp] &
|
|
1401
|
+
const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK;
|
|
1321
1402
|
target[x] = filtered;
|
|
1322
|
-
sum += Math.min(filtered,
|
|
1403
|
+
sum += Math.min(filtered, BYTE_MODULUS - filtered);
|
|
1323
1404
|
});
|
|
1324
1405
|
break;
|
|
1325
|
-
case
|
|
1406
|
+
case PNG_FILTER_AVERAGE:
|
|
1326
1407
|
target.forEach((_byte, x) => {
|
|
1327
|
-
const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) &
|
|
1408
|
+
const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK;
|
|
1328
1409
|
target[x] = filtered;
|
|
1329
|
-
sum += Math.min(filtered,
|
|
1410
|
+
sum += Math.min(filtered, BYTE_MODULUS - filtered);
|
|
1330
1411
|
});
|
|
1331
1412
|
break;
|
|
1332
|
-
case
|
|
1413
|
+
case PNG_FILTER_PAETH:
|
|
1333
1414
|
target.forEach((_byte, x) => {
|
|
1334
|
-
const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) &
|
|
1415
|
+
const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK;
|
|
1335
1416
|
target[x] = filtered;
|
|
1336
|
-
sum += Math.min(filtered,
|
|
1417
|
+
sum += Math.min(filtered, BYTE_MODULUS - filtered);
|
|
1337
1418
|
});
|
|
1338
1419
|
break;
|
|
1339
|
-
case
|
|
1420
|
+
case PNG_FILTER_NONE: target.forEach((_byte, x) => {
|
|
1340
1421
|
const filtered = current[x + bpp];
|
|
1341
1422
|
target[x] = filtered;
|
|
1342
|
-
sum += Math.min(filtered,
|
|
1423
|
+
sum += Math.min(filtered, BYTE_MODULUS - filtered);
|
|
1343
1424
|
});
|
|
1344
1425
|
}
|
|
1345
1426
|
return sum;
|
|
1346
1427
|
}
|
|
1347
1428
|
const ALL_FILTER_TYPES = [
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1429
|
+
PNG_FILTER_NONE,
|
|
1430
|
+
PNG_FILTER_SUB,
|
|
1431
|
+
PNG_FILTER_UP,
|
|
1432
|
+
PNG_FILTER_AVERAGE,
|
|
1433
|
+
PNG_FILTER_PAETH
|
|
1353
1434
|
];
|
|
1354
1435
|
function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
|
|
1355
1436
|
const stride = bytesPerRow + 1;
|
|
@@ -1358,10 +1439,10 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
|
|
|
1358
1439
|
let previous = new Uint8Array(bytesPerRow + bpp);
|
|
1359
1440
|
let candidate = new Uint8Array(bytesPerRow);
|
|
1360
1441
|
let best = new Uint8Array(bytesPerRow);
|
|
1361
|
-
const filterTypes = strategy === "none" ? [
|
|
1442
|
+
const filterTypes = strategy === "none" ? [PNG_FILTER_NONE] : ALL_FILTER_TYPES;
|
|
1362
1443
|
Array.from({ length: height }).forEach((_row, y) => {
|
|
1363
1444
|
current.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow), bpp);
|
|
1364
|
-
let bestType =
|
|
1445
|
+
let bestType = PNG_FILTER_NONE;
|
|
1365
1446
|
let bestSum = Number.POSITIVE_INFINITY;
|
|
1366
1447
|
for (const filterType of filterTypes) {
|
|
1367
1448
|
const sum = filterRowInto(current, previous, bpp, filterType, candidate);
|
|
@@ -1379,24 +1460,44 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
|
|
|
1379
1460
|
}
|
|
1380
1461
|
//#endregion
|
|
1381
1462
|
//#region src/image/png-encode.ts
|
|
1463
|
+
const PNG_SIG_HIGH_BIT_MARKER$1 = 137;
|
|
1464
|
+
const PNG_SIG_P$1 = 80;
|
|
1465
|
+
const PNG_SIG_N$1 = 78;
|
|
1466
|
+
const PNG_SIG_G$1 = 71;
|
|
1467
|
+
const PNG_SIG_CR$1 = 13;
|
|
1468
|
+
const PNG_SIG_LF$1 = 10;
|
|
1382
1469
|
const PNG_SIGNATURE$1 = new Uint8Array([
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1470
|
+
PNG_SIG_HIGH_BIT_MARKER$1,
|
|
1471
|
+
PNG_SIG_P$1,
|
|
1472
|
+
PNG_SIG_N$1,
|
|
1473
|
+
PNG_SIG_G$1,
|
|
1474
|
+
PNG_SIG_CR$1,
|
|
1475
|
+
PNG_SIG_LF$1,
|
|
1389
1476
|
26,
|
|
1390
|
-
|
|
1477
|
+
PNG_SIG_LF$1
|
|
1391
1478
|
]);
|
|
1392
1479
|
const MAX_PALETTE_ENTRIES = 256;
|
|
1480
|
+
const BYTES_PER_UINT32 = 4;
|
|
1481
|
+
const IHDR_BYTE_LENGTH = 13;
|
|
1482
|
+
const IHDR_HEIGHT_OFFSET$1 = 4;
|
|
1483
|
+
const PNG_BIT_DEPTH_8 = 8;
|
|
1484
|
+
const PNG_COLOR_TYPE_GRAY = 0;
|
|
1485
|
+
const PNG_COLOR_TYPE_RGB = 2;
|
|
1486
|
+
const PNG_COLOR_TYPE_INDEXED$1 = 3;
|
|
1487
|
+
const PNG_COLOR_TYPE_GRAY_ALPHA$1 = 4;
|
|
1488
|
+
const PNG_COLOR_TYPE_RGBA$1 = 6;
|
|
1489
|
+
const RGB_CHANNELS$1 = 3;
|
|
1490
|
+
const OPAQUE_ALPHA$1 = 255;
|
|
1491
|
+
const GREEN_SHIFT = 8;
|
|
1492
|
+
const BLUE_SHIFT = 16;
|
|
1493
|
+
const ALPHA_SHIFT = 24;
|
|
1393
1494
|
const PNG_MAX_DIMENSION = 2147483647;
|
|
1394
1495
|
const PNG_MAX_PIXELS = 1e8;
|
|
1395
1496
|
function exceedsMaxPixelCount(pixelCount) {
|
|
1396
1497
|
return pixelCount > PNG_MAX_PIXELS;
|
|
1397
1498
|
}
|
|
1398
1499
|
function u32be(value) {
|
|
1399
|
-
const bytes =
|
|
1500
|
+
const bytes = new Uint8Array(BYTES_PER_UINT32);
|
|
1400
1501
|
new DataView(bytes.buffer).setUint32(0, value);
|
|
1401
1502
|
return bytes;
|
|
1402
1503
|
}
|
|
@@ -1408,11 +1509,11 @@ function writeChunk(writer, type, data) {
|
|
|
1408
1509
|
writer.writeBytes(u32be(crc32(concatBytes([typeBytes, data]))));
|
|
1409
1510
|
}
|
|
1410
1511
|
function writeIhdr(writer, width, height, colorType) {
|
|
1411
|
-
const ihdr =
|
|
1512
|
+
const ihdr = new Uint8Array(IHDR_BYTE_LENGTH);
|
|
1412
1513
|
const ihdrView = new DataView(ihdr.buffer);
|
|
1413
1514
|
ihdrView.setUint32(0, width);
|
|
1414
|
-
ihdrView.setUint32(
|
|
1415
|
-
ihdr[8] =
|
|
1515
|
+
ihdrView.setUint32(IHDR_HEIGHT_OFFSET$1, height);
|
|
1516
|
+
ihdr[8] = PNG_BIT_DEPTH_8;
|
|
1416
1517
|
ihdr[9] = colorType;
|
|
1417
1518
|
ihdr[10] = 0;
|
|
1418
1519
|
ihdr[11] = 0;
|
|
@@ -1420,8 +1521,8 @@ function writeIhdr(writer, width, height, colorType) {
|
|
|
1420
1521
|
writeChunk(writer, "IHDR", ihdr);
|
|
1421
1522
|
}
|
|
1422
1523
|
function colorTypeFor(image) {
|
|
1423
|
-
if (image.channels === 1) return image.alpha === void 0 ?
|
|
1424
|
-
return image.alpha === void 0 ?
|
|
1524
|
+
if (image.channels === 1) return image.alpha === void 0 ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA$1;
|
|
1525
|
+
return image.alpha === void 0 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGBA$1;
|
|
1425
1526
|
}
|
|
1426
1527
|
function detectPalette(image) {
|
|
1427
1528
|
const { width, height, data, alpha } = image;
|
|
@@ -1431,12 +1532,12 @@ function detectPalette(image) {
|
|
|
1431
1532
|
const paletteRgb = [];
|
|
1432
1533
|
const paletteAlpha = [];
|
|
1433
1534
|
for (let i = 0; i < pixelCount; i++) {
|
|
1434
|
-
const base = i *
|
|
1535
|
+
const base = i * RGB_CHANNELS$1;
|
|
1435
1536
|
const r = data[base] ?? 0;
|
|
1436
1537
|
const g = data[base + 1] ?? 0;
|
|
1437
1538
|
const b = data[base + 2] ?? 0;
|
|
1438
|
-
const a = alpha === void 0 ?
|
|
1439
|
-
const key = r | g <<
|
|
1539
|
+
const a = alpha === void 0 ? OPAQUE_ALPHA$1 : alpha[i] ?? 0;
|
|
1540
|
+
const key = r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
|
|
1440
1541
|
let index = colorToIndex.get(key);
|
|
1441
1542
|
if (index === void 0) {
|
|
1442
1543
|
if (colorToIndex.size >= MAX_PALETTE_ENTRIES) return;
|
|
@@ -1453,7 +1554,7 @@ function detectPalette(image) {
|
|
|
1453
1554
|
palette
|
|
1454
1555
|
};
|
|
1455
1556
|
let trnsLength = paletteAlpha.length;
|
|
1456
|
-
while (trnsLength > 1 && paletteAlpha[trnsLength - 1] ===
|
|
1557
|
+
while (trnsLength > 1 && paletteAlpha[trnsLength - 1] === OPAQUE_ALPHA$1) trnsLength--;
|
|
1457
1558
|
return {
|
|
1458
1559
|
indices,
|
|
1459
1560
|
palette,
|
|
@@ -1468,7 +1569,7 @@ function buildPng(writeBody) {
|
|
|
1468
1569
|
return writer.toBytes();
|
|
1469
1570
|
}
|
|
1470
1571
|
function writeIndexedPng(writer, width, height, encoding, options) {
|
|
1471
|
-
writeIhdr(writer, width, height,
|
|
1572
|
+
writeIhdr(writer, width, height, PNG_COLOR_TYPE_INDEXED$1);
|
|
1472
1573
|
writeChunk(writer, "PLTE", encoding.palette);
|
|
1473
1574
|
if (encoding.trns !== void 0) writeChunk(writer, "tRNS", encoding.trns);
|
|
1474
1575
|
writeChunk(writer, "IDAT", deflate(filterScanlines(encoding.indices, height, width, 1, options.filter ?? "adaptive")));
|
|
@@ -1491,7 +1592,7 @@ function encodePng(image, options = {}) {
|
|
|
1491
1592
|
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}`);
|
|
1492
1593
|
const pixelCount = image.width * image.height;
|
|
1493
1594
|
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`);
|
|
1494
|
-
const paletteEncoding = image.channels ===
|
|
1595
|
+
const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
|
|
1495
1596
|
if (paletteEncoding === void 0) return buildPng((writer) => {
|
|
1496
1597
|
writeTruecolorPng(writer, image, options);
|
|
1497
1598
|
});
|
|
@@ -1505,16 +1606,38 @@ function encodePng(image, options = {}) {
|
|
|
1505
1606
|
}
|
|
1506
1607
|
//#endregion
|
|
1507
1608
|
//#region src/image/png-decode.ts
|
|
1609
|
+
const PNG_SIG_HIGH_BIT_MARKER = 137;
|
|
1610
|
+
const PNG_SIG_P = 80;
|
|
1611
|
+
const PNG_SIG_N = 78;
|
|
1612
|
+
const PNG_SIG_G = 71;
|
|
1613
|
+
const PNG_SIG_CR = 13;
|
|
1614
|
+
const PNG_SIG_LF = 10;
|
|
1508
1615
|
const PNG_SIGNATURE = [
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1616
|
+
PNG_SIG_HIGH_BIT_MARKER,
|
|
1617
|
+
PNG_SIG_P,
|
|
1618
|
+
PNG_SIG_N,
|
|
1619
|
+
PNG_SIG_G,
|
|
1620
|
+
PNG_SIG_CR,
|
|
1621
|
+
PNG_SIG_LF,
|
|
1515
1622
|
26,
|
|
1516
|
-
|
|
1623
|
+
PNG_SIG_LF
|
|
1517
1624
|
];
|
|
1625
|
+
const CHUNK_LENGTH_FIELD_BYTES = 4;
|
|
1626
|
+
const CHUNK_HEADER_BYTES = 8;
|
|
1627
|
+
const CHUNK_CRC_FIELD_BYTES = 4;
|
|
1628
|
+
const IHDR_HEIGHT_OFFSET = 4;
|
|
1629
|
+
const RGB_CHANNELS = 3;
|
|
1630
|
+
const RGBA_CHANNELS = 4;
|
|
1631
|
+
const ALPHA_CHANNEL_OFFSET = 3;
|
|
1632
|
+
const BITS_PER_BYTE$1 = 8;
|
|
1633
|
+
const BYTE_SHIFT = 3;
|
|
1634
|
+
const BYTE_BIT_MASK = 7;
|
|
1635
|
+
const MAX_SAMPLE_VALUE = 255;
|
|
1636
|
+
const OPAQUE_ALPHA = 255;
|
|
1637
|
+
const PNG_BIT_DEPTH_16 = 16;
|
|
1638
|
+
const PNG_COLOR_TYPE_INDEXED = 3;
|
|
1639
|
+
const PNG_COLOR_TYPE_GRAY_ALPHA = 4;
|
|
1640
|
+
const PNG_COLOR_TYPE_RGBA = 6;
|
|
1518
1641
|
function requireDataView(bytes) {
|
|
1519
1642
|
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1520
1643
|
}
|
|
@@ -1522,13 +1645,13 @@ function readChunks(bytes, onWarning) {
|
|
|
1522
1645
|
const chunks = [];
|
|
1523
1646
|
const view = requireDataView(bytes);
|
|
1524
1647
|
let offset = PNG_SIGNATURE.length;
|
|
1525
|
-
while (offset +
|
|
1648
|
+
while (offset + CHUNK_HEADER_BYTES <= bytes.length) {
|
|
1526
1649
|
const length = view.getUint32(offset);
|
|
1527
|
-
const typeBytes = bytes.subarray(offset +
|
|
1650
|
+
const typeBytes = bytes.subarray(offset + CHUNK_LENGTH_FIELD_BYTES, offset + CHUNK_HEADER_BYTES);
|
|
1528
1651
|
const type = new TextDecoder("latin1").decode(typeBytes);
|
|
1529
|
-
const dataStart = offset +
|
|
1652
|
+
const dataStart = offset + CHUNK_HEADER_BYTES;
|
|
1530
1653
|
const dataEnd = dataStart + length;
|
|
1531
|
-
if (dataEnd +
|
|
1654
|
+
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`);
|
|
1532
1655
|
const data = bytes.subarray(dataStart, dataEnd);
|
|
1533
1656
|
if (onWarning !== void 0) {
|
|
1534
1657
|
if (view.getUint32(dataEnd) !== crc32(concatBytes([typeBytes, data]))) onWarning(`PNG chunk '${type}' failed its CRC32 check`);
|
|
@@ -1537,7 +1660,7 @@ function readChunks(bytes, onWarning) {
|
|
|
1537
1660
|
type,
|
|
1538
1661
|
data
|
|
1539
1662
|
});
|
|
1540
|
-
offset = dataEnd +
|
|
1663
|
+
offset = dataEnd + CHUNK_CRC_FIELD_BYTES;
|
|
1541
1664
|
if (type === "IEND") break;
|
|
1542
1665
|
}
|
|
1543
1666
|
return chunks;
|
|
@@ -1546,7 +1669,7 @@ function parseIhdr(data) {
|
|
|
1546
1669
|
const view = requireDataView(data);
|
|
1547
1670
|
return {
|
|
1548
1671
|
width: view.getUint32(0),
|
|
1549
|
-
height: view.getUint32(
|
|
1672
|
+
height: view.getUint32(IHDR_HEIGHT_OFFSET),
|
|
1550
1673
|
bitDepth: data[8],
|
|
1551
1674
|
colorType: data[9],
|
|
1552
1675
|
interlace: data[12]
|
|
@@ -1554,17 +1677,17 @@ function parseIhdr(data) {
|
|
|
1554
1677
|
}
|
|
1555
1678
|
function channelsForColorType(colorType) {
|
|
1556
1679
|
if (colorType === 0) return 1;
|
|
1557
|
-
if (colorType === 2) return
|
|
1558
|
-
if (colorType ===
|
|
1559
|
-
if (colorType ===
|
|
1560
|
-
if (colorType ===
|
|
1680
|
+
if (colorType === 2) return RGB_CHANNELS;
|
|
1681
|
+
if (colorType === PNG_COLOR_TYPE_INDEXED) return 1;
|
|
1682
|
+
if (colorType === PNG_COLOR_TYPE_GRAY_ALPHA) return 2;
|
|
1683
|
+
if (colorType === PNG_COLOR_TYPE_RGBA) return RGBA_CHANNELS;
|
|
1561
1684
|
throw new Error(`unsupported PNG colour type: ${colorType}`);
|
|
1562
1685
|
}
|
|
1563
1686
|
function filterBpp(bitDepth, channels) {
|
|
1564
|
-
return Math.max(1, Math.ceil(bitDepth * channels /
|
|
1687
|
+
return Math.max(1, Math.ceil(bitDepth * channels / BITS_PER_BYTE$1));
|
|
1565
1688
|
}
|
|
1566
1689
|
function unpackRow(rowBytes, samples, bitDepth) {
|
|
1567
|
-
if (bitDepth ===
|
|
1690
|
+
if (bitDepth === PNG_BIT_DEPTH_16) {
|
|
1568
1691
|
samples.forEach((_sample, i) => {
|
|
1569
1692
|
samples[i] = rowBytes[i * 2];
|
|
1570
1693
|
});
|
|
@@ -1573,8 +1696,8 @@ function unpackRow(rowBytes, samples, bitDepth) {
|
|
|
1573
1696
|
const mask = (1 << bitDepth) - 1;
|
|
1574
1697
|
samples.forEach((_sample, i) => {
|
|
1575
1698
|
const bitOffset = i * bitDepth;
|
|
1576
|
-
const byteIndex = bitOffset >>
|
|
1577
|
-
const shift =
|
|
1699
|
+
const byteIndex = bitOffset >> BYTE_SHIFT;
|
|
1700
|
+
const shift = BITS_PER_BYTE$1 - bitDepth - (bitOffset & BYTE_BIT_MASK);
|
|
1578
1701
|
samples[i] = rowBytes[byteIndex] >> shift & mask;
|
|
1579
1702
|
});
|
|
1580
1703
|
}
|
|
@@ -1586,13 +1709,13 @@ function readTrnsRgbKey(trns) {
|
|
|
1586
1709
|
return [
|
|
1587
1710
|
view.getUint16(0),
|
|
1588
1711
|
view.getUint16(2),
|
|
1589
|
-
view.getUint16(
|
|
1712
|
+
view.getUint16(IHDR_HEIGHT_OFFSET)
|
|
1590
1713
|
];
|
|
1591
1714
|
}
|
|
1592
1715
|
function scaleToByte(sample, bitDepth) {
|
|
1593
|
-
if (bitDepth ===
|
|
1716
|
+
if (bitDepth === PNG_BIT_DEPTH_16) return sample;
|
|
1594
1717
|
const maxSample = (1 << bitDepth) - 1;
|
|
1595
|
-
return Math.round(sample *
|
|
1718
|
+
return Math.round(sample * MAX_SAMPLE_VALUE / maxSample);
|
|
1596
1719
|
}
|
|
1597
1720
|
function decodePng(bytes, options = {}) {
|
|
1598
1721
|
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");
|
|
@@ -1603,22 +1726,22 @@ function decodePng(bytes, options = {}) {
|
|
|
1603
1726
|
if (ihdr.interlace !== 0) throw new Error("Adam7-interlaced PNG images are not supported");
|
|
1604
1727
|
const channels = channelsForColorType(ihdr.colorType);
|
|
1605
1728
|
const bpp = filterBpp(ihdr.bitDepth, channels);
|
|
1606
|
-
const bytesPerRow = Math.ceil(ihdr.width * channels * ihdr.bitDepth /
|
|
1729
|
+
const bytesPerRow = Math.ceil(ihdr.width * channels * ihdr.bitDepth / BITS_PER_BYTE$1);
|
|
1607
1730
|
const idatChunks = chunks.filter((c) => c.type === "IDAT").map((c) => c.data);
|
|
1608
1731
|
if (idatChunks.length === 0) throw new Error("PNG file has no IDAT chunks");
|
|
1609
1732
|
const { bytes: inflated, recovered } = inflateTolerant(concatBytes(idatChunks));
|
|
1610
1733
|
if (recovered && options.onWarning !== void 0) options.onWarning("PNG IDAT stream required tolerant recovery (truncated or malformed)");
|
|
1611
1734
|
const unfiltered = unfilterScanlines(inflated, ihdr.height, bytesPerRow, bpp);
|
|
1612
1735
|
const palette = chunks.find((c) => c.type === "PLTE")?.data;
|
|
1613
|
-
if (ihdr.colorType ===
|
|
1736
|
+
if (ihdr.colorType === PNG_COLOR_TYPE_INDEXED && palette === void 0) throw new Error("indexed-colour PNG has no PLTE chunk");
|
|
1614
1737
|
const trns = chunks.find((c) => c.type === "tRNS")?.data;
|
|
1615
1738
|
return buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns);
|
|
1616
1739
|
}
|
|
1617
1740
|
function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
|
|
1618
1741
|
const { width, height, bitDepth, colorType } = ihdr;
|
|
1619
|
-
const outChannels = colorType === 0 || colorType ===
|
|
1742
|
+
const outChannels = colorType === 0 || colorType === PNG_COLOR_TYPE_GRAY_ALPHA ? 1 : RGB_CHANNELS;
|
|
1620
1743
|
const data = new Uint8Array(width * height * outChannels);
|
|
1621
|
-
const alpha = colorType ===
|
|
1744
|
+
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;
|
|
1622
1745
|
const trnsGray = colorType === 0 && trns !== void 0 ? readTrnsGrayValue(trns) : void 0;
|
|
1623
1746
|
const trnsRgb = colorType === 2 && trns !== void 0 ? readTrnsRgbKey(trns) : void 0;
|
|
1624
1747
|
const samples = new Uint8Array(width * channels);
|
|
@@ -1633,7 +1756,7 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
|
|
|
1633
1756
|
if (colorType === 0) {
|
|
1634
1757
|
const g = samples[pixelBase];
|
|
1635
1758
|
data[outBase] = scaleToByte(g, bitDepth);
|
|
1636
|
-
if (trnsGray !== void 0) alpha[alphaIndex] = g === trnsGray ? 0 :
|
|
1759
|
+
if (trnsGray !== void 0) alpha[alphaIndex] = g === trnsGray ? 0 : OPAQUE_ALPHA;
|
|
1637
1760
|
} else if (colorType === 2) {
|
|
1638
1761
|
const r = samples[pixelBase];
|
|
1639
1762
|
const g = samples[pixelBase + 1];
|
|
@@ -1643,15 +1766,15 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
|
|
|
1643
1766
|
data[outBase + 2] = b;
|
|
1644
1767
|
if (alpha !== void 0 && trnsRgb !== void 0) {
|
|
1645
1768
|
const [kr, kg, kb] = trnsRgb;
|
|
1646
|
-
alpha[alphaIndex] = r === kr && g === kg && b === kb ? 0 :
|
|
1769
|
+
alpha[alphaIndex] = r === kr && g === kg && b === kb ? 0 : OPAQUE_ALPHA;
|
|
1647
1770
|
}
|
|
1648
|
-
} else if (colorType ===
|
|
1771
|
+
} else if (colorType === PNG_COLOR_TYPE_INDEXED) {
|
|
1649
1772
|
const index = samples[pixelBase];
|
|
1650
|
-
data[outBase] = palette[index *
|
|
1651
|
-
data[outBase + 1] = palette[index *
|
|
1652
|
-
data[outBase + 2] = palette[index *
|
|
1653
|
-
if (alpha !== void 0 && trns !== void 0) alpha[alphaIndex] = index < trns.length ? trns[index] :
|
|
1654
|
-
} else if (colorType ===
|
|
1773
|
+
data[outBase] = palette[index * RGB_CHANNELS];
|
|
1774
|
+
data[outBase + 1] = palette[index * RGB_CHANNELS + 1];
|
|
1775
|
+
data[outBase + 2] = palette[index * RGB_CHANNELS + 2];
|
|
1776
|
+
if (alpha !== void 0 && trns !== void 0) alpha[alphaIndex] = index < trns.length ? trns[index] : OPAQUE_ALPHA;
|
|
1777
|
+
} else if (colorType === PNG_COLOR_TYPE_GRAY_ALPHA) {
|
|
1655
1778
|
const g = samples[pixelBase];
|
|
1656
1779
|
const a = samples[pixelBase + 1];
|
|
1657
1780
|
data[outBase] = scaleToByte(g, bitDepth);
|
|
@@ -1660,7 +1783,7 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
|
|
|
1660
1783
|
data[outBase] = samples[pixelBase];
|
|
1661
1784
|
data[outBase + 1] = samples[pixelBase + 1];
|
|
1662
1785
|
data[outBase + 2] = samples[pixelBase + 2];
|
|
1663
|
-
if (alpha !== void 0) alpha[alphaIndex] = samples[pixelBase +
|
|
1786
|
+
if (alpha !== void 0) alpha[alphaIndex] = samples[pixelBase + ALPHA_CHANNEL_OFFSET];
|
|
1664
1787
|
}
|
|
1665
1788
|
});
|
|
1666
1789
|
});
|
|
@@ -1682,18 +1805,23 @@ function buildRawImage(ihdr, channels, bytesPerRow, unfiltered, palette, trns) {
|
|
|
1682
1805
|
const SOI = 216;
|
|
1683
1806
|
const EOI = 217;
|
|
1684
1807
|
const APP14 = 238;
|
|
1808
|
+
const SOF0 = 192;
|
|
1809
|
+
const SOF1 = 193;
|
|
1810
|
+
const SOF2 = 194;
|
|
1811
|
+
const SOF9 = 201;
|
|
1812
|
+
const SOF10 = 202;
|
|
1685
1813
|
const SOF_MARKERS = /* @__PURE__ */ new Set([
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1814
|
+
SOF0,
|
|
1815
|
+
SOF1,
|
|
1816
|
+
SOF2,
|
|
1817
|
+
SOF9,
|
|
1818
|
+
SOF10
|
|
1691
1819
|
]);
|
|
1692
|
-
const PROGRESSIVE_SOF_MARKERS = /* @__PURE__ */ new Set([
|
|
1820
|
+
const PROGRESSIVE_SOF_MARKERS = /* @__PURE__ */ new Set([SOF2, SOF10]);
|
|
1693
1821
|
const NO_PAYLOAD_MARKERS = /* @__PURE__ */ new Set([
|
|
1694
1822
|
1,
|
|
1695
|
-
|
|
1696
|
-
|
|
1823
|
+
SOI,
|
|
1824
|
+
EOI,
|
|
1697
1825
|
208,
|
|
1698
1826
|
209,
|
|
1699
1827
|
210,
|
|
@@ -1703,40 +1831,46 @@ const NO_PAYLOAD_MARKERS = /* @__PURE__ */ new Set([
|
|
|
1703
1831
|
214,
|
|
1704
1832
|
215
|
|
1705
1833
|
]);
|
|
1834
|
+
const BITS_PER_BYTE = 8;
|
|
1835
|
+
const JPEG_MARKER_PREFIX = 255;
|
|
1836
|
+
const APP14_MIN_LENGTH_FOR_TRANSFORM = 14;
|
|
1837
|
+
const APP14_TRANSFORM_OFFSET = 11;
|
|
1838
|
+
const SOF_WIDTH_OFFSET = 3;
|
|
1839
|
+
const SOF_COMPONENTS_OFFSET = 5;
|
|
1706
1840
|
function requireByte(bytes, index) {
|
|
1707
1841
|
const value = bytes[index];
|
|
1708
1842
|
if (value === void 0) throw new Error("unexpected end of JPEG data");
|
|
1709
1843
|
return value;
|
|
1710
1844
|
}
|
|
1711
1845
|
function readUint16BE(bytes, offset) {
|
|
1712
|
-
return requireByte(bytes, offset) <<
|
|
1846
|
+
return requireByte(bytes, offset) << BITS_PER_BYTE | requireByte(bytes, offset + 1);
|
|
1713
1847
|
}
|
|
1714
1848
|
function readJpegInfo(bytes) {
|
|
1715
|
-
if (requireByte(bytes, 0) !==
|
|
1849
|
+
if (requireByte(bytes, 0) !== JPEG_MARKER_PREFIX || requireByte(bytes, 1) !== SOI) throw new Error("not a valid JPEG file: missing SOI marker");
|
|
1716
1850
|
let offset = 2;
|
|
1717
1851
|
let adobeTransform;
|
|
1718
1852
|
while (bytes[offset] !== void 0) {
|
|
1719
|
-
if (bytes[offset] !==
|
|
1853
|
+
if (bytes[offset] !== JPEG_MARKER_PREFIX) {
|
|
1720
1854
|
offset++;
|
|
1721
1855
|
continue;
|
|
1722
1856
|
}
|
|
1723
1857
|
let markerOffset = offset + 1;
|
|
1724
|
-
while (bytes[markerOffset] ===
|
|
1858
|
+
while (bytes[markerOffset] === JPEG_MARKER_PREFIX) markerOffset++;
|
|
1725
1859
|
const marker = bytes[markerOffset];
|
|
1726
1860
|
if (marker === void 0) break;
|
|
1727
1861
|
offset = markerOffset + 1;
|
|
1728
1862
|
if (marker === EOI) break;
|
|
1729
1863
|
if (NO_PAYLOAD_MARKERS.has(marker)) continue;
|
|
1730
1864
|
const segmentLength = readUint16BE(bytes, offset);
|
|
1731
|
-
if (marker === APP14 && segmentLength >=
|
|
1865
|
+
if (marker === APP14 && segmentLength >= APP14_MIN_LENGTH_FOR_TRANSFORM) adobeTransform = requireByte(bytes, offset + 2 + APP14_TRANSFORM_OFFSET);
|
|
1732
1866
|
if (SOF_MARKERS.has(marker)) {
|
|
1733
1867
|
const p = offset + 2;
|
|
1734
1868
|
const precision = requireByte(bytes, p);
|
|
1735
1869
|
const height = readUint16BE(bytes, p + 1);
|
|
1736
1870
|
return {
|
|
1737
|
-
width: readUint16BE(bytes, p +
|
|
1871
|
+
width: readUint16BE(bytes, p + SOF_WIDTH_OFFSET),
|
|
1738
1872
|
height,
|
|
1739
|
-
components: requireByte(bytes, p +
|
|
1873
|
+
components: requireByte(bytes, p + SOF_COMPONENTS_OFFSET),
|
|
1740
1874
|
precision,
|
|
1741
1875
|
progressive: PROGRESSIVE_SOF_MARKERS.has(marker),
|
|
1742
1876
|
adobeTransform
|