document-bytes 2.0.2 → 2.1.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/README.md CHANGED
@@ -26,7 +26,7 @@ graph TD
26
26
 
27
27
  ## Getting started
28
28
 
29
- Requires Node.js `>=20` and pnpm `11.6.0`.
29
+ Requires Node.js `>=20` and pnpm (the version pinned as `packageManager` in the root `package.json`).
30
30
 
31
31
  ```sh
32
32
  pnpm install
@@ -51,7 +51,7 @@ To run a single test file, pass its path to vitest directly, e.g. `pnpm exec vit
51
51
  | `bytes/flate` | `deflate`, `inflate`, `inflateTolerant` (fflate-backed DEFLATE compression/decompression with a safety cap) |
52
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
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) |
54
+ | `image/png-filter` | `filterScanlines`, `unfilterScanlines` (the five PNG scanline filters), `filterScanlineRows` (`filterScanlines` reading each row from a callback, so a caller whose pixels are not laid out as PNG rows writes each row as it is filtered rather than building an interleaved copy of the whole image first; `encodePng` filters its colour and alpha planes this way) |
55
55
  | `image/jpeg-info` | `readJpegInfo` (JPEG header reader: dimensions, components, progressive flag — no sample decoding) |
56
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
 
package/dist/index.cjs CHANGED
@@ -173,7 +173,7 @@ function base64ToBytes(base64) {
173
173
  const CRC32_POLYNOMIAL = 3988292384;
174
174
  const BYTE_VALUES = 256;
175
175
  const BITS_PER_BYTE$2 = 8;
176
- const BYTE_MASK$1 = 255;
176
+ const BYTE_MASK$2 = 255;
177
177
  const CRC32_ALL_ONES = 4294967295;
178
178
  const CRC32_TABLE = (() => {
179
179
  const table = new Uint32Array(BYTE_VALUES);
@@ -186,7 +186,7 @@ const CRC32_TABLE = (() => {
186
186
  })();
187
187
  function crc32(bytes) {
188
188
  let crc = CRC32_ALL_ONES;
189
- for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$1] ^ crc >>> BITS_PER_BYTE$2;
189
+ for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$2] ^ crc >>> BITS_PER_BYTE$2;
190
190
  return (crc ^ CRC32_ALL_ONES) >>> 0;
191
191
  }
192
192
  const MAX_INFLATE_OUTPUT_BYTES = 536870912;
@@ -1344,7 +1344,7 @@ const PNG_FILTER_SUB = 1;
1344
1344
  const PNG_FILTER_UP = 2;
1345
1345
  const PNG_FILTER_AVERAGE = 3;
1346
1346
  const PNG_FILTER_PAETH = 4;
1347
- const BYTE_MASK = 255;
1347
+ const BYTE_MASK$1 = 255;
1348
1348
  const BYTE_MODULUS = 256;
1349
1349
  function paethPredictor(a, b, c) {
1350
1350
  const p = a + b - c;
@@ -1381,7 +1381,7 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
1381
1381
  const a = x >= bpp ? out[outRowStart + x - bpp] : 0;
1382
1382
  const b = prevOutRowStart === void 0 ? 0 : out[prevOutRowStart + x];
1383
1383
  const c = x >= bpp && prevOutRowStart !== void 0 ? out[prevOutRowStart + x - bpp] : 0;
1384
- out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK;
1384
+ out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK$1;
1385
1385
  });
1386
1386
  }
1387
1387
  return out;
@@ -1391,28 +1391,28 @@ function filterRowInto(current, previous, bpp, filterType, target) {
1391
1391
  switch (filterType) {
1392
1392
  case PNG_FILTER_SUB:
1393
1393
  target.forEach((_byte, x) => {
1394
- const filtered = current[x + bpp] - current[x] & BYTE_MASK;
1394
+ const filtered = current[x + bpp] - current[x] & BYTE_MASK$1;
1395
1395
  target[x] = filtered;
1396
1396
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1397
1397
  });
1398
1398
  break;
1399
1399
  case PNG_FILTER_UP:
1400
1400
  target.forEach((_byte, x) => {
1401
- const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK;
1401
+ const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK$1;
1402
1402
  target[x] = filtered;
1403
1403
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1404
1404
  });
1405
1405
  break;
1406
1406
  case PNG_FILTER_AVERAGE:
1407
1407
  target.forEach((_byte, x) => {
1408
- const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK;
1408
+ const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK$1;
1409
1409
  target[x] = filtered;
1410
1410
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1411
1411
  });
1412
1412
  break;
1413
1413
  case PNG_FILTER_PAETH:
1414
1414
  target.forEach((_byte, x) => {
1415
- const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK;
1415
+ const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK$1;
1416
1416
  target[x] = filtered;
1417
1417
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1418
1418
  });
@@ -1433,6 +1433,20 @@ const ALL_FILTER_TYPES = [
1433
1433
  PNG_FILTER_PAETH
1434
1434
  ];
1435
1435
  function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1436
+ return filterScanlineRows((y, row) => {
1437
+ row.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow));
1438
+ }, height, bytesPerRow, bpp, strategy);
1439
+ }
1440
+ /**
1441
+ * Filters pixel rows into PNG's per-scanline IDAT payload shape, as `filterScanlines` does, reading each row from a callback rather than from one buffer holding the whole image: a caller whose pixels are not already laid out as PNG rows (separate colour and alpha planes, say) writes each row as it is filtered instead of building the whole interleaved image first.
1442
+ * @param readRow - Writes row `y`'s unfiltered bytes into `row` (exactly `bytesPerRow` long, holding whatever an earlier row left there: a byte the callback leaves unwritten keeps that value, which is how `filterScanlines` treats a `raw` shorter than `height` rows, so a caller wanting each row to stand alone writes every byte). Called once per row, in order.
1443
+ * @param height - Rows.
1444
+ * @param bytesPerRow - Unfiltered bytes per row.
1445
+ * @param bpp - Bytes per complete pixel, at least 1: the distance the Sub, Average and Paeth filters look back.
1446
+ * @param strategy - As for `filterScanlines`.
1447
+ * @returns The filtered rows, each prefixed by its filter-type byte.
1448
+ */
1449
+ function filterScanlineRows(readRow, height, bytesPerRow, bpp, strategy = "adaptive") {
1436
1450
  const stride = bytesPerRow + 1;
1437
1451
  const out = new Uint8Array(height * stride);
1438
1452
  let current = new Uint8Array(bytesPerRow + bpp);
@@ -1441,7 +1455,7 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1441
1455
  let best = new Uint8Array(bytesPerRow);
1442
1456
  const filterTypes = strategy === "none" ? [PNG_FILTER_NONE] : ALL_FILTER_TYPES;
1443
1457
  Array.from({ length: height }).forEach((_row, y) => {
1444
- current.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow), bpp);
1458
+ readRow(y, current.subarray(bpp));
1445
1459
  let bestType = PNG_FILTER_NONE;
1446
1460
  let bestSum = Number.POSITIVE_INFINITY;
1447
1461
  for (const filterType of filterTypes) {
@@ -1491,6 +1505,7 @@ const OPAQUE_ALPHA$1 = 255;
1491
1505
  const GREEN_SHIFT = 8;
1492
1506
  const BLUE_SHIFT = 16;
1493
1507
  const ALPHA_SHIFT = 24;
1508
+ const BYTE_MASK = 255;
1494
1509
  const PNG_MAX_DIMENSION = 2147483647;
1495
1510
  const PNG_MAX_PIXELS = 1e8;
1496
1511
  function exceedsMaxPixelCount(pixelCount) {
@@ -1528,26 +1543,29 @@ function detectPalette(image) {
1528
1543
  const { width, height, data, alpha } = image;
1529
1544
  const pixelCount = width * height;
1530
1545
  const colorToIndex = /* @__PURE__ */ new Map();
1531
- const indices = new Uint8Array(pixelCount);
1532
1546
  const paletteRgb = [];
1533
1547
  const paletteAlpha = [];
1534
- for (let i = 0; i < pixelCount; i++) {
1548
+ const colorKey = (i) => {
1535
1549
  const base = i * RGB_CHANNELS$1;
1536
1550
  const r = data[base] ?? 0;
1537
1551
  const g = data[base + 1] ?? 0;
1538
1552
  const b = data[base + 2] ?? 0;
1539
1553
  const a = alpha === void 0 ? OPAQUE_ALPHA$1 : alpha[i] ?? 0;
1540
- const key = r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
1541
- let index = colorToIndex.get(key);
1542
- if (index === void 0) {
1554
+ return r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
1555
+ };
1556
+ for (let i = 0; i < pixelCount; i++) {
1557
+ const key = colorKey(i);
1558
+ if (!colorToIndex.has(key)) {
1543
1559
  if (colorToIndex.size >= MAX_PALETTE_ENTRIES) return;
1544
- index = colorToIndex.size;
1545
- colorToIndex.set(key, index);
1546
- paletteRgb.push(r, g, b);
1547
- paletteAlpha.push(a);
1560
+ colorToIndex.set(key, colorToIndex.size);
1561
+ paletteRgb.push(key & BYTE_MASK, key >>> GREEN_SHIFT & BYTE_MASK, key >>> BLUE_SHIFT & BYTE_MASK);
1562
+ paletteAlpha.push(key >>> ALPHA_SHIFT);
1548
1563
  }
1549
- indices[i] = index;
1550
1564
  }
1565
+ const indices = new Uint8Array(pixelCount);
1566
+ indices.forEach((_index, i) => {
1567
+ indices[i] = colorToIndex.get(colorKey(i));
1568
+ });
1551
1569
  const palette = Uint8Array.from(paletteRgb);
1552
1570
  if (alpha === void 0) return {
1553
1571
  indices,
@@ -1578,30 +1596,32 @@ function writeTruecolorPng(writer, image, options) {
1578
1596
  const { width, height, channels, data, alpha } = image;
1579
1597
  const outChannels = alpha === void 0 ? channels : channels + 1;
1580
1598
  const bytesPerRow = width * outChannels;
1581
- const pixelCount = width * height;
1582
- const interleaved = new Uint8Array(pixelCount * outChannels);
1583
- interleaved.forEach((_byte, index) => {
1584
- const pixel = Math.floor(index / outChannels);
1585
- const channel = index % outChannels;
1586
- interleaved[index] = alpha !== void 0 && channel === channels ? alpha[pixel] : data[pixel * channels + channel];
1587
- });
1588
1599
  writeIhdr(writer, width, height, colorTypeFor(image));
1589
- writeChunk(writer, "IDAT", deflate(filterScanlines(interleaved, height, bytesPerRow, outChannels, options.filter ?? "adaptive")));
1600
+ writeChunk(writer, "IDAT", deflate(filterScanlineRows(alpha === void 0 ? (y, row) => {
1601
+ const samples = data.subarray(y * bytesPerRow, (y + 1) * bytesPerRow);
1602
+ row.set(samples);
1603
+ row.fill(0, samples.length);
1604
+ } : (y, row) => {
1605
+ const firstPixel = y * width;
1606
+ row.forEach((_byte, index) => {
1607
+ const pixel = firstPixel + Math.floor(index / outChannels);
1608
+ const channel = index % outChannels;
1609
+ row[index] = (channel === channels ? alpha[pixel] : data[pixel * channels + channel]) ?? 0;
1610
+ });
1611
+ }, height, bytesPerRow, outChannels, options.filter ?? "adaptive")));
1590
1612
  }
1591
1613
  function encodePng(image, options = {}) {
1592
1614
  if (!Number.isInteger(image.width) || image.width <= 0 || image.width > 2147483647 || !Number.isInteger(image.height) || image.height <= 0 || image.height > 2147483647) throw new Error(`cannot encode a PNG with an invalid dimension (width=${image.width}, height=${image.height}); the PNG spec's IHDR section requires both width and height to be positive integers no greater than ${PNG_MAX_DIMENSION}`);
1593
1615
  const pixelCount = image.width * image.height;
1594
1616
  if (exceedsMaxPixelCount(pixelCount)) throw new Error(`cannot encode a PNG with ${pixelCount} pixels (width=${image.width}, height=${image.height}); each dimension is individually within the PNG spec's own limit, but this encoder bounds their product to ${PNG_MAX_PIXELS} to avoid an unbounded per-pixel scan and allocation`);
1595
- const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
1596
- if (paletteEncoding === void 0) return buildPng((writer) => {
1617
+ const truecolor = buildPng((writer) => {
1597
1618
  writeTruecolorPng(writer, image, options);
1598
1619
  });
1620
+ const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
1621
+ if (paletteEncoding === void 0) return truecolor;
1599
1622
  const indexed = buildPng((writer) => {
1600
1623
  writeIndexedPng(writer, image.width, image.height, paletteEncoding, options);
1601
1624
  });
1602
- const truecolor = buildPng((writer) => {
1603
- writeTruecolorPng(writer, image, options);
1604
- });
1605
1625
  return indexed.length <= truecolor.length ? indexed : truecolor;
1606
1626
  }
1607
1627
  //#endregion
@@ -1900,6 +1920,7 @@ exports.deflate = deflate;
1900
1920
  exports.detectByteOrderMark = detectByteOrderMark;
1901
1921
  exports.encodePng = encodePng;
1902
1922
  exports.exceedsMaxPixelCount = exceedsMaxPixelCount;
1923
+ exports.filterScanlineRows = filterScanlineRows;
1903
1924
  exports.filterScanlines = filterScanlines;
1904
1925
  exports.fromCodeUnits = fromCodeUnits;
1905
1926
  exports.inflate = inflate;
package/dist/index.d.cts CHANGED
@@ -228,6 +228,16 @@ declare function encodePng(image: RawImage, options?: PngEncodeOptions): Uint8Ar
228
228
  type PngFilterType = 0 | 1 | 2 | 3 | 4;
229
229
  declare function unfilterScanlines(data: Uint8Array<ArrayBuffer>, height: number, bytesPerRow: number, bpp: number): Uint8Array<ArrayBuffer>;
230
230
  declare function filterScanlines(raw: Uint8Array<ArrayBuffer>, height: number, bytesPerRow: number, bpp: number, strategy?: "none" | "adaptive"): Uint8Array<ArrayBuffer>;
231
+ /**
232
+ * Filters pixel rows into PNG's per-scanline IDAT payload shape, as `filterScanlines` does, reading each row from a callback rather than from one buffer holding the whole image: a caller whose pixels are not already laid out as PNG rows (separate colour and alpha planes, say) writes each row as it is filtered instead of building the whole interleaved image first.
233
+ * @param readRow - Writes row `y`'s unfiltered bytes into `row` (exactly `bytesPerRow` long, holding whatever an earlier row left there: a byte the callback leaves unwritten keeps that value, which is how `filterScanlines` treats a `raw` shorter than `height` rows, so a caller wanting each row to stand alone writes every byte). Called once per row, in order.
234
+ * @param height - Rows.
235
+ * @param bytesPerRow - Unfiltered bytes per row.
236
+ * @param bpp - Bytes per complete pixel, at least 1: the distance the Sub, Average and Paeth filters look back.
237
+ * @param strategy - As for `filterScanlines`.
238
+ * @returns The filtered rows, each prefixed by its filter-type byte.
239
+ */
240
+ declare function filterScanlineRows(readRow: (y: number, row: Uint8Array<ArrayBuffer>) => void, height: number, bytesPerRow: number, bpp: number, strategy?: "none" | "adaptive"): Uint8Array<ArrayBuffer>;
231
241
  //#endregion
232
242
  //#region src/image/jpeg-info.d.ts
233
243
  interface JpegInfo {
@@ -240,4 +250,4 @@ interface JpegInfo {
240
250
  }
241
251
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
242
252
  //#endregion
243
- export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, CodeUnitSink, 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, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, fromCodeUnits, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
253
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, CodeUnitSink, 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, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlineRows, filterScanlines, fromCodeUnits, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
package/dist/index.d.ts CHANGED
@@ -228,6 +228,16 @@ declare function encodePng(image: RawImage, options?: PngEncodeOptions): Uint8Ar
228
228
  type PngFilterType = 0 | 1 | 2 | 3 | 4;
229
229
  declare function unfilterScanlines(data: Uint8Array<ArrayBuffer>, height: number, bytesPerRow: number, bpp: number): Uint8Array<ArrayBuffer>;
230
230
  declare function filterScanlines(raw: Uint8Array<ArrayBuffer>, height: number, bytesPerRow: number, bpp: number, strategy?: "none" | "adaptive"): Uint8Array<ArrayBuffer>;
231
+ /**
232
+ * Filters pixel rows into PNG's per-scanline IDAT payload shape, as `filterScanlines` does, reading each row from a callback rather than from one buffer holding the whole image: a caller whose pixels are not already laid out as PNG rows (separate colour and alpha planes, say) writes each row as it is filtered instead of building the whole interleaved image first.
233
+ * @param readRow - Writes row `y`'s unfiltered bytes into `row` (exactly `bytesPerRow` long, holding whatever an earlier row left there: a byte the callback leaves unwritten keeps that value, which is how `filterScanlines` treats a `raw` shorter than `height` rows, so a caller wanting each row to stand alone writes every byte). Called once per row, in order.
234
+ * @param height - Rows.
235
+ * @param bytesPerRow - Unfiltered bytes per row.
236
+ * @param bpp - Bytes per complete pixel, at least 1: the distance the Sub, Average and Paeth filters look back.
237
+ * @param strategy - As for `filterScanlines`.
238
+ * @returns The filtered rows, each prefixed by its filter-type byte.
239
+ */
240
+ declare function filterScanlineRows(readRow: (y: number, row: Uint8Array<ArrayBuffer>) => void, height: number, bytesPerRow: number, bpp: number, strategy?: "none" | "adaptive"): Uint8Array<ArrayBuffer>;
231
241
  //#endregion
232
242
  //#region src/image/jpeg-info.d.ts
233
243
  interface JpegInfo {
@@ -240,4 +250,4 @@ interface JpegInfo {
240
250
  }
241
251
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
242
252
  //#endregion
243
- export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, CodeUnitSink, 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, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, fromCodeUnits, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
253
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteOrderMark, ByteReader, ByteWriter, CodeUnitSink, 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, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlineRows, filterScanlines, fromCodeUnits, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
package/dist/index.js CHANGED
@@ -172,7 +172,7 @@ function base64ToBytes(base64) {
172
172
  const CRC32_POLYNOMIAL = 3988292384;
173
173
  const BYTE_VALUES = 256;
174
174
  const BITS_PER_BYTE$2 = 8;
175
- const BYTE_MASK$1 = 255;
175
+ const BYTE_MASK$2 = 255;
176
176
  const CRC32_ALL_ONES = 4294967295;
177
177
  const CRC32_TABLE = (() => {
178
178
  const table = new Uint32Array(BYTE_VALUES);
@@ -185,7 +185,7 @@ const CRC32_TABLE = (() => {
185
185
  })();
186
186
  function crc32(bytes) {
187
187
  let crc = CRC32_ALL_ONES;
188
- for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$1] ^ crc >>> BITS_PER_BYTE$2;
188
+ for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & BYTE_MASK$2] ^ crc >>> BITS_PER_BYTE$2;
189
189
  return (crc ^ CRC32_ALL_ONES) >>> 0;
190
190
  }
191
191
  const MAX_INFLATE_OUTPUT_BYTES = 536870912;
@@ -1343,7 +1343,7 @@ const PNG_FILTER_SUB = 1;
1343
1343
  const PNG_FILTER_UP = 2;
1344
1344
  const PNG_FILTER_AVERAGE = 3;
1345
1345
  const PNG_FILTER_PAETH = 4;
1346
- const BYTE_MASK = 255;
1346
+ const BYTE_MASK$1 = 255;
1347
1347
  const BYTE_MODULUS = 256;
1348
1348
  function paethPredictor(a, b, c) {
1349
1349
  const p = a + b - c;
@@ -1380,7 +1380,7 @@ function unfilterScanlines(data, height, bytesPerRow, bpp) {
1380
1380
  const a = x >= bpp ? out[outRowStart + x - bpp] : 0;
1381
1381
  const b = prevOutRowStart === void 0 ? 0 : out[prevOutRowStart + x];
1382
1382
  const c = x >= bpp && prevOutRowStart !== void 0 ? out[prevOutRowStart + x - bpp] : 0;
1383
- out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK;
1383
+ out[outRowStart + x] = raw + predictorValue(filterByte, a, b, c) & BYTE_MASK$1;
1384
1384
  });
1385
1385
  }
1386
1386
  return out;
@@ -1390,28 +1390,28 @@ function filterRowInto(current, previous, bpp, filterType, target) {
1390
1390
  switch (filterType) {
1391
1391
  case PNG_FILTER_SUB:
1392
1392
  target.forEach((_byte, x) => {
1393
- const filtered = current[x + bpp] - current[x] & BYTE_MASK;
1393
+ const filtered = current[x + bpp] - current[x] & BYTE_MASK$1;
1394
1394
  target[x] = filtered;
1395
1395
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1396
1396
  });
1397
1397
  break;
1398
1398
  case PNG_FILTER_UP:
1399
1399
  target.forEach((_byte, x) => {
1400
- const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK;
1400
+ const filtered = current[x + bpp] - previous[x + bpp] & BYTE_MASK$1;
1401
1401
  target[x] = filtered;
1402
1402
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1403
1403
  });
1404
1404
  break;
1405
1405
  case PNG_FILTER_AVERAGE:
1406
1406
  target.forEach((_byte, x) => {
1407
- const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK;
1407
+ const filtered = current[x + bpp] - Math.floor((current[x] + previous[x + bpp]) / 2) & BYTE_MASK$1;
1408
1408
  target[x] = filtered;
1409
1409
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1410
1410
  });
1411
1411
  break;
1412
1412
  case PNG_FILTER_PAETH:
1413
1413
  target.forEach((_byte, x) => {
1414
- const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK;
1414
+ const filtered = current[x + bpp] - paethPredictor(current[x], previous[x + bpp], previous[x]) & BYTE_MASK$1;
1415
1415
  target[x] = filtered;
1416
1416
  sum += Math.min(filtered, BYTE_MODULUS - filtered);
1417
1417
  });
@@ -1432,6 +1432,20 @@ const ALL_FILTER_TYPES = [
1432
1432
  PNG_FILTER_PAETH
1433
1433
  ];
1434
1434
  function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1435
+ return filterScanlineRows((y, row) => {
1436
+ row.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow));
1437
+ }, height, bytesPerRow, bpp, strategy);
1438
+ }
1439
+ /**
1440
+ * Filters pixel rows into PNG's per-scanline IDAT payload shape, as `filterScanlines` does, reading each row from a callback rather than from one buffer holding the whole image: a caller whose pixels are not already laid out as PNG rows (separate colour and alpha planes, say) writes each row as it is filtered instead of building the whole interleaved image first.
1441
+ * @param readRow - Writes row `y`'s unfiltered bytes into `row` (exactly `bytesPerRow` long, holding whatever an earlier row left there: a byte the callback leaves unwritten keeps that value, which is how `filterScanlines` treats a `raw` shorter than `height` rows, so a caller wanting each row to stand alone writes every byte). Called once per row, in order.
1442
+ * @param height - Rows.
1443
+ * @param bytesPerRow - Unfiltered bytes per row.
1444
+ * @param bpp - Bytes per complete pixel, at least 1: the distance the Sub, Average and Paeth filters look back.
1445
+ * @param strategy - As for `filterScanlines`.
1446
+ * @returns The filtered rows, each prefixed by its filter-type byte.
1447
+ */
1448
+ function filterScanlineRows(readRow, height, bytesPerRow, bpp, strategy = "adaptive") {
1435
1449
  const stride = bytesPerRow + 1;
1436
1450
  const out = new Uint8Array(height * stride);
1437
1451
  let current = new Uint8Array(bytesPerRow + bpp);
@@ -1440,7 +1454,7 @@ function filterScanlines(raw, height, bytesPerRow, bpp, strategy = "adaptive") {
1440
1454
  let best = new Uint8Array(bytesPerRow);
1441
1455
  const filterTypes = strategy === "none" ? [PNG_FILTER_NONE] : ALL_FILTER_TYPES;
1442
1456
  Array.from({ length: height }).forEach((_row, y) => {
1443
- current.set(raw.subarray(y * bytesPerRow, (y + 1) * bytesPerRow), bpp);
1457
+ readRow(y, current.subarray(bpp));
1444
1458
  let bestType = PNG_FILTER_NONE;
1445
1459
  let bestSum = Number.POSITIVE_INFINITY;
1446
1460
  for (const filterType of filterTypes) {
@@ -1490,6 +1504,7 @@ const OPAQUE_ALPHA$1 = 255;
1490
1504
  const GREEN_SHIFT = 8;
1491
1505
  const BLUE_SHIFT = 16;
1492
1506
  const ALPHA_SHIFT = 24;
1507
+ const BYTE_MASK = 255;
1493
1508
  const PNG_MAX_DIMENSION = 2147483647;
1494
1509
  const PNG_MAX_PIXELS = 1e8;
1495
1510
  function exceedsMaxPixelCount(pixelCount) {
@@ -1527,26 +1542,29 @@ function detectPalette(image) {
1527
1542
  const { width, height, data, alpha } = image;
1528
1543
  const pixelCount = width * height;
1529
1544
  const colorToIndex = /* @__PURE__ */ new Map();
1530
- const indices = new Uint8Array(pixelCount);
1531
1545
  const paletteRgb = [];
1532
1546
  const paletteAlpha = [];
1533
- for (let i = 0; i < pixelCount; i++) {
1547
+ const colorKey = (i) => {
1534
1548
  const base = i * RGB_CHANNELS$1;
1535
1549
  const r = data[base] ?? 0;
1536
1550
  const g = data[base + 1] ?? 0;
1537
1551
  const b = data[base + 2] ?? 0;
1538
1552
  const a = alpha === void 0 ? OPAQUE_ALPHA$1 : alpha[i] ?? 0;
1539
- const key = r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
1540
- let index = colorToIndex.get(key);
1541
- if (index === void 0) {
1553
+ return r | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;
1554
+ };
1555
+ for (let i = 0; i < pixelCount; i++) {
1556
+ const key = colorKey(i);
1557
+ if (!colorToIndex.has(key)) {
1542
1558
  if (colorToIndex.size >= MAX_PALETTE_ENTRIES) return;
1543
- index = colorToIndex.size;
1544
- colorToIndex.set(key, index);
1545
- paletteRgb.push(r, g, b);
1546
- paletteAlpha.push(a);
1559
+ colorToIndex.set(key, colorToIndex.size);
1560
+ paletteRgb.push(key & BYTE_MASK, key >>> GREEN_SHIFT & BYTE_MASK, key >>> BLUE_SHIFT & BYTE_MASK);
1561
+ paletteAlpha.push(key >>> ALPHA_SHIFT);
1547
1562
  }
1548
- indices[i] = index;
1549
1563
  }
1564
+ const indices = new Uint8Array(pixelCount);
1565
+ indices.forEach((_index, i) => {
1566
+ indices[i] = colorToIndex.get(colorKey(i));
1567
+ });
1550
1568
  const palette = Uint8Array.from(paletteRgb);
1551
1569
  if (alpha === void 0) return {
1552
1570
  indices,
@@ -1577,30 +1595,32 @@ function writeTruecolorPng(writer, image, options) {
1577
1595
  const { width, height, channels, data, alpha } = image;
1578
1596
  const outChannels = alpha === void 0 ? channels : channels + 1;
1579
1597
  const bytesPerRow = width * outChannels;
1580
- const pixelCount = width * height;
1581
- const interleaved = new Uint8Array(pixelCount * outChannels);
1582
- interleaved.forEach((_byte, index) => {
1583
- const pixel = Math.floor(index / outChannels);
1584
- const channel = index % outChannels;
1585
- interleaved[index] = alpha !== void 0 && channel === channels ? alpha[pixel] : data[pixel * channels + channel];
1586
- });
1587
1598
  writeIhdr(writer, width, height, colorTypeFor(image));
1588
- writeChunk(writer, "IDAT", deflate(filterScanlines(interleaved, height, bytesPerRow, outChannels, options.filter ?? "adaptive")));
1599
+ writeChunk(writer, "IDAT", deflate(filterScanlineRows(alpha === void 0 ? (y, row) => {
1600
+ const samples = data.subarray(y * bytesPerRow, (y + 1) * bytesPerRow);
1601
+ row.set(samples);
1602
+ row.fill(0, samples.length);
1603
+ } : (y, row) => {
1604
+ const firstPixel = y * width;
1605
+ row.forEach((_byte, index) => {
1606
+ const pixel = firstPixel + Math.floor(index / outChannels);
1607
+ const channel = index % outChannels;
1608
+ row[index] = (channel === channels ? alpha[pixel] : data[pixel * channels + channel]) ?? 0;
1609
+ });
1610
+ }, height, bytesPerRow, outChannels, options.filter ?? "adaptive")));
1589
1611
  }
1590
1612
  function encodePng(image, options = {}) {
1591
1613
  if (!Number.isInteger(image.width) || image.width <= 0 || image.width > 2147483647 || !Number.isInteger(image.height) || image.height <= 0 || image.height > 2147483647) throw new Error(`cannot encode a PNG with an invalid dimension (width=${image.width}, height=${image.height}); the PNG spec's IHDR section requires both width and height to be positive integers no greater than ${PNG_MAX_DIMENSION}`);
1592
1614
  const pixelCount = image.width * image.height;
1593
1615
  if (exceedsMaxPixelCount(pixelCount)) throw new Error(`cannot encode a PNG with ${pixelCount} pixels (width=${image.width}, height=${image.height}); each dimension is individually within the PNG spec's own limit, but this encoder bounds their product to ${PNG_MAX_PIXELS} to avoid an unbounded per-pixel scan and allocation`);
1594
- const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
1595
- if (paletteEncoding === void 0) return buildPng((writer) => {
1616
+ const truecolor = buildPng((writer) => {
1596
1617
  writeTruecolorPng(writer, image, options);
1597
1618
  });
1619
+ const paletteEncoding = image.channels === RGB_CHANNELS$1 ? detectPalette(image) : void 0;
1620
+ if (paletteEncoding === void 0) return truecolor;
1598
1621
  const indexed = buildPng((writer) => {
1599
1622
  writeIndexedPng(writer, image.width, image.height, paletteEncoding, options);
1600
1623
  });
1601
- const truecolor = buildPng((writer) => {
1602
- writeTruecolorPng(writer, image, options);
1603
- });
1604
1624
  return indexed.length <= truecolor.length ? indexed : truecolor;
1605
1625
  }
1606
1626
  //#endregion
@@ -1880,4 +1900,4 @@ function readJpegInfo(bytes) {
1880
1900
  throw new Error("no SOF marker found in JPEG file");
1881
1901
  }
1882
1902
  //#endregion
1883
- export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, TEXT_DECODE_CHUNK_CODE_UNITS, UndecodableTextError, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlines, fromCodeUnits, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, resolveEncodingLabel, tryDecodeText, unfilterScanlines };
1903
+ export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, TEXT_DECODE_CHUNK_CODE_UNITS, UndecodableTextError, appendCodePoint, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, detectByteOrderMark, encodePng, exceedsMaxPixelCount, filterScanlineRows, filterScanlines, fromCodeUnits, 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": "2.0.2",
3
+ "version": "2.1.0",
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": {