document-bytes 1.6.3 → 1.8.0

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.cjs CHANGED
@@ -224,6 +224,620 @@ function inflateTolerant(data) {
224
224
  };
225
225
  }
226
226
  //#endregion
227
+ //#region src/text/legacy-single-byte-tables.ts
228
+ /** Byte 0x80-0xFF lookup tables for {@link LegacySingleByteEncodingLabel}, one 128-character string per encoding, indexed by `byte - 0x80`. See the top of this file for what generated them and what a U+FFFD entry means. */
229
+ const LEGACY_SINGLE_BYTE_TABLES = {
230
+ ibm866: "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■\xA0",
231
+ "iso-8859-2": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙",
232
+ "iso-8859-3": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙",
233
+ "iso-8859-4": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙",
234
+ "iso-8859-5": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ",
235
+ "iso-8859-6": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������",
236
+ "iso-8859-7": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�",
237
+ "iso-8859-8": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0�¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
238
+ "iso-8859-8-i": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0�¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
239
+ "iso-8859-10": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ",
240
+ "iso-8859-13": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’",
241
+ "iso-8859-14": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ",
242
+ "iso-8859-15": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
243
+ "iso-8859-16": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ",
244
+ "koi8-r": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥\xA0⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ",
245
+ "koi8-u": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥\xA0⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ",
246
+ macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»…\xA0ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ",
247
+ "windows-874": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����",
248
+ "windows-1250": "€‚ƒ„…†‡ˆ‰Š‹ŚŤŽŹ‘’“”•–—˜™š›śťžź\xA0ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙",
249
+ "windows-1251": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—˜™љ›њќћџ\xA0ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя",
250
+ "windows-1253": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�",
251
+ "windows-1254": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ",
252
+ "windows-1255": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
253
+ "windows-1256": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں\xA0،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے",
254
+ "windows-1257": "€‚ƒ„…†‡ˆ‰Š‹Œ¨ˇ¸‘’“”•–—˜™š›œ¯˛Ÿ\xA0�¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙",
255
+ "windows-1258": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ",
256
+ "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»…\xA0ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю€"
257
+ };
258
+ //#endregion
259
+ //#region src/text/decode.ts
260
+ /** Thrown when bytes cannot be turned into text: they are not text at all, they contradict a declared or marked encoding, or they match none of the supported encodings. */
261
+ var UndecodableTextError = class extends Error {
262
+ /** Which of the three failures this was, for a caller that treats them differently. */
263
+ reason;
264
+ constructor(reason, message) {
265
+ super(message);
266
+ this.name = "UndecodableTextError";
267
+ this.reason = reason;
268
+ }
269
+ };
270
+ /** NUL, as a byte and as a code unit alike: it belongs to no text under either reading. */
271
+ const NUL_CODE = 0;
272
+ /** The first character code that is not a C0 control. */
273
+ const FIRST_NON_CONTROL_CODE = 32;
274
+ /** The first byte outside ASCII, which is also where every encoding in the supported set stops agreeing with every other. */
275
+ const FIRST_HIGH_BYTE = 128;
276
+ /** The C1 control range, which is both where windows-1252 differs from ISO-8859-1 and the range whose presence in a decoded result says the guess was wrong. Its start doubles as the first byte the windows-1252 table below covers. */
277
+ const C1_CONTROL_START = 128;
278
+ const C1_CONTROL_END = 159;
279
+ /** C0 controls that appear in real text: tab, line feed, form feed, carriage return. Every other code below {@link FIRST_NON_CONTROL_CODE} belongs to binary content. */
280
+ const TEXTUAL_CONTROL_CODES = /* @__PURE__ */ new Set([
281
+ 9,
282
+ 10,
283
+ 12,
284
+ 13
285
+ ]);
286
+ /** One C0 control outside {@link TEXTUAL_CONTROL_CODES} is permitted per this many characters before the content is taken for binary. Plain text carries none at all, so the allowance exists only to tolerate a stray one, an end-of-file Ctrl-Z left by a DOS-era editor being the case that actually occurs; compressed and image data puts roughly an eighth of its bytes in the C0 range, more than an order of magnitude above this. Counted as integer arithmetic against the length rather than a floating-point ratio so the boundary is exact. */
287
+ const CODES_PER_PERMITTED_CONTROL = 64;
288
+ /** The longest run of consecutive bytes at or above {@link FIRST_HIGH_BYTE} the windows-1252 guess accepts. Latin-script text sets an accented letter inside otherwise-ASCII words, so even the most accent-dense Western orthography never strings many together; text in a non-Latin single-byte code page, and bytes that are not text at all, put whole words above that boundary and run far longer. A caller holding bytes that genuinely do (a line of nothing but bullets, say) names the encoding explicitly rather than relying on the guess. */
289
+ const MAX_HIGH_BYTE_RUN = 4;
290
+ /** windows-1252's own mapping for the bytes from {@link C1_CONTROL_START} to {@link C1_CONTROL_END}, the one range where it differs from ISO-8859-1: bytes below are ASCII and bytes above are ISO-8859-1 exactly, so neither needs a table. Held as a string rather than an array so a lookup is a `charCodeAt` on a fixed-length string, with no index the type system has to be told is in range. Five positions (0x81, 0x8D, 0x8F, 0x90, 0x9D) have no character in Microsoft's own code page; the Encoding Standard maps them to the matching C1 control characters so that its decoder is total, and this table does the same, so decoding here and decoding through a TextDecoder that does support the label agree byte for byte. */
291
+ const WINDOWS_1252_HIGH_RANGE = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
292
+ /** The bytes windows-1252 leaves without a character of their own, derived from {@link WINDOWS_1252_HIGH_RANGE} as exactly those positions whose mapping lands back in the C1 control range instead of on a real character. A C1 control appears in no text document, so one of these bytes says the content is not windows-1252 text whatever else it may be. */
293
+ const WINDOWS_1252_UNDEFINED_BYTES = new Set(Array.from(WINDOWS_1252_HIGH_RANGE).flatMap((character, index) => {
294
+ const codePoint = character.charCodeAt(0);
295
+ return codePoint >= C1_CONTROL_START && codePoint <= C1_CONTROL_END ? [C1_CONTROL_START + index] : [];
296
+ }));
297
+ /** UTF-16's surrogate range, whose halves pair up to carry a code point above the basic plane and which is never a code point in its own right. */
298
+ const HIGH_SURROGATE_START = 55296;
299
+ const HIGH_SURROGATE_END = 56319;
300
+ const LOW_SURROGATE_START = 56320;
301
+ const LOW_SURROGATE_END = 57343;
302
+ /** The highest code point Unicode defines, and the first one that needs a surrogate pair to reach in UTF-16. */
303
+ const MAX_CODE_POINT = 1114111;
304
+ const SUPPLEMENTARY_PLANE_START = 65536;
305
+ /** 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. */
306
+ const SURROGATE_BITS = 10;
307
+ const LOW_SURROGATE_MASK = 1023;
308
+ /**
309
+ * 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.
310
+ *
311
+ * Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
312
+ */
313
+ const TEXT_DECODE_CHUNK_CODE_UNITS = 32768;
314
+ function fromCodeUnits(units) {
315
+ return Array.from({ length: Math.ceil(units.length / TEXT_DECODE_CHUNK_CODE_UNITS) }, (_unused, chunk) => {
316
+ const start = chunk * TEXT_DECODE_CHUNK_CODE_UNITS;
317
+ return String.fromCharCode.apply(null, units.slice(start, start + TEXT_DECODE_CHUNK_CODE_UNITS));
318
+ }).join("");
319
+ }
320
+ /** 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. */
321
+ const BOM_SIGNATURES = [
322
+ {
323
+ encoding: "utf-32be",
324
+ bytes: [
325
+ 0,
326
+ 0,
327
+ 254,
328
+ 255
329
+ ]
330
+ },
331
+ {
332
+ encoding: "utf-32le",
333
+ bytes: [
334
+ 255,
335
+ 254,
336
+ 0,
337
+ 0
338
+ ]
339
+ },
340
+ {
341
+ encoding: "utf-8",
342
+ bytes: [
343
+ 239,
344
+ 187,
345
+ 191
346
+ ]
347
+ },
348
+ {
349
+ encoding: "utf-16be",
350
+ bytes: [254, 255]
351
+ },
352
+ {
353
+ encoding: "utf-16le",
354
+ bytes: [255, 254]
355
+ }
356
+ ];
357
+ function findBom(bytes) {
358
+ return BOM_SIGNATURES.find((signature) => signature.bytes.every((value, index) => bytes[index] === value));
359
+ }
360
+ /**
361
+ * Detects a byte order mark at the start of `bytes`, without decoding anything past it.
362
+ *
363
+ * {@link decodeText} already checks for a mark as part of its own detection order; this exists for a caller that has to settle the encoding before it can safely read anything else, an XML document's own encoding declaration being the case that occurs: the declaration lives inside the document, in whichever encoding the document turns out to be, so a mark has to be ruled out (or read) before that declaration can even be located.
364
+ * @param bytes - The bytes to check.
365
+ * @returns The mark's encoding and length, or `undefined` when the bytes carry none of the five marks {@link decodeText} itself recognises.
366
+ */
367
+ function detectByteOrderMark(bytes) {
368
+ const bom = findBom(bytes);
369
+ return bom === void 0 ? void 0 : {
370
+ encoding: bom.encoding,
371
+ length: bom.bytes.length
372
+ };
373
+ }
374
+ /** The bytes past a byte order mark for `encoding`, or the bytes unchanged when they carry no such mark. A mark for a different encoding is left alone: under a declared encoding it is content, not a mark. */
375
+ function stripBom(bytes, encoding) {
376
+ const bom = findBom(bytes);
377
+ return bom?.encoding === encoding ? bytes.subarray(bom.bytes.length) : bytes;
378
+ }
379
+ function tryDecodeUtf8(bytes) {
380
+ try {
381
+ return new TextDecoder("utf-8", {
382
+ fatal: true,
383
+ ignoreBOM: true
384
+ }).decode(bytes);
385
+ } catch {
386
+ return;
387
+ }
388
+ }
389
+ function decodeUtf16(bytes, littleEndian) {
390
+ if (bytes.byteLength % 2 !== 0) throw new UndecodableTextError("malformed", "UTF-16 text must hold a whole number of 16-bit code units");
391
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
392
+ const units = [];
393
+ for (let offset = 0; offset < bytes.byteLength; offset += 2) units.push(view.getUint16(offset, littleEndian));
394
+ let awaitingLowSurrogate = false;
395
+ for (const unit of units) {
396
+ if (awaitingLowSurrogate !== (unit >= LOW_SURROGATE_START && unit <= LOW_SURROGATE_END)) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
397
+ awaitingLowSurrogate = unit >= HIGH_SURROGATE_START && unit <= HIGH_SURROGATE_END;
398
+ }
399
+ if (awaitingLowSurrogate) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
400
+ return fromCodeUnits(units);
401
+ }
402
+ function tryDecodeUtf16(bytes, littleEndian) {
403
+ try {
404
+ return decodeUtf16(bytes, littleEndian);
405
+ } catch {
406
+ return;
407
+ }
408
+ }
409
+ function decodeUtf32(bytes, littleEndian) {
410
+ if (bytes.byteLength % 4 !== 0) throw new UndecodableTextError("malformed", "UTF-32 text must hold a whole number of 32-bit code units");
411
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
412
+ const units = [];
413
+ for (let offset = 0; offset < bytes.byteLength; offset += 4) {
414
+ const codePoint = view.getUint32(offset, littleEndian);
415
+ 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");
416
+ if (codePoint < SUPPLEMENTARY_PLANE_START) {
417
+ units.push(codePoint);
418
+ continue;
419
+ }
420
+ const supplementary = codePoint - SUPPLEMENTARY_PLANE_START;
421
+ units.push(HIGH_SURROGATE_START + (supplementary >> SURROGATE_BITS));
422
+ units.push(LOW_SURROGATE_START + (supplementary & LOW_SURROGATE_MASK));
423
+ }
424
+ return fromCodeUnits(units);
425
+ }
426
+ function decodeWindows1252(bytes) {
427
+ const units = [];
428
+ for (const byte of bytes) units.push(byte < C1_CONTROL_START || byte > C1_CONTROL_END ? byte : WINDOWS_1252_HIGH_RANGE.charCodeAt(byte - C1_CONTROL_START));
429
+ return fromCodeUnits(units);
430
+ }
431
+ function decodeUtf8(bytes) {
432
+ const text = tryDecodeUtf8(bytes);
433
+ if (text === void 0) throw new UndecodableTextError("malformed", "UTF-8 text must hold only well-formed byte sequences");
434
+ return text;
435
+ }
436
+ /** 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. */
437
+ const LEGACY_SINGLE_BYTE_GAP_CODE = 65533;
438
+ /** 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. */
439
+ function decodeLegacySingleByte(bytes, table, label) {
440
+ const units = [];
441
+ for (const byte of bytes) {
442
+ if (byte < FIRST_HIGH_BYTE) {
443
+ units.push(byte);
444
+ continue;
445
+ }
446
+ const unit = table.charCodeAt(byte - FIRST_HIGH_BYTE);
447
+ if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(16)}`);
448
+ units.push(unit);
449
+ }
450
+ return fromCodeUnits(units);
451
+ }
452
+ /** One {@link decodeLegacySingleByte} decoder per {@link LegacySingleByteEncodingLabel}, built from {@link LEGACY_SINGLE_BYTE_TABLES} rather than listed by hand so that every table entry gets exactly one decoder and neither list can drift from the other. */
453
+ function legacySingleByteDecoder(label) {
454
+ const table = LEGACY_SINGLE_BYTE_TABLES[label];
455
+ return (bytes) => decodeLegacySingleByte(bytes, table, label);
456
+ }
457
+ /** One decoder per supported encoding, as a record keyed by the encoding union itself so that adding an encoding to {@link TextEncodingLabel} without a decoder for it is a compile error rather than a run-time gap. */
458
+ const DECODERS = {
459
+ "utf-8": decodeUtf8,
460
+ "utf-16le": (bytes) => decodeUtf16(bytes, true),
461
+ "utf-16be": (bytes) => decodeUtf16(bytes, false),
462
+ "utf-32le": (bytes) => decodeUtf32(bytes, true),
463
+ "utf-32be": (bytes) => decodeUtf32(bytes, false),
464
+ "windows-1252": decodeWindows1252,
465
+ ibm866: legacySingleByteDecoder("ibm866"),
466
+ "iso-8859-2": legacySingleByteDecoder("iso-8859-2"),
467
+ "iso-8859-3": legacySingleByteDecoder("iso-8859-3"),
468
+ "iso-8859-4": legacySingleByteDecoder("iso-8859-4"),
469
+ "iso-8859-5": legacySingleByteDecoder("iso-8859-5"),
470
+ "iso-8859-6": legacySingleByteDecoder("iso-8859-6"),
471
+ "iso-8859-7": legacySingleByteDecoder("iso-8859-7"),
472
+ "iso-8859-8": legacySingleByteDecoder("iso-8859-8"),
473
+ "iso-8859-8-i": legacySingleByteDecoder("iso-8859-8-i"),
474
+ "iso-8859-10": legacySingleByteDecoder("iso-8859-10"),
475
+ "iso-8859-13": legacySingleByteDecoder("iso-8859-13"),
476
+ "iso-8859-14": legacySingleByteDecoder("iso-8859-14"),
477
+ "iso-8859-15": legacySingleByteDecoder("iso-8859-15"),
478
+ "iso-8859-16": legacySingleByteDecoder("iso-8859-16"),
479
+ "koi8-r": legacySingleByteDecoder("koi8-r"),
480
+ "koi8-u": legacySingleByteDecoder("koi8-u"),
481
+ macintosh: legacySingleByteDecoder("macintosh"),
482
+ "windows-874": legacySingleByteDecoder("windows-874"),
483
+ "windows-1250": legacySingleByteDecoder("windows-1250"),
484
+ "windows-1251": legacySingleByteDecoder("windows-1251"),
485
+ "windows-1253": legacySingleByteDecoder("windows-1253"),
486
+ "windows-1254": legacySingleByteDecoder("windows-1254"),
487
+ "windows-1255": legacySingleByteDecoder("windows-1255"),
488
+ "windows-1256": legacySingleByteDecoder("windows-1256"),
489
+ "windows-1257": legacySingleByteDecoder("windows-1257"),
490
+ "windows-1258": legacySingleByteDecoder("windows-1258"),
491
+ "x-mac-cyrillic": legacySingleByteDecoder("x-mac-cyrillic")
492
+ };
493
+ /** The text-versus-binary rule itself, over character codes: a NUL settles it outright, and every other C0 control outside {@link TEXTUAL_CONTROL_CODES} is allowed only up to one per {@link CODES_PER_PERMITTED_CONTROL}. Reading codes through an accessor rather than taking an array lets the identical rule run over a Uint8Array's bytes and over a decoded string's code units without copying either into one. */
494
+ function codesAreTextual(codeAt, length) {
495
+ let controlCodes = 0;
496
+ for (let index = 0; index < length; index += 1) {
497
+ const code = codeAt(index);
498
+ if (code === NUL_CODE) return false;
499
+ if (code < FIRST_NON_CONTROL_CODE && !TEXTUAL_CONTROL_CODES.has(code)) controlCodes += 1;
500
+ }
501
+ return controlCodes * CODES_PER_PERMITTED_CONTROL <= length;
502
+ }
503
+ /**
504
+ * Whether bytes can hold text at all, judged without reference to which encoding they might be in.
505
+ *
506
+ * A NUL byte belongs to no text document format, and outside NUL the only C0 control bytes text carries are tab, line feed, form feed and carriage return, so a density of any others says binary. {@link decodeText} asks this before it guesses at windows-1252, which maps nearly every byte to some character and would otherwise read a PNG as a page of mojibake rather than refusing it.
507
+ *
508
+ * UTF-16 is the one text encoding this returns `false` for, since it interleaves NUL bytes by design. {@link decodeText} settles UTF-16 from a byte order mark or that same interleave before it reaches this check, and applies the identical rule to the characters a mark-less UTF-16 guess produced, so that guess cannot smuggle binary past this one.
509
+ * @param bytes - The bytes to judge.
510
+ * @returns Whether the bytes carry no NUL and few enough other C0 control bytes to be text.
511
+ */
512
+ function isProbablyText(bytes) {
513
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
514
+ return codesAreTextual((index) => view.getUint8(index), bytes.byteLength);
515
+ }
516
+ /** {@link isProbablyText}'s own question asked of characters rather than of bytes, for a decode that has already happened. A multi-byte encoding puts NULs and other low bytes into its bytes as part of how it spells ordinary characters, so the bytes cannot answer it; the characters that came out can. */
517
+ function isTextualString(text) {
518
+ return codesAreTextual((index) => text.charCodeAt(index), text.length);
519
+ }
520
+ /** Whether the bytes could be windows-1252 text, as opposed to some other single-byte code page or no text at all. windows-1252 has a character for all but five of its byte values, so trying it and seeing whether it fails proves nothing; these two structural tests are what stands in for that. */
521
+ function looksLikeWindows1252Text(bytes) {
522
+ let highByteRun = 0;
523
+ for (const byte of bytes) {
524
+ if (WINDOWS_1252_UNDEFINED_BYTES.has(byte)) return false;
525
+ if (byte < FIRST_HIGH_BYTE) {
526
+ highByteRun = 0;
527
+ continue;
528
+ }
529
+ highByteRun += 1;
530
+ if (highByteRun > MAX_HIGH_BYTE_RUN) return false;
531
+ }
532
+ return true;
533
+ }
534
+ /**
535
+ * UTF-16 without a byte order mark, recognised from the NUL a code unit below U+0100 puts on one fixed side of every unit pair.
536
+ *
537
+ * The recognised case is UTF-16 holding mostly Latin-script text, which is the only case a NUL interleave makes visible at all: UTF-16 holding CJK text has no NUL high bytes to see and is indistinguishable from other byte sequences without the statistical model this module does not carry.
538
+ *
539
+ * A majority of the units carrying a NUL on one fixed side is the whole of the test, and it is deliberately not also a comparison between the two sides. Bytes that put NULs on both sides, padding rather than text, do satisfy it, and are answered by the decode rather than here: a unit whose two bytes are both NUL decodes to U+0000, which is not text, so the caller's own check on the decoded characters refuses them. Requiring one side to beat the other would be unobservable, since a tie can only arise when some unit carries NULs on both sides, which is exactly the case that cannot survive that check. An odd byte count is left to the decoder for the same reason: it has no whole final code unit, so decoding it fails and the bytes are refused there.
540
+ */
541
+ function detectBomlessUtf16(bytes) {
542
+ let evenIndexNuls = 0;
543
+ let oddIndexNuls = 0;
544
+ let atEvenIndex = true;
545
+ for (const byte of bytes) {
546
+ if (byte === NUL_CODE) {
547
+ if (atEvenIndex) evenIndexNuls += 1;
548
+ else oddIndexNuls += 1;
549
+ }
550
+ atEvenIndex = !atEvenIndex;
551
+ }
552
+ const units = bytes.length / 2;
553
+ if (oddIndexNuls * 2 > units) return "utf-16le";
554
+ if (evenIndexNuls * 2 > units) return "utf-16be";
555
+ }
556
+ const BINARY_MESSAGE = "bytes are not text: they carry a NUL byte, or too many other C0 control bytes for any text encoding";
557
+ function refuseAsBinary() {
558
+ throw new UndecodableTextError("binary", BINARY_MESSAGE);
559
+ }
560
+ function guessWarning(encoding, evidence) {
561
+ return `encoding was guessed as ${encoding}: ${evidence}. Pass an explicit encoding if that is wrong.`;
562
+ }
563
+ /**
564
+ * Decodes bytes to text, working out which character encoding they hold.
565
+ *
566
+ * The encoding is settled in a fixed order: the `encoding` option if the caller gave one, then a byte order mark, then the NUL interleave UTF-16 leaves when it holds Latin-script text and carries no mark, then UTF-8 if the bytes satisfy its own validity rules, then windows-1252 if the bytes read as Western text. Anything a byte order mark or the caller names is decoded under that encoding alone and fails if the bytes contradict it. Everything reached by detection reports how it was reached, so a caller can show the encoding, and a guess additionally carries a warning and a `low` confidence rather than being presented as fact.
567
+ *
568
+ * Bytes that are not text (a NUL byte, or a density of other C0 control bytes) are refused before any guess is made, so detection never widens what counts as text. The readings whose bytes carry NULs legitimately, mark-less UTF-16 and anything behind a UTF-16 or UTF-32 byte order mark, are judged by the same rule applied to the characters they produced instead. Only an explicit `encoding` from the caller skips the judgement entirely, since that is the caller overriding detection outright. A byte order mark is removed from the result rather than left as a leading U+FEFF.
569
+ * @param bytes - The bytes to decode.
570
+ * @param options - An explicit `encoding` to decode under, skipping detection.
571
+ * @throws UndecodableTextError When the bytes are not text, contradict a declared or marked encoding, or match none of the supported encodings.
572
+ * @returns The text, the encoding it was decoded under, and how far that account of the encoding can be relied on.
573
+ */
574
+ function decodeText(bytes, options = {}) {
575
+ const declared = options.encoding;
576
+ if (declared !== void 0) return {
577
+ text: DECODERS[declared](stripBom(bytes, declared)),
578
+ encoding: declared,
579
+ source: "declared",
580
+ confidence: "certain",
581
+ warnings: []
582
+ };
583
+ const bom = findBom(bytes);
584
+ if (bom !== void 0) {
585
+ const text = DECODERS[bom.encoding](bytes.subarray(bom.bytes.length));
586
+ if (!isTextualString(text)) refuseAsBinary();
587
+ return {
588
+ text,
589
+ encoding: bom.encoding,
590
+ source: "bom",
591
+ confidence: "certain",
592
+ warnings: []
593
+ };
594
+ }
595
+ const interleaved = detectBomlessUtf16(bytes);
596
+ if (interleaved !== void 0) {
597
+ const guessed = tryDecodeUtf16(bytes, interleaved === "utf-16le");
598
+ if (guessed !== void 0 && isTextualString(guessed)) return {
599
+ text: guessed,
600
+ encoding: interleaved,
601
+ source: "detected",
602
+ confidence: "low",
603
+ warnings: [guessWarning(interleaved, "the bytes carry no byte order mark, but interleave NUL bytes in the pattern UTF-16 gives Latin-script text")]
604
+ };
605
+ }
606
+ if (!isProbablyText(bytes)) refuseAsBinary();
607
+ const utf8 = tryDecodeUtf8(bytes);
608
+ if (utf8 !== void 0) return {
609
+ text: utf8,
610
+ encoding: "utf-8",
611
+ source: "utf8",
612
+ confidence: utf8.length === bytes.length ? "certain" : "high",
613
+ warnings: []
614
+ };
615
+ if (looksLikeWindows1252Text(bytes)) return {
616
+ text: decodeWindows1252(bytes),
617
+ encoding: "windows-1252",
618
+ source: "detected",
619
+ confidence: "low",
620
+ warnings: [guessWarning("windows-1252", "the bytes carry no byte order mark, are not well-formed UTF-8, and read as Western text")]
621
+ };
622
+ throw new UndecodableTextError("unrecognised", "bytes are text but match none of the supported encodings: not UTF-8, and not plausible as windows-1252");
623
+ }
624
+ /**
625
+ * {@link decodeText}, returning `undefined` where it would throw.
626
+ *
627
+ * For a caller asking whether bytes are decodable at all, a schema refinement being the case this exists for, where an exception would be control flow rather than an error.
628
+ * @param bytes - The bytes to decode.
629
+ * @param options - An explicit `encoding` to decode under, skipping detection.
630
+ * @returns What {@link decodeText} would return, or `undefined` where it would throw.
631
+ */
632
+ function tryDecodeText(bytes, options = {}) {
633
+ try {
634
+ return decodeText(bytes, options);
635
+ } catch {
636
+ return;
637
+ }
638
+ }
639
+ //#endregion
640
+ //#region src/text/labels.ts
641
+ /** Every spelling a document may use, mapped to the encoding decodeText decodes under. Keys are already lowercased and trimmed, which is the form {@link resolveEncodingLabel} reduces its argument to. */
642
+ const ENCODING_LABELS = /* @__PURE__ */ new Map([
643
+ ["866", "ibm866"],
644
+ ["ansi_x3.4-1968", "windows-1252"],
645
+ ["arabic", "iso-8859-6"],
646
+ ["ascii", "windows-1252"],
647
+ ["asmo-708", "iso-8859-6"],
648
+ ["cp1250", "windows-1250"],
649
+ ["cp1251", "windows-1251"],
650
+ ["cp1252", "windows-1252"],
651
+ ["cp1253", "windows-1253"],
652
+ ["cp1254", "windows-1254"],
653
+ ["cp1255", "windows-1255"],
654
+ ["cp1256", "windows-1256"],
655
+ ["cp1257", "windows-1257"],
656
+ ["cp1258", "windows-1258"],
657
+ ["cp819", "windows-1252"],
658
+ ["cp866", "ibm866"],
659
+ ["csibm866", "ibm866"],
660
+ ["csiso88596e", "iso-8859-6"],
661
+ ["csiso88596i", "iso-8859-6"],
662
+ ["csiso88598e", "iso-8859-8"],
663
+ ["csiso88598i", "iso-8859-8-i"],
664
+ ["csisolatin1", "windows-1252"],
665
+ ["csisolatin2", "iso-8859-2"],
666
+ ["csisolatin3", "iso-8859-3"],
667
+ ["csisolatin4", "iso-8859-4"],
668
+ ["csisolatin5", "windows-1254"],
669
+ ["csisolatin6", "iso-8859-10"],
670
+ ["csisolatin9", "iso-8859-15"],
671
+ ["csisolatinarabic", "iso-8859-6"],
672
+ ["csisolatincyrillic", "iso-8859-5"],
673
+ ["csisolatingreek", "iso-8859-7"],
674
+ ["csisolatinhebrew", "iso-8859-8"],
675
+ ["cskoi8r", "koi8-r"],
676
+ ["csmacintosh", "macintosh"],
677
+ ["csunicode", "utf-16le"],
678
+ ["cyrillic", "iso-8859-5"],
679
+ ["dos-874", "windows-874"],
680
+ ["ecma-114", "iso-8859-6"],
681
+ ["ecma-118", "iso-8859-7"],
682
+ ["elot_928", "iso-8859-7"],
683
+ ["greek", "iso-8859-7"],
684
+ ["greek8", "iso-8859-7"],
685
+ ["hebrew", "iso-8859-8"],
686
+ ["ibm819", "windows-1252"],
687
+ ["ibm866", "ibm866"],
688
+ ["iso-10646-ucs-2", "utf-16le"],
689
+ ["iso-8859-1", "windows-1252"],
690
+ ["iso-8859-10", "iso-8859-10"],
691
+ ["iso-8859-11", "windows-874"],
692
+ ["iso-8859-13", "iso-8859-13"],
693
+ ["iso-8859-14", "iso-8859-14"],
694
+ ["iso-8859-15", "iso-8859-15"],
695
+ ["iso-8859-16", "iso-8859-16"],
696
+ ["iso-8859-2", "iso-8859-2"],
697
+ ["iso-8859-3", "iso-8859-3"],
698
+ ["iso-8859-4", "iso-8859-4"],
699
+ ["iso-8859-5", "iso-8859-5"],
700
+ ["iso-8859-6", "iso-8859-6"],
701
+ ["iso-8859-6-e", "iso-8859-6"],
702
+ ["iso-8859-6-i", "iso-8859-6"],
703
+ ["iso-8859-7", "iso-8859-7"],
704
+ ["iso-8859-8", "iso-8859-8"],
705
+ ["iso-8859-8-e", "iso-8859-8"],
706
+ ["iso-8859-8-i", "iso-8859-8-i"],
707
+ ["iso-8859-9", "windows-1254"],
708
+ ["iso-ir-100", "windows-1252"],
709
+ ["iso-ir-101", "iso-8859-2"],
710
+ ["iso-ir-109", "iso-8859-3"],
711
+ ["iso-ir-110", "iso-8859-4"],
712
+ ["iso-ir-126", "iso-8859-7"],
713
+ ["iso-ir-127", "iso-8859-6"],
714
+ ["iso-ir-138", "iso-8859-8"],
715
+ ["iso-ir-144", "iso-8859-5"],
716
+ ["iso-ir-148", "windows-1254"],
717
+ ["iso-ir-157", "iso-8859-10"],
718
+ ["iso8859-1", "windows-1252"],
719
+ ["iso8859-10", "iso-8859-10"],
720
+ ["iso8859-11", "windows-874"],
721
+ ["iso8859-13", "iso-8859-13"],
722
+ ["iso8859-14", "iso-8859-14"],
723
+ ["iso8859-15", "iso-8859-15"],
724
+ ["iso8859-2", "iso-8859-2"],
725
+ ["iso8859-3", "iso-8859-3"],
726
+ ["iso8859-4", "iso-8859-4"],
727
+ ["iso8859-5", "iso-8859-5"],
728
+ ["iso8859-6", "iso-8859-6"],
729
+ ["iso8859-7", "iso-8859-7"],
730
+ ["iso8859-8", "iso-8859-8"],
731
+ ["iso8859-9", "windows-1254"],
732
+ ["iso88591", "windows-1252"],
733
+ ["iso885910", "iso-8859-10"],
734
+ ["iso885911", "windows-874"],
735
+ ["iso885913", "iso-8859-13"],
736
+ ["iso885914", "iso-8859-14"],
737
+ ["iso885915", "iso-8859-15"],
738
+ ["iso88592", "iso-8859-2"],
739
+ ["iso88593", "iso-8859-3"],
740
+ ["iso88594", "iso-8859-4"],
741
+ ["iso88595", "iso-8859-5"],
742
+ ["iso88596", "iso-8859-6"],
743
+ ["iso88597", "iso-8859-7"],
744
+ ["iso88598", "iso-8859-8"],
745
+ ["iso88599", "windows-1254"],
746
+ ["iso_8859-1", "windows-1252"],
747
+ ["iso_8859-15", "iso-8859-15"],
748
+ ["iso_8859-1:1987", "windows-1252"],
749
+ ["iso_8859-2", "iso-8859-2"],
750
+ ["iso_8859-2:1987", "iso-8859-2"],
751
+ ["iso_8859-3", "iso-8859-3"],
752
+ ["iso_8859-3:1988", "iso-8859-3"],
753
+ ["iso_8859-4", "iso-8859-4"],
754
+ ["iso_8859-4:1988", "iso-8859-4"],
755
+ ["iso_8859-5", "iso-8859-5"],
756
+ ["iso_8859-5:1988", "iso-8859-5"],
757
+ ["iso_8859-6", "iso-8859-6"],
758
+ ["iso_8859-6:1987", "iso-8859-6"],
759
+ ["iso_8859-7", "iso-8859-7"],
760
+ ["iso_8859-7:1987", "iso-8859-7"],
761
+ ["iso_8859-8", "iso-8859-8"],
762
+ ["iso_8859-8:1988", "iso-8859-8"],
763
+ ["iso_8859-9", "windows-1254"],
764
+ ["iso_8859-9:1989", "windows-1254"],
765
+ ["koi", "koi8-r"],
766
+ ["koi8", "koi8-r"],
767
+ ["koi8-r", "koi8-r"],
768
+ ["koi8-ru", "koi8-u"],
769
+ ["koi8-u", "koi8-u"],
770
+ ["koi8_r", "koi8-r"],
771
+ ["l1", "windows-1252"],
772
+ ["l2", "iso-8859-2"],
773
+ ["l3", "iso-8859-3"],
774
+ ["l4", "iso-8859-4"],
775
+ ["l5", "windows-1254"],
776
+ ["l6", "iso-8859-10"],
777
+ ["l9", "iso-8859-15"],
778
+ ["latin1", "windows-1252"],
779
+ ["latin2", "iso-8859-2"],
780
+ ["latin3", "iso-8859-3"],
781
+ ["latin4", "iso-8859-4"],
782
+ ["latin5", "windows-1254"],
783
+ ["latin6", "iso-8859-10"],
784
+ ["logical", "iso-8859-8-i"],
785
+ ["mac", "macintosh"],
786
+ ["macintosh", "macintosh"],
787
+ ["sun_eu_greek", "iso-8859-7"],
788
+ ["tis-620", "windows-874"],
789
+ ["ucs-2", "utf-16le"],
790
+ ["unicode", "utf-16le"],
791
+ ["unicode-1-1-utf-8", "utf-8"],
792
+ ["unicode11utf8", "utf-8"],
793
+ ["unicode20utf8", "utf-8"],
794
+ ["unicodefeff", "utf-16le"],
795
+ ["unicodefffe", "utf-16be"],
796
+ ["us-ascii", "windows-1252"],
797
+ ["utf-16", "utf-16le"],
798
+ ["utf-16be", "utf-16be"],
799
+ ["utf-16le", "utf-16le"],
800
+ ["utf-32", "utf-32le"],
801
+ ["utf-32be", "utf-32be"],
802
+ ["utf-32le", "utf-32le"],
803
+ ["utf-8", "utf-8"],
804
+ ["utf8", "utf-8"],
805
+ ["visual", "iso-8859-8"],
806
+ ["windows-1250", "windows-1250"],
807
+ ["windows-1251", "windows-1251"],
808
+ ["windows-1252", "windows-1252"],
809
+ ["windows-1253", "windows-1253"],
810
+ ["windows-1254", "windows-1254"],
811
+ ["windows-1255", "windows-1255"],
812
+ ["windows-1256", "windows-1256"],
813
+ ["windows-1257", "windows-1257"],
814
+ ["windows-1258", "windows-1258"],
815
+ ["windows-874", "windows-874"],
816
+ ["x-cp1250", "windows-1250"],
817
+ ["x-cp1251", "windows-1251"],
818
+ ["x-cp1252", "windows-1252"],
819
+ ["x-cp1253", "windows-1253"],
820
+ ["x-cp1254", "windows-1254"],
821
+ ["x-cp1255", "windows-1255"],
822
+ ["x-cp1256", "windows-1256"],
823
+ ["x-cp1257", "windows-1257"],
824
+ ["x-cp1258", "windows-1258"],
825
+ ["x-mac-cyrillic", "x-mac-cyrillic"],
826
+ ["x-mac-roman", "macintosh"],
827
+ ["x-mac-ukrainian", "x-mac-cyrillic"],
828
+ ["x-unicode20utf8", "utf-8"]
829
+ ]);
830
+ /**
831
+ * Resolves the name a document gives its own encoding to one {@link decodeText} can decode under.
832
+ *
833
+ * Matching follows the Encoding Standard: the name is stripped of leading and trailing ASCII whitespace and lowercased before lookup, so " UTF-8 " and "utf-8" are the same label. A name decodeText cannot decode, a legacy multi-byte encoding or something unrecognised entirely, resolves to `undefined` rather than to an approximation.
834
+ * @param label - The declared encoding name, however the document spelled it.
835
+ * @returns The encoding to decode under, or `undefined` when the name names nothing decodeText decodes.
836
+ */
837
+ function resolveEncodingLabel(label) {
838
+ return ENCODING_LABELS.get(label.trim().toLowerCase());
839
+ }
840
+ //#endregion
227
841
  //#region src/image/png-filter.ts
228
842
  function paethPredictor(a, b, c) {
229
843
  const p = a + b - c;
@@ -713,17 +1327,24 @@ exports.ByteWriter = ByteWriter;
713
1327
  exports.MAX_INFLATE_OUTPUT_BYTES = MAX_INFLATE_OUTPUT_BYTES;
714
1328
  exports.PNG_MAX_DIMENSION = PNG_MAX_DIMENSION;
715
1329
  exports.PNG_MAX_PIXELS = PNG_MAX_PIXELS;
1330
+ exports.TEXT_DECODE_CHUNK_CODE_UNITS = TEXT_DECODE_CHUNK_CODE_UNITS;
1331
+ exports.UndecodableTextError = UndecodableTextError;
716
1332
  exports.base64ToBytes = base64ToBytes;
717
1333
  exports.bytesToBase64 = bytesToBase64;
718
1334
  exports.concatBytes = concatBytes;
719
1335
  exports.crc32 = crc32;
720
1336
  exports.decodePng = decodePng;
1337
+ exports.decodeText = decodeText;
721
1338
  exports.deflate = deflate;
1339
+ exports.detectByteOrderMark = detectByteOrderMark;
722
1340
  exports.encodePng = encodePng;
723
1341
  exports.exceedsMaxPixelCount = exceedsMaxPixelCount;
724
1342
  exports.filterScanlines = filterScanlines;
725
1343
  exports.inflate = inflate;
726
1344
  exports.inflateTolerant = inflateTolerant;
727
1345
  exports.isAsciiWhitespace = isAsciiWhitespace;
1346
+ exports.isProbablyText = isProbablyText;
728
1347
  exports.readJpegInfo = readJpegInfo;
1348
+ exports.resolveEncodingLabel = resolveEncodingLabel;
1349
+ exports.tryDecodeText = tryDecodeText;
729
1350
  exports.unfilterScanlines = unfilterScanlines;