document-bytes 1.7.0 → 1.8.1

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 CHANGED
@@ -42,18 +42,18 @@ To run a single test file, pass its path to vitest directly, e.g. `pnpm exec vit
42
42
 
43
43
  ## What it provides
44
44
 
45
- | Module | Exports |
46
- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
47
- | `bytes/writer` | `ByteWriter` (chunked growable byte-output builder), `concatBytes` |
48
- | `bytes/reader` | `ByteReader` (sequential big/little-endian byte reader), `isAsciiWhitespace` |
49
- | `bytes/base64` | `bytesToBase64`, `base64ToBytes` (standard-alphabet base64, RFC 4648 section 4, with padding — the one implementation every package in the family shares for image payloads and `data:` URIs), `BASE64_ENCODE_CHUNK_CHARS` |
50
- | `bytes/crc32` | `crc32` (IEEE 802.3 / ZIP / PNG polynomial table-driven CRC-32) |
51
- | `bytes/flate` | `deflate`, `inflate`, `inflateTolerant` (fflate-backed DEFLATE compression/decompression with a safety cap) |
52
- | `image/png-encode` | `encodePng` (raw RGB/RGBA pixels → PNG bytes; a truecolour source image whose pixels reduce to 256 or fewer distinct colours is encoded both as indexed colour, PNG colour type 3 with a PLTE and, where needed, a tRNS chunk, and as plain truecolour, and whichever comes out smaller is returned -- indexed colour wins for the large flat-colour images typical of diagrams and screenshots, but the PLTE/tRNS chunk overhead can make it larger for small images, so the encoder measures rather than assumes, at the cost of a full second encode for every eligible image; throws if either `width` or `height` is not a positive integer no greater than the PNG spec's own IHDR limit, or if their product exceeds a practical per-call pixel-count ceiling, since PNG's IHDR chunk has no valid encoding for zero, negative, fractional, or non-finite dimensions and this bounds an otherwise-unbounded encode to a fixed worst case) |
53
- | `image/png-decode` | `decodePng` (PNG bytes → raw pixels, handling every PNG colour type including indexed/palette via its own PLTE/tRNS lookup), `RawImage` |
54
- | `image/png-filter` | `filterScanlines`, `unfilterScanlines` (the five PNG scanline filters) |
55
- | `image/jpeg-info` | `readJpegInfo` (JPEG header reader: dimensions, components, progressive flag — no sample decoding) |
56
- | `text/decode` | `decodeText`, `tryDecodeText`, `isProbablyText`, `UndecodableTextError`, `TEXT_DECODE_CHUNK_CODE_UNITS` (bytes → text with the character encoding worked out from the bytes; see [Text decoding](#text-decoding) below) |
45
+ | Module | Exports |
46
+ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
47
+ | `bytes/writer` | `ByteWriter` (chunked growable byte-output builder), `concatBytes` |
48
+ | `bytes/reader` | `ByteReader` (sequential big/little-endian byte reader), `isAsciiWhitespace` |
49
+ | `bytes/base64` | `bytesToBase64`, `base64ToBytes` (standard-alphabet base64, RFC 4648 section 4, with padding — the one implementation every package in the family shares for image payloads and `data:` URIs), `BASE64_ENCODE_CHUNK_CHARS` |
50
+ | `bytes/crc32` | `crc32` (IEEE 802.3 / ZIP / PNG polynomial table-driven CRC-32) |
51
+ | `bytes/flate` | `deflate`, `inflate`, `inflateTolerant` (fflate-backed DEFLATE compression/decompression with a safety cap) |
52
+ | `image/png-encode` | `encodePng` (raw RGB/RGBA pixels → PNG bytes; a truecolour source image whose pixels reduce to 256 or fewer distinct colours is encoded both as indexed colour, PNG colour type 3 with a PLTE and, where needed, a tRNS chunk, and as plain truecolour, and whichever comes out smaller is returned — indexed colour wins for the large flat-colour images typical of diagrams and screenshots, but the PLTE/tRNS chunk overhead can make it larger for small images, so the encoder measures rather than assumes, at the cost of a full second encode for every eligible image; throws if either `width` or `height` is not a positive integer no greater than the PNG spec's own IHDR limit, or if their product exceeds a practical per-call pixel-count ceiling, since PNG's IHDR chunk has no valid encoding for zero, negative, fractional, or non-finite dimensions and this bounds an otherwise-unbounded encode to a fixed worst case) |
53
+ | `image/png-decode` | `decodePng` (PNG bytes → raw pixels, handling every PNG colour type including indexed/palette via its own PLTE/tRNS lookup), `RawImage` |
54
+ | `image/png-filter` | `filterScanlines`, `unfilterScanlines` (the five PNG scanline filters) |
55
+ | `image/jpeg-info` | `readJpegInfo` (JPEG header reader: dimensions, components, progressive flag — no sample decoding) |
56
+ | `text/decode` | `decodeText`, `tryDecodeText`, `detectByteOrderMark`, `isProbablyText`, `UndecodableTextError`, `TEXT_DECODE_CHUNK_CODE_UNITS` (bytes → text with the character encoding worked out from the bytes; see [Text decoding](#text-decoding) below) |
57
57
 
58
58
  ## Text decoding
59
59
 
@@ -73,6 +73,8 @@ Anything guessed (`confidence: "low"`) also carries a `warnings` entry naming wh
73
73
 
74
74
  Bytes that are not text at all are refused with an `UndecodableTextError` before any guess is made, since without that gate windows-1252 would read a PNG as a page of mojibake instead of refusing it. `isProbablyText` is that judgement on its own, for a caller whose real question is whether bytes are text: a NUL byte, or more than one C0 control byte other than tab, line feed, form feed and carriage return per 64 bytes, says binary.
75
75
 
76
+ `detectByteOrderMark` is step 2 above on its own, for a caller that has to settle the encoding before it can safely read anything past the mark — an XML document's own encoding declaration is 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. It returns the same encoding and mark length `decodeText` itself would settle on from a mark, or `undefined` when the bytes carry none of the five it recognises.
77
+
76
78
  Everything except UTF-8 is decoded by this package rather than through `TextDecoder`. `TextDecoder`'s legacy single-byte and UTF-16 support comes from the host's ICU build, which a Node binary compiled with small-icu does not carry, and the [Encoding Standard](https://encoding.spec.whatwg.org/#names-and-labels) has no UTF-32 at all, so delegating would make the same bytes decode differently, or not at all, depending on where the code runs. The `pnpm test:workers` suite decodes windows-1252, UTF-16 and UTF-32 inside a real `workerd` isolate for exactly that reason, and one unit test checks the whole windows-1252 table, all 256 bytes, against the platform's own decoder wherever the platform has one.
77
79
 
78
80
  Three limits are worth knowing rather than discovering:
package/dist/index.cjs CHANGED
@@ -224,6 +224,38 @@ 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
227
259
  //#region src/text/decode.ts
228
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. */
229
261
  var UndecodableTextError = class extends Error {
@@ -325,6 +357,20 @@ const BOM_SIGNATURES = [
325
357
  function findBom(bytes) {
326
358
  return BOM_SIGNATURES.find((signature) => signature.bytes.every((value, index) => bytes[index] === value));
327
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
+ }
328
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. */
329
375
  function stripBom(bytes, encoding) {
330
376
  const bom = findBom(bytes);
@@ -387,6 +433,27 @@ function decodeUtf8(bytes) {
387
433
  if (text === void 0) throw new UndecodableTextError("malformed", "UTF-8 text must hold only well-formed byte sequences");
388
434
  return text;
389
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
+ }
390
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. */
391
458
  const DECODERS = {
392
459
  "utf-8": decodeUtf8,
@@ -394,7 +461,34 @@ const DECODERS = {
394
461
  "utf-16be": (bytes) => decodeUtf16(bytes, false),
395
462
  "utf-32le": (bytes) => decodeUtf32(bytes, true),
396
463
  "utf-32be": (bytes) => decodeUtf32(bytes, false),
397
- "windows-1252": decodeWindows1252
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")
398
492
  };
399
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. */
400
494
  function codesAreTextual(codeAt, length) {
@@ -543,6 +637,207 @@ function tryDecodeText(bytes, options = {}) {
543
637
  }
544
638
  }
545
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
546
841
  //#region src/image/png-filter.ts
547
842
  function paethPredictor(a, b, c) {
548
843
  const p = a + b - c;
@@ -1041,6 +1336,7 @@ exports.crc32 = crc32;
1041
1336
  exports.decodePng = decodePng;
1042
1337
  exports.decodeText = decodeText;
1043
1338
  exports.deflate = deflate;
1339
+ exports.detectByteOrderMark = detectByteOrderMark;
1044
1340
  exports.encodePng = encodePng;
1045
1341
  exports.exceedsMaxPixelCount = exceedsMaxPixelCount;
1046
1342
  exports.filterScanlines = filterScanlines;
@@ -1049,5 +1345,6 @@ exports.inflateTolerant = inflateTolerant;
1049
1345
  exports.isAsciiWhitespace = isAsciiWhitespace;
1050
1346
  exports.isProbablyText = isProbablyText;
1051
1347
  exports.readJpegInfo = readJpegInfo;
1348
+ exports.resolveEncodingLabel = resolveEncodingLabel;
1052
1349
  exports.tryDecodeText = tryDecodeText;
1053
1350
  exports.unfilterScanlines = unfilterScanlines;
package/dist/index.d.cts CHANGED
@@ -64,13 +64,19 @@ interface InflateResult {
64
64
  }
65
65
  declare function inflateTolerant(data: Uint8Array<ArrayBuffer>): InflateResult;
66
66
  //#endregion
67
+ //#region src/text/legacy-single-byte-tables.d.ts
68
+ /** A legacy single-byte encoding {@link decodeText} can decode when the caller declares it explicitly. Never produced by detection: nothing distinguishes one of these code pages from another, or from windows-1252, without the statistical model this module does not carry (see {@link TextEncodingLabel}). */
69
+ type LegacySingleByteEncodingLabel = "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic";
70
+ //#endregion
67
71
  //#region src/text/decode.d.ts
68
72
  /**
69
73
  * The character encodings {@link decodeText} can produce text from.
70
74
  *
71
- * Deliberately bounded: each is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test. Legacy CJK and Cyrillic code pages are outside the set on purpose, since nothing tells them apart from one another without the statistical model this module does not carry; bytes that look like one are refused rather than guessed at. That boundary also limits what {@link DecodeTextOptions.encoding} can name, which is a narrower restriction than detection itself needs (ExaDev/documents.js#1361).
75
+ * Detection stays deliberately bounded to `"utf-8"`, `"utf-16le"`, `"utf-16be"`, `"utf-32le"`, `"utf-32be"` and `"windows-1252"`: each of those is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test, and nothing distinguishes one legacy code page from another, or from windows-1252, without the statistical model this module does not carry. Bytes that look like an undetected legacy encoding are refused rather than guessed at.
76
+ *
77
+ * {@link DecodeTextOptions.encoding} can name more than detection can reach, though: every {@link LegacySingleByteEncodingLabel} the WHATWG Encoding Standard defines is also accepted, for a caller who already knows their file's code page rather than asking this module to guess it (ExaDev/documents.js#1361). Legacy multi-byte and double-byte CJK encodings (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR) remain outside what either detection or a declared `encoding` can reach; see legacy-single-byte-tables.ts for why that is a different kind of change, tracked separately as ExaDev/documents.js#1388.
72
78
  */
73
- type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252";
79
+ type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252" | LegacySingleByteEncodingLabel;
74
80
  /**
75
81
  * How {@link decodeText} arrived at the encoding it used.
76
82
  *
@@ -115,6 +121,21 @@ declare class UndecodableTextError extends Error {
115
121
  * Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
116
122
  */
117
123
  declare const TEXT_DECODE_CHUNK_CODE_UNITS: number;
124
+ /** A byte order mark's own encoding, and how many leading bytes it occupies. */
125
+ interface ByteOrderMark {
126
+ /** The encoding the mark identifies. */
127
+ readonly encoding: TextEncodingLabel;
128
+ /** The mark's own length in bytes, ahead of whatever it precedes. */
129
+ readonly length: number;
130
+ }
131
+ /**
132
+ * Detects a byte order mark at the start of `bytes`, without decoding anything past it.
133
+ *
134
+ * {@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.
135
+ * @param bytes - The bytes to check.
136
+ * @returns The mark's encoding and length, or `undefined` when the bytes carry none of the five marks {@link decodeText} itself recognises.
137
+ */
138
+ declare function detectByteOrderMark(bytes: Uint8Array): ByteOrderMark | undefined;
118
139
  /**
119
140
  * Whether bytes can hold text at all, judged without reference to which encoding they might be in.
120
141
  *
@@ -147,6 +168,16 @@ declare function decodeText(bytes: Uint8Array, options?: DecodeTextOptions): Dec
147
168
  */
148
169
  declare function tryDecodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText | undefined;
149
170
  //#endregion
171
+ //#region src/text/labels.d.ts
172
+ /**
173
+ * Resolves the name a document gives its own encoding to one {@link decodeText} can decode under.
174
+ *
175
+ * 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.
176
+ * @param label - The declared encoding name, however the document spelled it.
177
+ * @returns The encoding to decode under, or `undefined` when the name names nothing decodeText decodes.
178
+ */
179
+ declare function resolveEncodingLabel(label: string): TextEncodingLabel | undefined;
180
+ //#endregion
150
181
  //#region src/image/png-decode.d.ts
151
182
  interface RawImage {
152
183
  readonly width: number;
@@ -185,4 +216,4 @@ interface JpegInfo {
185
216
  }
186
217
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
187
218
  //#endregion
188
- export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
219
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
package/dist/index.d.ts CHANGED
@@ -64,13 +64,19 @@ interface InflateResult {
64
64
  }
65
65
  declare function inflateTolerant(data: Uint8Array<ArrayBuffer>): InflateResult;
66
66
  //#endregion
67
+ //#region src/text/legacy-single-byte-tables.d.ts
68
+ /** A legacy single-byte encoding {@link decodeText} can decode when the caller declares it explicitly. Never produced by detection: nothing distinguishes one of these code pages from another, or from windows-1252, without the statistical model this module does not carry (see {@link TextEncodingLabel}). */
69
+ type LegacySingleByteEncodingLabel = "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic";
70
+ //#endregion
67
71
  //#region src/text/decode.d.ts
68
72
  /**
69
73
  * The character encodings {@link decodeText} can produce text from.
70
74
  *
71
- * Deliberately bounded: each is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test. Legacy CJK and Cyrillic code pages are outside the set on purpose, since nothing tells them apart from one another without the statistical model this module does not carry; bytes that look like one are refused rather than guessed at. That boundary also limits what {@link DecodeTextOptions.encoding} can name, which is a narrower restriction than detection itself needs (ExaDev/documents.js#1361).
75
+ * Detection stays deliberately bounded to `"utf-8"`, `"utf-16le"`, `"utf-16be"`, `"utf-32le"`, `"utf-32be"` and `"windows-1252"`: each of those is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test, and nothing distinguishes one legacy code page from another, or from windows-1252, without the statistical model this module does not carry. Bytes that look like an undetected legacy encoding are refused rather than guessed at.
76
+ *
77
+ * {@link DecodeTextOptions.encoding} can name more than detection can reach, though: every {@link LegacySingleByteEncodingLabel} the WHATWG Encoding Standard defines is also accepted, for a caller who already knows their file's code page rather than asking this module to guess it (ExaDev/documents.js#1361). Legacy multi-byte and double-byte CJK encodings (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR) remain outside what either detection or a declared `encoding` can reach; see legacy-single-byte-tables.ts for why that is a different kind of change, tracked separately as ExaDev/documents.js#1388.
72
78
  */
73
- type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252";
79
+ type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252" | LegacySingleByteEncodingLabel;
74
80
  /**
75
81
  * How {@link decodeText} arrived at the encoding it used.
76
82
  *
@@ -115,6 +121,21 @@ declare class UndecodableTextError extends Error {
115
121
  * Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
116
122
  */
117
123
  declare const TEXT_DECODE_CHUNK_CODE_UNITS: number;
124
+ /** A byte order mark's own encoding, and how many leading bytes it occupies. */
125
+ interface ByteOrderMark {
126
+ /** The encoding the mark identifies. */
127
+ readonly encoding: TextEncodingLabel;
128
+ /** The mark's own length in bytes, ahead of whatever it precedes. */
129
+ readonly length: number;
130
+ }
131
+ /**
132
+ * Detects a byte order mark at the start of `bytes`, without decoding anything past it.
133
+ *
134
+ * {@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.
135
+ * @param bytes - The bytes to check.
136
+ * @returns The mark's encoding and length, or `undefined` when the bytes carry none of the five marks {@link decodeText} itself recognises.
137
+ */
138
+ declare function detectByteOrderMark(bytes: Uint8Array): ByteOrderMark | undefined;
118
139
  /**
119
140
  * Whether bytes can hold text at all, judged without reference to which encoding they might be in.
120
141
  *
@@ -147,6 +168,16 @@ declare function decodeText(bytes: Uint8Array, options?: DecodeTextOptions): Dec
147
168
  */
148
169
  declare function tryDecodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText | undefined;
149
170
  //#endregion
171
+ //#region src/text/labels.d.ts
172
+ /**
173
+ * Resolves the name a document gives its own encoding to one {@link decodeText} can decode under.
174
+ *
175
+ * 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.
176
+ * @param label - The declared encoding name, however the document spelled it.
177
+ * @returns The encoding to decode under, or `undefined` when the name names nothing decodeText decodes.
178
+ */
179
+ declare function resolveEncodingLabel(label: string): TextEncodingLabel | undefined;
180
+ //#endregion
150
181
  //#region src/image/png-decode.d.ts
151
182
  interface RawImage {
152
183
  readonly width: number;
@@ -185,4 +216,4 @@ interface JpegInfo {
185
216
  }
186
217
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
187
218
  //#endregion
188
- export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
219
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
package/dist/index.js CHANGED
@@ -223,6 +223,38 @@ function inflateTolerant(data) {
223
223
  };
224
224
  }
225
225
  //#endregion
226
+ //#region src/text/legacy-single-byte-tables.ts
227
+ /** 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. */
228
+ const LEGACY_SINGLE_BYTE_TABLES = {
229
+ ibm866: "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■\xA0",
230
+ "iso-8859-2": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙",
231
+ "iso-8859-3": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙",
232
+ "iso-8859-4": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙",
233
+ "iso-8859-5": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ",
234
+ "iso-8859-6": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������",
235
+ "iso-8859-7": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�",
236
+ "iso-8859-8": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0�¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
237
+ "iso-8859-8-i": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0�¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
238
+ "iso-8859-10": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ",
239
+ "iso-8859-13": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’",
240
+ "iso-8859-14": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ",
241
+ "iso-8859-15": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
242
+ "iso-8859-16": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ",
243
+ "koi8-r": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥\xA0⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ",
244
+ "koi8-u": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥\xA0⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ",
245
+ macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»…\xA0ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ",
246
+ "windows-874": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����",
247
+ "windows-1250": "€‚ƒ„…†‡ˆ‰Š‹ŚŤŽŹ‘’“”•–—˜™š›śťžź\xA0ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙",
248
+ "windows-1251": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—˜™љ›њќћџ\xA0ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя",
249
+ "windows-1253": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�",
250
+ "windows-1254": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ",
251
+ "windows-1255": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�",
252
+ "windows-1256": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں\xA0،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے",
253
+ "windows-1257": "€‚ƒ„…†‡ˆ‰Š‹Œ¨ˇ¸‘’“”•–—˜™š›œ¯˛Ÿ\xA0�¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙",
254
+ "windows-1258": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ\xA0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ",
255
+ "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»…\xA0ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю€"
256
+ };
257
+ //#endregion
226
258
  //#region src/text/decode.ts
227
259
  /** 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. */
228
260
  var UndecodableTextError = class extends Error {
@@ -324,6 +356,20 @@ const BOM_SIGNATURES = [
324
356
  function findBom(bytes) {
325
357
  return BOM_SIGNATURES.find((signature) => signature.bytes.every((value, index) => bytes[index] === value));
326
358
  }
359
+ /**
360
+ * Detects a byte order mark at the start of `bytes`, without decoding anything past it.
361
+ *
362
+ * {@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.
363
+ * @param bytes - The bytes to check.
364
+ * @returns The mark's encoding and length, or `undefined` when the bytes carry none of the five marks {@link decodeText} itself recognises.
365
+ */
366
+ function detectByteOrderMark(bytes) {
367
+ const bom = findBom(bytes);
368
+ return bom === void 0 ? void 0 : {
369
+ encoding: bom.encoding,
370
+ length: bom.bytes.length
371
+ };
372
+ }
327
373
  /** 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. */
328
374
  function stripBom(bytes, encoding) {
329
375
  const bom = findBom(bytes);
@@ -386,6 +432,27 @@ function decodeUtf8(bytes) {
386
432
  if (text === void 0) throw new UndecodableTextError("malformed", "UTF-8 text must hold only well-formed byte sequences");
387
433
  return text;
388
434
  }
435
+ /** 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. */
436
+ const LEGACY_SINGLE_BYTE_GAP_CODE = 65533;
437
+ /** 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. */
438
+ function decodeLegacySingleByte(bytes, table, label) {
439
+ const units = [];
440
+ for (const byte of bytes) {
441
+ if (byte < FIRST_HIGH_BYTE) {
442
+ units.push(byte);
443
+ continue;
444
+ }
445
+ const unit = table.charCodeAt(byte - FIRST_HIGH_BYTE);
446
+ if (unit === LEGACY_SINGLE_BYTE_GAP_CODE) throw new UndecodableTextError("malformed", `${label} has no character for byte 0x${byte.toString(16)}`);
447
+ units.push(unit);
448
+ }
449
+ return fromCodeUnits(units);
450
+ }
451
+ /** 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. */
452
+ function legacySingleByteDecoder(label) {
453
+ const table = LEGACY_SINGLE_BYTE_TABLES[label];
454
+ return (bytes) => decodeLegacySingleByte(bytes, table, label);
455
+ }
389
456
  /** 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. */
390
457
  const DECODERS = {
391
458
  "utf-8": decodeUtf8,
@@ -393,7 +460,34 @@ const DECODERS = {
393
460
  "utf-16be": (bytes) => decodeUtf16(bytes, false),
394
461
  "utf-32le": (bytes) => decodeUtf32(bytes, true),
395
462
  "utf-32be": (bytes) => decodeUtf32(bytes, false),
396
- "windows-1252": decodeWindows1252
463
+ "windows-1252": decodeWindows1252,
464
+ ibm866: legacySingleByteDecoder("ibm866"),
465
+ "iso-8859-2": legacySingleByteDecoder("iso-8859-2"),
466
+ "iso-8859-3": legacySingleByteDecoder("iso-8859-3"),
467
+ "iso-8859-4": legacySingleByteDecoder("iso-8859-4"),
468
+ "iso-8859-5": legacySingleByteDecoder("iso-8859-5"),
469
+ "iso-8859-6": legacySingleByteDecoder("iso-8859-6"),
470
+ "iso-8859-7": legacySingleByteDecoder("iso-8859-7"),
471
+ "iso-8859-8": legacySingleByteDecoder("iso-8859-8"),
472
+ "iso-8859-8-i": legacySingleByteDecoder("iso-8859-8-i"),
473
+ "iso-8859-10": legacySingleByteDecoder("iso-8859-10"),
474
+ "iso-8859-13": legacySingleByteDecoder("iso-8859-13"),
475
+ "iso-8859-14": legacySingleByteDecoder("iso-8859-14"),
476
+ "iso-8859-15": legacySingleByteDecoder("iso-8859-15"),
477
+ "iso-8859-16": legacySingleByteDecoder("iso-8859-16"),
478
+ "koi8-r": legacySingleByteDecoder("koi8-r"),
479
+ "koi8-u": legacySingleByteDecoder("koi8-u"),
480
+ macintosh: legacySingleByteDecoder("macintosh"),
481
+ "windows-874": legacySingleByteDecoder("windows-874"),
482
+ "windows-1250": legacySingleByteDecoder("windows-1250"),
483
+ "windows-1251": legacySingleByteDecoder("windows-1251"),
484
+ "windows-1253": legacySingleByteDecoder("windows-1253"),
485
+ "windows-1254": legacySingleByteDecoder("windows-1254"),
486
+ "windows-1255": legacySingleByteDecoder("windows-1255"),
487
+ "windows-1256": legacySingleByteDecoder("windows-1256"),
488
+ "windows-1257": legacySingleByteDecoder("windows-1257"),
489
+ "windows-1258": legacySingleByteDecoder("windows-1258"),
490
+ "x-mac-cyrillic": legacySingleByteDecoder("x-mac-cyrillic")
397
491
  };
398
492
  /** 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. */
399
493
  function codesAreTextual(codeAt, length) {
@@ -542,6 +636,207 @@ function tryDecodeText(bytes, options = {}) {
542
636
  }
543
637
  }
544
638
  //#endregion
639
+ //#region src/text/labels.ts
640
+ /** 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. */
641
+ const ENCODING_LABELS = /* @__PURE__ */ new Map([
642
+ ["866", "ibm866"],
643
+ ["ansi_x3.4-1968", "windows-1252"],
644
+ ["arabic", "iso-8859-6"],
645
+ ["ascii", "windows-1252"],
646
+ ["asmo-708", "iso-8859-6"],
647
+ ["cp1250", "windows-1250"],
648
+ ["cp1251", "windows-1251"],
649
+ ["cp1252", "windows-1252"],
650
+ ["cp1253", "windows-1253"],
651
+ ["cp1254", "windows-1254"],
652
+ ["cp1255", "windows-1255"],
653
+ ["cp1256", "windows-1256"],
654
+ ["cp1257", "windows-1257"],
655
+ ["cp1258", "windows-1258"],
656
+ ["cp819", "windows-1252"],
657
+ ["cp866", "ibm866"],
658
+ ["csibm866", "ibm866"],
659
+ ["csiso88596e", "iso-8859-6"],
660
+ ["csiso88596i", "iso-8859-6"],
661
+ ["csiso88598e", "iso-8859-8"],
662
+ ["csiso88598i", "iso-8859-8-i"],
663
+ ["csisolatin1", "windows-1252"],
664
+ ["csisolatin2", "iso-8859-2"],
665
+ ["csisolatin3", "iso-8859-3"],
666
+ ["csisolatin4", "iso-8859-4"],
667
+ ["csisolatin5", "windows-1254"],
668
+ ["csisolatin6", "iso-8859-10"],
669
+ ["csisolatin9", "iso-8859-15"],
670
+ ["csisolatinarabic", "iso-8859-6"],
671
+ ["csisolatincyrillic", "iso-8859-5"],
672
+ ["csisolatingreek", "iso-8859-7"],
673
+ ["csisolatinhebrew", "iso-8859-8"],
674
+ ["cskoi8r", "koi8-r"],
675
+ ["csmacintosh", "macintosh"],
676
+ ["csunicode", "utf-16le"],
677
+ ["cyrillic", "iso-8859-5"],
678
+ ["dos-874", "windows-874"],
679
+ ["ecma-114", "iso-8859-6"],
680
+ ["ecma-118", "iso-8859-7"],
681
+ ["elot_928", "iso-8859-7"],
682
+ ["greek", "iso-8859-7"],
683
+ ["greek8", "iso-8859-7"],
684
+ ["hebrew", "iso-8859-8"],
685
+ ["ibm819", "windows-1252"],
686
+ ["ibm866", "ibm866"],
687
+ ["iso-10646-ucs-2", "utf-16le"],
688
+ ["iso-8859-1", "windows-1252"],
689
+ ["iso-8859-10", "iso-8859-10"],
690
+ ["iso-8859-11", "windows-874"],
691
+ ["iso-8859-13", "iso-8859-13"],
692
+ ["iso-8859-14", "iso-8859-14"],
693
+ ["iso-8859-15", "iso-8859-15"],
694
+ ["iso-8859-16", "iso-8859-16"],
695
+ ["iso-8859-2", "iso-8859-2"],
696
+ ["iso-8859-3", "iso-8859-3"],
697
+ ["iso-8859-4", "iso-8859-4"],
698
+ ["iso-8859-5", "iso-8859-5"],
699
+ ["iso-8859-6", "iso-8859-6"],
700
+ ["iso-8859-6-e", "iso-8859-6"],
701
+ ["iso-8859-6-i", "iso-8859-6"],
702
+ ["iso-8859-7", "iso-8859-7"],
703
+ ["iso-8859-8", "iso-8859-8"],
704
+ ["iso-8859-8-e", "iso-8859-8"],
705
+ ["iso-8859-8-i", "iso-8859-8-i"],
706
+ ["iso-8859-9", "windows-1254"],
707
+ ["iso-ir-100", "windows-1252"],
708
+ ["iso-ir-101", "iso-8859-2"],
709
+ ["iso-ir-109", "iso-8859-3"],
710
+ ["iso-ir-110", "iso-8859-4"],
711
+ ["iso-ir-126", "iso-8859-7"],
712
+ ["iso-ir-127", "iso-8859-6"],
713
+ ["iso-ir-138", "iso-8859-8"],
714
+ ["iso-ir-144", "iso-8859-5"],
715
+ ["iso-ir-148", "windows-1254"],
716
+ ["iso-ir-157", "iso-8859-10"],
717
+ ["iso8859-1", "windows-1252"],
718
+ ["iso8859-10", "iso-8859-10"],
719
+ ["iso8859-11", "windows-874"],
720
+ ["iso8859-13", "iso-8859-13"],
721
+ ["iso8859-14", "iso-8859-14"],
722
+ ["iso8859-15", "iso-8859-15"],
723
+ ["iso8859-2", "iso-8859-2"],
724
+ ["iso8859-3", "iso-8859-3"],
725
+ ["iso8859-4", "iso-8859-4"],
726
+ ["iso8859-5", "iso-8859-5"],
727
+ ["iso8859-6", "iso-8859-6"],
728
+ ["iso8859-7", "iso-8859-7"],
729
+ ["iso8859-8", "iso-8859-8"],
730
+ ["iso8859-9", "windows-1254"],
731
+ ["iso88591", "windows-1252"],
732
+ ["iso885910", "iso-8859-10"],
733
+ ["iso885911", "windows-874"],
734
+ ["iso885913", "iso-8859-13"],
735
+ ["iso885914", "iso-8859-14"],
736
+ ["iso885915", "iso-8859-15"],
737
+ ["iso88592", "iso-8859-2"],
738
+ ["iso88593", "iso-8859-3"],
739
+ ["iso88594", "iso-8859-4"],
740
+ ["iso88595", "iso-8859-5"],
741
+ ["iso88596", "iso-8859-6"],
742
+ ["iso88597", "iso-8859-7"],
743
+ ["iso88598", "iso-8859-8"],
744
+ ["iso88599", "windows-1254"],
745
+ ["iso_8859-1", "windows-1252"],
746
+ ["iso_8859-15", "iso-8859-15"],
747
+ ["iso_8859-1:1987", "windows-1252"],
748
+ ["iso_8859-2", "iso-8859-2"],
749
+ ["iso_8859-2:1987", "iso-8859-2"],
750
+ ["iso_8859-3", "iso-8859-3"],
751
+ ["iso_8859-3:1988", "iso-8859-3"],
752
+ ["iso_8859-4", "iso-8859-4"],
753
+ ["iso_8859-4:1988", "iso-8859-4"],
754
+ ["iso_8859-5", "iso-8859-5"],
755
+ ["iso_8859-5:1988", "iso-8859-5"],
756
+ ["iso_8859-6", "iso-8859-6"],
757
+ ["iso_8859-6:1987", "iso-8859-6"],
758
+ ["iso_8859-7", "iso-8859-7"],
759
+ ["iso_8859-7:1987", "iso-8859-7"],
760
+ ["iso_8859-8", "iso-8859-8"],
761
+ ["iso_8859-8:1988", "iso-8859-8"],
762
+ ["iso_8859-9", "windows-1254"],
763
+ ["iso_8859-9:1989", "windows-1254"],
764
+ ["koi", "koi8-r"],
765
+ ["koi8", "koi8-r"],
766
+ ["koi8-r", "koi8-r"],
767
+ ["koi8-ru", "koi8-u"],
768
+ ["koi8-u", "koi8-u"],
769
+ ["koi8_r", "koi8-r"],
770
+ ["l1", "windows-1252"],
771
+ ["l2", "iso-8859-2"],
772
+ ["l3", "iso-8859-3"],
773
+ ["l4", "iso-8859-4"],
774
+ ["l5", "windows-1254"],
775
+ ["l6", "iso-8859-10"],
776
+ ["l9", "iso-8859-15"],
777
+ ["latin1", "windows-1252"],
778
+ ["latin2", "iso-8859-2"],
779
+ ["latin3", "iso-8859-3"],
780
+ ["latin4", "iso-8859-4"],
781
+ ["latin5", "windows-1254"],
782
+ ["latin6", "iso-8859-10"],
783
+ ["logical", "iso-8859-8-i"],
784
+ ["mac", "macintosh"],
785
+ ["macintosh", "macintosh"],
786
+ ["sun_eu_greek", "iso-8859-7"],
787
+ ["tis-620", "windows-874"],
788
+ ["ucs-2", "utf-16le"],
789
+ ["unicode", "utf-16le"],
790
+ ["unicode-1-1-utf-8", "utf-8"],
791
+ ["unicode11utf8", "utf-8"],
792
+ ["unicode20utf8", "utf-8"],
793
+ ["unicodefeff", "utf-16le"],
794
+ ["unicodefffe", "utf-16be"],
795
+ ["us-ascii", "windows-1252"],
796
+ ["utf-16", "utf-16le"],
797
+ ["utf-16be", "utf-16be"],
798
+ ["utf-16le", "utf-16le"],
799
+ ["utf-32", "utf-32le"],
800
+ ["utf-32be", "utf-32be"],
801
+ ["utf-32le", "utf-32le"],
802
+ ["utf-8", "utf-8"],
803
+ ["utf8", "utf-8"],
804
+ ["visual", "iso-8859-8"],
805
+ ["windows-1250", "windows-1250"],
806
+ ["windows-1251", "windows-1251"],
807
+ ["windows-1252", "windows-1252"],
808
+ ["windows-1253", "windows-1253"],
809
+ ["windows-1254", "windows-1254"],
810
+ ["windows-1255", "windows-1255"],
811
+ ["windows-1256", "windows-1256"],
812
+ ["windows-1257", "windows-1257"],
813
+ ["windows-1258", "windows-1258"],
814
+ ["windows-874", "windows-874"],
815
+ ["x-cp1250", "windows-1250"],
816
+ ["x-cp1251", "windows-1251"],
817
+ ["x-cp1252", "windows-1252"],
818
+ ["x-cp1253", "windows-1253"],
819
+ ["x-cp1254", "windows-1254"],
820
+ ["x-cp1255", "windows-1255"],
821
+ ["x-cp1256", "windows-1256"],
822
+ ["x-cp1257", "windows-1257"],
823
+ ["x-cp1258", "windows-1258"],
824
+ ["x-mac-cyrillic", "x-mac-cyrillic"],
825
+ ["x-mac-roman", "macintosh"],
826
+ ["x-mac-ukrainian", "x-mac-cyrillic"],
827
+ ["x-unicode20utf8", "utf-8"]
828
+ ]);
829
+ /**
830
+ * Resolves the name a document gives its own encoding to one {@link decodeText} can decode under.
831
+ *
832
+ * 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.
833
+ * @param label - The declared encoding name, however the document spelled it.
834
+ * @returns The encoding to decode under, or `undefined` when the name names nothing decodeText decodes.
835
+ */
836
+ function resolveEncodingLabel(label) {
837
+ return ENCODING_LABELS.get(label.trim().toLowerCase());
838
+ }
839
+ //#endregion
545
840
  //#region src/image/png-filter.ts
546
841
  function paethPredictor(a, b, c) {
547
842
  const p = a + b - c;
@@ -1025,4 +1320,4 @@ function readJpegInfo(bytes) {
1025
1320
  throw new Error("no SOF marker found in JPEG file");
1026
1321
  }
1027
1322
  //#endregion
1028
- export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, TEXT_DECODE_CHUNK_CODE_UNITS, UndecodableTextError, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
1323
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, TEXT_DECODE_CHUNK_CODE_UNITS, UndecodableTextError, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document-bytes",
3
- "version": "1.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "Generic byte-level primitives (ByteWriter, ByteReader, CRC-32, deflate/inflate, base64) and PNG/JPEG image encoding/decoding with zero PDF knowledge — the shared utility package for the documents.js family.",
5
5
  "type": "module",
6
6
  "repository": {