agglomerative-clustering 3.4.2 → 3.5.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
@@ -36,7 +36,7 @@ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome
36
36
  import sharp from 'sharp';
37
37
  import { buildPalette, quantize } from 'agglomerative-clustering';
38
38
 
39
- const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
39
+ const { data, info } = await sharp('photo.jpg').rotate().ensureAlpha().raw().toBuffer({ resolveWithObject: true });
40
40
  const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
41
41
 
42
42
  const palette = await buildPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
@@ -67,6 +67,8 @@ shares.forEach((share, i) => {
67
67
  });
68
68
  ```
69
69
 
70
+ Entries keep their place as `k` grows (split order), so palettes nest. For hex strings, the largest share first or a dominant colour, see [Heaviest first](docs/guides.md#heaviest-first).
71
+
70
72
  **A colour-count slider:** cluster once, then cut and map as often as you like.
71
73
 
72
74
  ```js
@@ -80,7 +82,7 @@ slider.oninput = async () => {
80
82
  };
81
83
  ```
82
84
 
83
- Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
85
+ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
84
86
 
85
87
  ## How it works
86
88
 
Binary file
package/dist/index.cjs CHANGED
@@ -470,70 +470,6 @@ const unpack = (wasm, pointer) => {
470
470
  // A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
471
471
  const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
472
472
 
473
- // ----- Encoded image files -------------------------------------------------------------------------------------------
474
- // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
475
- // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
476
- // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
477
- // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
478
- // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
479
- //
480
- // This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
481
- // sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
482
- // { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
483
- const ascii = (bytes, at, text) => {
484
- for (let i = 0; i < text.length; i++) {
485
- if (bytes[at + i] !== text.charCodeAt(i)) {
486
- return false;
487
- }
488
- }
489
- return true;
490
- };
491
-
492
- // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
493
- // beyond the first few bytes, that raw pixels all but never match.
494
- const sniffImageFormat = bytes => {
495
- const length = bytes.length;
496
- if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
497
- return 'PNG';
498
- }
499
- // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
500
- if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
501
- return 'JPEG';
502
- }
503
- if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
504
- return 'GIF';
505
- }
506
- if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
507
- return 'WebP';
508
- }
509
- // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
510
- if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
511
- return 'BMP';
512
- }
513
- // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
514
- if (length >= 12) {
515
- const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
516
- const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
517
- if (little || big) {
518
- const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
519
- const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
520
- if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
521
- return 'TIFF';
522
- }
523
- }
524
- }
525
- // ISO base media: a 'ftyp' box, then a brand
526
- if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
527
- if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
528
- return 'AVIF';
529
- }
530
- if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
531
- return 'HEIC';
532
- }
533
- }
534
- return null;
535
- };
536
-
537
473
  // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
538
474
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
539
475
  // call returns; until then (the first call) a copy is kept for when it has loaded.
@@ -552,6 +488,19 @@ const checkSize = (pixels, size, name, argument) => {
552
488
  throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
553
489
  }
554
490
  };
491
+
492
+ // The rgb-as-rgba warning for an image, decided before load() and given only once the call's own checks have passed,
493
+ // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
494
+ const noWarning = () => {};
495
+ // A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
496
+ const warningFor = image => {
497
+ const code = (0, _shared.bareRgbWarning)(image);
498
+ return code ? signal => {
499
+ if (!(signal && signal.aborted)) {
500
+ (0, _shared.warnOnce)(code, image.byteLength);
501
+ }
502
+ } : noWarning;
503
+ };
555
504
  const load = image => {
556
505
  if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
557
506
  const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
@@ -562,9 +511,9 @@ const load = image => {
562
511
  throw (0, _shared.detachedError)('bare');
563
512
  }
564
513
  if ((0, _shared.isUint8Array)(image)) {
565
- const encoded = sniffImageFormat(image);
514
+ const encoded = (0, _shared.sniffImageFormat)(image);
566
515
  if (encoded) {
567
- throw (0, _shared.fail)('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
516
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
568
517
  }
569
518
  if (image.length % 4 !== 0) {
570
519
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
@@ -978,8 +927,10 @@ const noOptions = (name, extra) => {
978
927
  // happens before the call returns.
979
928
 
980
929
  const buildClustering = async (image, options) => {
930
+ const warn = warningFor(image);
981
931
  image = load(image);
982
932
  const o = parseOptions(options, clusterOptions, image);
933
+ warn(o.signal);
983
934
  const wasm = Module || (await acquire());
984
935
  if (isControlled(o)) {
985
936
  const report = reporter(o);
@@ -993,9 +944,11 @@ const buildClustering = async (image, options) => {
993
944
  exports.buildClustering = buildClustering;
994
945
  const getClustering = exports.getClustering = buildClustering;
995
946
  const buildPalette = async (image, k, options) => {
947
+ const warn = warningFor(image);
996
948
  image = load(image);
997
949
  k = check(k);
998
950
  const o = parseOptions(options, clusterOptions, image);
951
+ warn(o.signal);
999
952
  const wasm = Module || (await acquire());
1000
953
  if (isControlled(o)) {
1001
954
  const report = reporter(o);
@@ -1131,10 +1084,12 @@ const readInfo = async (name, clustering, extra) => {
1131
1084
  const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1132
1085
  exports.getClusteringInfo = getClusteringInfo;
1133
1086
  const quantize = async (image, k, options) => {
1087
+ const warn = warningFor(image);
1134
1088
  const wrap = getWrapper(image);
1135
1089
  image = load(image);
1136
1090
  k = check(k);
1137
1091
  const o = parseOptions(options, quantizeOptions, image);
1092
+ warn(o.signal);
1138
1093
  const wasm = Module || (await acquire());
1139
1094
  if (isControlled(o)) {
1140
1095
  const report = reporter(o);
@@ -1148,12 +1103,14 @@ const quantize = async (image, k, options) => {
1148
1103
  };
1149
1104
  exports.quantize = quantize;
1150
1105
  const quantizeFromClustering = async (image, clustering, k, options) => {
1106
+ const warn = warningFor(image);
1151
1107
  const wrap = getWrapper(image);
1152
1108
  image = load(image);
1153
1109
  (0, _shared.readHeader)(clustering);
1154
1110
  k = check(k);
1155
1111
  const o = parseOptions(options, mapOptions, image);
1156
1112
  clustering = held(clustering);
1113
+ warn(o.signal);
1157
1114
  const wasm = Module || (await acquire());
1158
1115
  checkAborted(o.signal);
1159
1116
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1162,6 +1119,7 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1162
1119
  };
1163
1120
  exports.quantizeFromClustering = quantizeFromClustering;
1164
1121
  const quantizeWithPalette = async (image, palette, options) => {
1122
+ const warn = warningFor(image);
1165
1123
  const wrap = getWrapper(image);
1166
1124
  image = load(image);
1167
1125
  (0, _shared.checkPalette)(palette);
@@ -1169,6 +1127,7 @@ const quantizeWithPalette = async (image, palette, options) => {
1169
1127
  checkNotEmpty(palette, image, 1);
1170
1128
  const space = matchingSpace(o, palette);
1171
1129
  palette = held(palette);
1130
+ warn(o.signal);
1172
1131
  const wasm = Module || (await acquire());
1173
1132
  checkAborted(o.signal);
1174
1133
  const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
@@ -1176,10 +1135,12 @@ const quantizeWithPalette = async (image, palette, options) => {
1176
1135
  };
1177
1136
  exports.quantizeWithPalette = quantizeWithPalette;
1178
1137
  const quantizeToIndices = async (image, k, options) => {
1138
+ const warn = warningFor(image);
1179
1139
  const original = image;
1180
1140
  image = load(image);
1181
1141
  k = check(k);
1182
1142
  const o = parseOptions(options, quantizeIndexOptions, image);
1143
+ warn(o.signal);
1183
1144
  const wasm = Module || (await acquire());
1184
1145
  if (isControlled(o)) {
1185
1146
  const report = reporter(o);
@@ -1193,12 +1154,14 @@ const quantizeToIndices = async (image, k, options) => {
1193
1154
  };
1194
1155
  exports.quantizeToIndices = quantizeToIndices;
1195
1156
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1157
+ const warn = warningFor(image);
1196
1158
  const original = image;
1197
1159
  image = load(image);
1198
1160
  const header = (0, _shared.readHeader)(clustering);
1199
1161
  k = check(k);
1200
1162
  const o = parseOptions(options, mapIndexOptions, image);
1201
1163
  clustering = held(clustering);
1164
+ warn(o.signal);
1202
1165
  const wasm = Module || (await acquire());
1203
1166
  checkAborted(o.signal);
1204
1167
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1210,6 +1173,7 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1210
1173
  };
1211
1174
  exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
1212
1175
  const quantizeToIndicesWithPalette = async (image, palette, options) => {
1176
+ const warn = warningFor(image);
1213
1177
  const original = image;
1214
1178
  image = load(image);
1215
1179
  (0, _shared.checkPalette)(palette);
@@ -1218,6 +1182,7 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1218
1182
  const space = matchingSpace(o, palette);
1219
1183
  const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
1220
1184
  palette = held(palette);
1185
+ warn(o.signal);
1221
1186
  const wasm = Module || (await acquire());
1222
1187
  checkAborted(o.signal);
1223
1188
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
2
+ import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge, sniffImageFormat, bareRgbWarning, warnOnce } from "./shared.mjs";
3
3
 
4
4
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
5
5
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -394,70 +394,6 @@ const unpack = (wasm, pointer) => {
394
394
  // A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
395
395
  const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
396
396
 
397
- // ----- Encoded image files -------------------------------------------------------------------------------------------
398
- // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
399
- // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
400
- // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
401
- // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
402
- // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
403
- //
404
- // This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
405
- // sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
406
- // { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
407
- const ascii = (bytes, at, text) => {
408
- for (let i = 0; i < text.length; i++) {
409
- if (bytes[at + i] !== text.charCodeAt(i)) {
410
- return false;
411
- }
412
- }
413
- return true;
414
- };
415
-
416
- // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
417
- // beyond the first few bytes, that raw pixels all but never match.
418
- const sniffImageFormat = bytes => {
419
- const length = bytes.length;
420
- if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
421
- return 'PNG';
422
- }
423
- // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
424
- if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
425
- return 'JPEG';
426
- }
427
- if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
428
- return 'GIF';
429
- }
430
- if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
431
- return 'WebP';
432
- }
433
- // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
434
- if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
435
- return 'BMP';
436
- }
437
- // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
438
- if (length >= 12) {
439
- const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
440
- const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
441
- if (little || big) {
442
- const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
443
- const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
444
- if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
445
- return 'TIFF';
446
- }
447
- }
448
- }
449
- // ISO base media: a 'ftyp' box, then a brand
450
- if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
451
- if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
452
- return 'AVIF';
453
- }
454
- if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
455
- return 'HEIC';
456
- }
457
- }
458
- return null;
459
- };
460
-
461
397
  // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
462
398
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
463
399
  // call returns; until then (the first call) a copy is kept for when it has loaded.
@@ -476,6 +412,19 @@ const checkSize = (pixels, size, name, argument) => {
476
412
  throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
477
413
  }
478
414
  };
415
+
416
+ // The rgb-as-rgba warning for an image, decided before load() and given only once the call's own checks have passed,
417
+ // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
418
+ const noWarning = () => {};
419
+ // A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
420
+ const warningFor = image => {
421
+ const code = bareRgbWarning(image);
422
+ return code ? signal => {
423
+ if (!(signal && signal.aborted)) {
424
+ warnOnce(code, image.byteLength);
425
+ }
426
+ } : noWarning;
427
+ };
479
428
  const load = image => {
480
429
  if (isClustering(image) || isPalette(image)) {
481
430
  const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
@@ -488,7 +437,7 @@ const load = image => {
488
437
  if (isUint8Array(image)) {
489
438
  const encoded = sniffImageFormat(image);
490
439
  if (encoded) {
491
- throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
440
+ throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
492
441
  }
493
442
  if (image.length % 4 !== 0) {
494
443
  throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
@@ -902,8 +851,10 @@ const noOptions = (name, extra) => {
902
851
  // happens before the call returns.
903
852
 
904
853
  export const buildClustering = async (image, options) => {
854
+ const warn = warningFor(image);
905
855
  image = load(image);
906
856
  const o = parseOptions(options, clusterOptions, image);
857
+ warn(o.signal);
907
858
  const wasm = Module || (await acquire());
908
859
  if (isControlled(o)) {
909
860
  const report = reporter(o);
@@ -916,9 +867,11 @@ export const buildClustering = async (image, options) => {
916
867
  /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
917
868
  export const getClustering = buildClustering;
918
869
  export const buildPalette = async (image, k, options) => {
870
+ const warn = warningFor(image);
919
871
  image = load(image);
920
872
  k = check(k);
921
873
  const o = parseOptions(options, clusterOptions, image);
874
+ warn(o.signal);
922
875
  const wasm = Module || (await acquire());
923
876
  if (isControlled(o)) {
924
877
  const report = reporter(o);
@@ -1049,10 +1002,12 @@ const readInfo = async (name, clustering, extra) => {
1049
1002
  };
1050
1003
  export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1051
1004
  export const quantize = async (image, k, options) => {
1005
+ const warn = warningFor(image);
1052
1006
  const wrap = getWrapper(image);
1053
1007
  image = load(image);
1054
1008
  k = check(k);
1055
1009
  const o = parseOptions(options, quantizeOptions, image);
1010
+ warn(o.signal);
1056
1011
  const wasm = Module || (await acquire());
1057
1012
  if (isControlled(o)) {
1058
1013
  const report = reporter(o);
@@ -1065,12 +1020,14 @@ export const quantize = async (image, k, options) => {
1065
1020
  return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
1066
1021
  };
1067
1022
  export const quantizeFromClustering = async (image, clustering, k, options) => {
1023
+ const warn = warningFor(image);
1068
1024
  const wrap = getWrapper(image);
1069
1025
  image = load(image);
1070
1026
  readHeader(clustering);
1071
1027
  k = check(k);
1072
1028
  const o = parseOptions(options, mapOptions, image);
1073
1029
  clustering = held(clustering);
1030
+ warn(o.signal);
1074
1031
  const wasm = Module || (await acquire());
1075
1032
  checkAborted(o.signal);
1076
1033
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1078,6 +1035,7 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
1078
1035
  return result;
1079
1036
  };
1080
1037
  export const quantizeWithPalette = async (image, palette, options) => {
1038
+ const warn = warningFor(image);
1081
1039
  const wrap = getWrapper(image);
1082
1040
  image = load(image);
1083
1041
  checkPalette(palette);
@@ -1085,16 +1043,19 @@ export const quantizeWithPalette = async (image, palette, options) => {
1085
1043
  checkNotEmpty(palette, image, 1);
1086
1044
  const space = matchingSpace(o, palette);
1087
1045
  palette = held(palette);
1046
+ warn(o.signal);
1088
1047
  const wasm = Module || (await acquire());
1089
1048
  checkAborted(o.signal);
1090
1049
  const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1091
1050
  return result;
1092
1051
  };
1093
1052
  export const quantizeToIndices = async (image, k, options) => {
1053
+ const warn = warningFor(image);
1094
1054
  const original = image;
1095
1055
  image = load(image);
1096
1056
  k = check(k);
1097
1057
  const o = parseOptions(options, quantizeIndexOptions, image);
1058
+ warn(o.signal);
1098
1059
  const wasm = Module || (await acquire());
1099
1060
  if (isControlled(o)) {
1100
1061
  const report = reporter(o);
@@ -1107,12 +1068,14 @@ export const quantizeToIndices = async (image, k, options) => {
1107
1068
  return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
1108
1069
  };
1109
1070
  export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1071
+ const warn = warningFor(image);
1110
1072
  const original = image;
1111
1073
  image = load(image);
1112
1074
  const header = readHeader(clustering);
1113
1075
  k = check(k);
1114
1076
  const o = parseOptions(options, mapIndexOptions, image);
1115
1077
  clustering = held(clustering);
1078
+ warn(o.signal);
1116
1079
  const wasm = Module || (await acquire());
1117
1080
  checkAborted(o.signal);
1118
1081
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1123,6 +1086,7 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
1123
1086
  return result;
1124
1087
  };
1125
1088
  export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1089
+ const warn = warningFor(image);
1126
1090
  const original = image;
1127
1091
  image = load(image);
1128
1092
  checkPalette(palette);
@@ -1131,6 +1095,7 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1131
1095
  const space = matchingSpace(o, palette);
1132
1096
  const paletteSpace = isPalette(palette) ? palette.colorSpace : colorSpaceName(space);
1133
1097
  palette = held(palette);
1098
+ warn(o.signal);
1134
1099
  const wasm = Module || (await acquire());
1135
1100
  checkAborted(o.signal);
1136
1101
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
9
+ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.bareRgbWarning = exports.alphaModes = void 0;
10
10
  // Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
11
11
  // header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
12
12
  // './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
13
13
 
14
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
15
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
16
- const version = exports.version = '3.4.2';
16
+ const version = exports.version = '3.5.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -306,9 +306,217 @@ const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
306
306
  const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
307
307
  exports.isPalette = isPalette;
308
308
  const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
309
+
310
+ // ----- Encoded image files -------------------------------------------------------------------------------------------
311
+ // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
312
+ // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
313
+ // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
314
+ // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
315
+ // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
316
+ //
317
+ // Decoding is left to the caller: the library has no decoders and no dependency on one (PRINCIPLES "Settled
318
+ // decisions"), and the guides' "Decoding image files" gives a recipe per environment, which the message points to.
319
+ exports.isClustering = isClustering;
320
+ const ascii = (bytes, at, text) => {
321
+ for (let i = 0; i < text.length; i++) {
322
+ if (bytes[at + i] !== text.charCodeAt(i)) {
323
+ return false;
324
+ }
325
+ }
326
+ return true;
327
+ };
328
+
329
+ // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
330
+ // beyond the first few bytes, that raw pixels all but never match.
331
+ const sniffImageFormat = bytes => {
332
+ const length = bytes.length;
333
+ if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
334
+ return 'PNG';
335
+ }
336
+ // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
337
+ if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
338
+ return 'JPEG';
339
+ }
340
+ if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
341
+ return 'GIF';
342
+ }
343
+ if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
344
+ return 'WebP';
345
+ }
346
+ // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
347
+ if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
348
+ return 'BMP';
349
+ }
350
+ // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
351
+ if (length >= 12) {
352
+ const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
353
+ const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
354
+ if (little || big) {
355
+ const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
356
+ const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
357
+ if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
358
+ return 'TIFF';
359
+ }
360
+ }
361
+ }
362
+ // ISO base media: a 'ftyp' box, then a brand
363
+ if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
364
+ if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
365
+ return 'AVIF';
366
+ }
367
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
368
+ return 'HEIC';
369
+ }
370
+ }
371
+ return null;
372
+ };
373
+
374
+ // ----- RGB bytes passed bare ----------------------------------------------------------------------------------------
375
+ // The other common way to get a bare array wrong is RGB bytes (sharp's plain .raw()): read as RGBA, every pixel takes
376
+ // colour bytes from its neighbours and a colour value as its alpha, and nothing fails while the length divides by 4. They
377
+ // are never reinterpreted (a bare array is RGBA, PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
378
+ //
379
+ // The rule (measured in bench/spikes/bare-rgb/: no false positives on 2,103 real RGBA images, 1,833 of 1,884 harmful RGB
380
+ // cases caught): real RGBA changes least between a byte and the one 4 before it, RGB between a byte and the one 3 before.
381
+ // A premultiplied white mask, (a, a, a, a), also scores high, so pixels with four equal bytes overrule it. Grey RGB is
382
+ // too smooth for that score, but where it changes its bytes come in equal triples at a step of 3 and not of 4. Units equal
383
+ // to the one before are skipped by the grey counts, since flat areas read the same either way. It samples 512 windows of
384
+ // 96 bytes (each on a multiple of 12, a pixel under both readings), so it costs about 0.25 ms at any size
385
+ // (about 0.4 ms for an array it flags, which happens once).
386
+ exports.sniffImageFormat = sniffImageFormat;
387
+ const rgbFloor = 192,
388
+ rgbWindow = 96,
389
+ rgbWindows = 512;
390
+ const looksLikeRgb = d => {
391
+ if (d.length < rgbFloor) {
392
+ return false;
393
+ }
394
+ const whole = d.length <= rgbWindow * rgbWindows;
395
+ const windows = whole ? 1 : rgbWindows,
396
+ size = whole ? d.length : rgbWindow;
397
+ const step = whole ? 0 : Math.floor((d.length - rgbWindow) / (rgbWindows - 1) / 12) * 12;
398
+ let e3 = 0,
399
+ e4 = 0,
400
+ n = 0,
401
+ g3 = 0,
402
+ n3 = 0,
403
+ g4 = 0,
404
+ q4 = 0,
405
+ n4 = 0;
406
+ for (let w = 0; w < windows; w++) {
407
+ const start = w * step,
408
+ end = start + size;
409
+ for (let i = start + 4; i < end; i++) {
410
+ const v = d[i],
411
+ a = v - d[i - 3],
412
+ b = v - d[i - 4];
413
+ e3 += a < 0 ? -a : a;
414
+ e4 += b < 0 ? -b : b;
415
+ }
416
+ n += size - 4;
417
+ for (let i = start + 3; i + 2 < end; i += 3) {
418
+ if (d[i] === d[i - 3] && d[i + 1] === d[i - 2] && d[i + 2] === d[i - 1]) {
419
+ continue;
420
+ }
421
+ n3++;
422
+ if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
423
+ g3++;
424
+ }
425
+ }
426
+ for (let i = start + 4; i + 3 < end; i += 4) {
427
+ if (d[i] === d[i - 4] && d[i + 1] === d[i - 3] && d[i + 2] === d[i - 2] && d[i + 3] === d[i - 1]) {
428
+ continue;
429
+ }
430
+ n4++;
431
+ if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
432
+ g4++;
433
+ if (d[i] === d[i + 3]) {
434
+ q4++;
435
+ }
436
+ }
437
+ }
438
+ }
439
+ const score = (e4 / n + 0.05) / (e3 / n + 0.05);
440
+ const flagged = score > 1.25 && q4 < 0.5 * Math.max(1, n4) || g3 > 0.9 * Math.max(1, n3) && g4 < 0.6 * Math.max(1, n4);
441
+ if (!flagged) {
442
+ return false;
443
+ }
444
+ // Bytes that mostly rise by one fixed step ((i * k) & 255, the usual fake image in tests) are pixels of neither kind,
445
+ // and score 4/3 whatever the step. Counted only for arrays about to be flagged, a second pass over the same windows,
446
+ // so RGBA (the usual input) doesn't pay for it.
447
+ let ramp = 0;
448
+ for (let w = 0; w < windows; w++) {
449
+ const start = w * step,
450
+ end = start + size;
451
+ for (let i = start + 4; i < end; i++) {
452
+ const rise = d[i] - d[i - 1] & 255;
453
+ if (rise !== 0 && rise === (d[i - 1] - d[i - 2] & 255)) {
454
+ ramp++;
455
+ }
456
+ }
457
+ }
458
+ return ramp <= 0.5 * n;
459
+ };
460
+
461
+ // Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
462
+ exports.looksLikeRgb = looksLikeRgb;
463
+ const warned = new Set();
464
+
465
+ // The warning a bare image calls for, or null. It skips everything the main entry rejects (palettes and clusterings
466
+ // passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns about its image and
467
+ // rejects it, and both entries share this one order.
468
+ const bareRgbWarning = image => {
469
+ if (warned.has('rgb-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
470
+ return null;
471
+ }
472
+ if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
473
+ return null;
474
+ }
475
+ return looksLikeRgb(image) ? 'rgb-as-rgba' : null;
476
+ };
477
+
478
+ // The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
479
+ // process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
480
+ // emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
481
+ // navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
482
+ // keeps Parcel from adding one.
483
+ exports.bareRgbWarning = bareRgbWarning;
484
+ const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
485
+ const warningText = {
486
+ 'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
487
+ };
488
+ const warnOnce = (code, byteLength) => {
489
+ if (warned.has(code)) {
490
+ return;
491
+ }
492
+ warned.add(code);
493
+ const message = warningText[code](byteLength);
494
+ const runtime = globalThis.process;
495
+ if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
496
+ runtime.emitWarning(message, {
497
+ type: 'AgglomerativeClusteringWarning',
498
+ code
499
+ });
500
+ } else if (typeof console !== 'undefined') {
501
+ console.warn(`agglomerative-clustering [${code}]: ${message}`);
502
+ }
503
+ };
504
+ // The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
505
+ // also skips the sampling.
506
+ exports.warnOnce = warnOnce;
507
+ const silenceWarnings = () => {
508
+ for (const code of Object.keys(warningText)) {
509
+ warned.add(code);
510
+ }
511
+ };
512
+ // For tests.
513
+ exports.silenceWarnings = silenceWarnings;
514
+ const resetWarnings = () => {
515
+ warned.clear();
516
+ };
309
517
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
310
518
  // `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
311
- exports.isClustering = isClustering;
519
+ exports.resetWarnings = resetWarnings;
312
520
  const inspect = Symbol.for('nodejs.util.inspect.custom');
313
521
  const view = label => function (depth, options, nodeInspect) {
314
522
  const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.4.2';
7
+ export const version = '3.5.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -276,6 +276,208 @@ const paletteBrand = Symbol.for('agglomerative-clustering.palette');
276
276
  const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
277
277
  export const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
278
278
  export const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
279
+
280
+ // ----- Encoded image files -------------------------------------------------------------------------------------------
281
+ // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
282
+ // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
283
+ // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
284
+ // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
285
+ // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
286
+ //
287
+ // Decoding is left to the caller: the library has no decoders and no dependency on one (PRINCIPLES "Settled
288
+ // decisions"), and the guides' "Decoding image files" gives a recipe per environment, which the message points to.
289
+ const ascii = (bytes, at, text) => {
290
+ for (let i = 0; i < text.length; i++) {
291
+ if (bytes[at + i] !== text.charCodeAt(i)) {
292
+ return false;
293
+ }
294
+ }
295
+ return true;
296
+ };
297
+
298
+ // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
299
+ // beyond the first few bytes, that raw pixels all but never match.
300
+ export const sniffImageFormat = bytes => {
301
+ const length = bytes.length;
302
+ if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
303
+ return 'PNG';
304
+ }
305
+ // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
306
+ if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
307
+ return 'JPEG';
308
+ }
309
+ if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
310
+ return 'GIF';
311
+ }
312
+ if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
313
+ return 'WebP';
314
+ }
315
+ // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
316
+ if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
317
+ return 'BMP';
318
+ }
319
+ // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
320
+ if (length >= 12) {
321
+ const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
322
+ const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
323
+ if (little || big) {
324
+ const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
325
+ const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
326
+ if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
327
+ return 'TIFF';
328
+ }
329
+ }
330
+ }
331
+ // ISO base media: a 'ftyp' box, then a brand
332
+ if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
333
+ if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
334
+ return 'AVIF';
335
+ }
336
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
337
+ return 'HEIC';
338
+ }
339
+ }
340
+ return null;
341
+ };
342
+
343
+ // ----- RGB bytes passed bare ----------------------------------------------------------------------------------------
344
+ // The other common way to get a bare array wrong is RGB bytes (sharp's plain .raw()): read as RGBA, every pixel takes
345
+ // colour bytes from its neighbours and a colour value as its alpha, and nothing fails while the length divides by 4. They
346
+ // are never reinterpreted (a bare array is RGBA, PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
347
+ //
348
+ // The rule (measured in bench/spikes/bare-rgb/: no false positives on 2,103 real RGBA images, 1,833 of 1,884 harmful RGB
349
+ // cases caught): real RGBA changes least between a byte and the one 4 before it, RGB between a byte and the one 3 before.
350
+ // A premultiplied white mask, (a, a, a, a), also scores high, so pixels with four equal bytes overrule it. Grey RGB is
351
+ // too smooth for that score, but where it changes its bytes come in equal triples at a step of 3 and not of 4. Units equal
352
+ // to the one before are skipped by the grey counts, since flat areas read the same either way. It samples 512 windows of
353
+ // 96 bytes (each on a multiple of 12, a pixel under both readings), so it costs about 0.25 ms at any size
354
+ // (about 0.4 ms for an array it flags, which happens once).
355
+ const rgbFloor = 192,
356
+ rgbWindow = 96,
357
+ rgbWindows = 512;
358
+ export const looksLikeRgb = d => {
359
+ if (d.length < rgbFloor) {
360
+ return false;
361
+ }
362
+ const whole = d.length <= rgbWindow * rgbWindows;
363
+ const windows = whole ? 1 : rgbWindows,
364
+ size = whole ? d.length : rgbWindow;
365
+ const step = whole ? 0 : Math.floor((d.length - rgbWindow) / (rgbWindows - 1) / 12) * 12;
366
+ let e3 = 0,
367
+ e4 = 0,
368
+ n = 0,
369
+ g3 = 0,
370
+ n3 = 0,
371
+ g4 = 0,
372
+ q4 = 0,
373
+ n4 = 0;
374
+ for (let w = 0; w < windows; w++) {
375
+ const start = w * step,
376
+ end = start + size;
377
+ for (let i = start + 4; i < end; i++) {
378
+ const v = d[i],
379
+ a = v - d[i - 3],
380
+ b = v - d[i - 4];
381
+ e3 += a < 0 ? -a : a;
382
+ e4 += b < 0 ? -b : b;
383
+ }
384
+ n += size - 4;
385
+ for (let i = start + 3; i + 2 < end; i += 3) {
386
+ if (d[i] === d[i - 3] && d[i + 1] === d[i - 2] && d[i + 2] === d[i - 1]) {
387
+ continue;
388
+ }
389
+ n3++;
390
+ if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
391
+ g3++;
392
+ }
393
+ }
394
+ for (let i = start + 4; i + 3 < end; i += 4) {
395
+ if (d[i] === d[i - 4] && d[i + 1] === d[i - 3] && d[i + 2] === d[i - 2] && d[i + 3] === d[i - 1]) {
396
+ continue;
397
+ }
398
+ n4++;
399
+ if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
400
+ g4++;
401
+ if (d[i] === d[i + 3]) {
402
+ q4++;
403
+ }
404
+ }
405
+ }
406
+ }
407
+ const score = (e4 / n + 0.05) / (e3 / n + 0.05);
408
+ const flagged = score > 1.25 && q4 < 0.5 * Math.max(1, n4) || g3 > 0.9 * Math.max(1, n3) && g4 < 0.6 * Math.max(1, n4);
409
+ if (!flagged) {
410
+ return false;
411
+ }
412
+ // Bytes that mostly rise by one fixed step ((i * k) & 255, the usual fake image in tests) are pixels of neither kind,
413
+ // and score 4/3 whatever the step. Counted only for arrays about to be flagged, a second pass over the same windows,
414
+ // so RGBA (the usual input) doesn't pay for it.
415
+ let ramp = 0;
416
+ for (let w = 0; w < windows; w++) {
417
+ const start = w * step,
418
+ end = start + size;
419
+ for (let i = start + 4; i < end; i++) {
420
+ const rise = d[i] - d[i - 1] & 255;
421
+ if (rise !== 0 && rise === (d[i - 1] - d[i - 2] & 255)) {
422
+ ramp++;
423
+ }
424
+ }
425
+ }
426
+ return ramp <= 0.5 * n;
427
+ };
428
+
429
+ // Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
430
+ const warned = new Set();
431
+
432
+ // The warning a bare image calls for, or null. It skips everything the main entry rejects (palettes and clusterings
433
+ // passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns about its image and
434
+ // rejects it, and both entries share this one order.
435
+ export const bareRgbWarning = image => {
436
+ if (warned.has('rgb-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
437
+ return null;
438
+ }
439
+ if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
440
+ return null;
441
+ }
442
+ return looksLikeRgb(image) ? 'rgb-as-rgba' : null;
443
+ };
444
+
445
+ // The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
446
+ // process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
447
+ // emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
448
+ // navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
449
+ // keeps Parcel from adding one.
450
+ const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
451
+ const warningText = {
452
+ 'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
453
+ };
454
+ export const warnOnce = (code, byteLength) => {
455
+ if (warned.has(code)) {
456
+ return;
457
+ }
458
+ warned.add(code);
459
+ const message = warningText[code](byteLength);
460
+ const runtime = globalThis.process;
461
+ if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
462
+ runtime.emitWarning(message, {
463
+ type: 'AgglomerativeClusteringWarning',
464
+ code
465
+ });
466
+ } else if (typeof console !== 'undefined') {
467
+ console.warn(`agglomerative-clustering [${code}]: ${message}`);
468
+ }
469
+ };
470
+ // The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
471
+ // also skips the sampling.
472
+ export const silenceWarnings = () => {
473
+ for (const code of Object.keys(warningText)) {
474
+ warned.add(code);
475
+ }
476
+ };
477
+ // For tests.
478
+ export const resetWarnings = () => {
479
+ warned.clear();
480
+ };
279
481
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
280
482
  // `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
281
483
  const inspect = Symbol.for('nodejs.util.inspect.custom');
@@ -1,7 +1,10 @@
1
1
  // Runs inside the worker started by worker.js: receives calls, runs them with the main entry, and posts results
2
2
  // back, transferring every result buffer. Imports `./index.mjs`, which exists only in dist/ (like clustering.js).
3
3
  import * as ac from './index.mjs';
4
- import { MARK, mark, revive, isPalette } from "./shared.mjs";
4
+ import { MARK, mark, revive, isPalette, silenceWarnings } from "./shared.mjs";
5
+
6
+ // The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
7
+ silenceWarnings();
5
8
 
6
9
  // Images kept in the worker by `cluster`, with their clusterings, by handle id.
7
10
  const handles = new Map();
package/dist/worker.cjs CHANGED
@@ -907,6 +907,11 @@ const makeWorker = (options, allowScript) => {
907
907
  }
908
908
  throw abortReason(signal);
909
909
  }
910
+ // The rgb-as-rgba warning is decided here, on the caller's side and before a transfer can empty the
911
+ // array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
912
+ // silenced (PRINCIPLES "Warnings").
913
+ const warning = (0, _shared.bareRgbWarning)(image);
914
+ const byteLength = warning ? image.byteLength : 0;
910
915
  let sent = send(image);
911
916
  if (!ready()) {
912
917
  sent = take(sent);
@@ -916,6 +921,9 @@ const makeWorker = (options, allowScript) => {
916
921
  signal,
917
922
  onProgress
918
923
  });
924
+ if (warning) {
925
+ (0, _shared.warnOnce)(warning, byteLength);
926
+ }
919
927
  return mapped ? rebuild(image)(result) : result;
920
928
  })();
921
929
  };
@@ -965,6 +973,8 @@ const makeWorker = (options, allowScript) => {
965
973
  throw abortReason(signal);
966
974
  }
967
975
  const id = nextHandle++;
976
+ const warning = (0, _shared.bareRgbWarning)(image);
977
+ const byteLength = warning ? image.byteLength : 0;
968
978
  const sent = ready() ? send(image) : take(send(image));
969
979
  // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
970
980
  // existing (see `abandoned`).
@@ -984,6 +994,9 @@ const makeWorker = (options, allowScript) => {
984
994
  }
985
995
  throw error;
986
996
  }
997
+ if (warning) {
998
+ (0, _shared.warnOnce)(warning, byteLength);
999
+ }
987
1000
  const output = rebuild(image);
988
1001
  let released = false;
989
1002
  // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
package/dist/worker.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
5
5
  // worker, started on first use.
6
6
 
7
- import { fail, isCodedError, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } from "./shared.mjs";
7
+ import { fail, isCodedError, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareRgbWarning, warnOnce } from "./shared.mjs";
8
8
 
9
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
10
10
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -838,6 +838,11 @@ const makeWorker = (options, allowScript) => {
838
838
  }
839
839
  throw abortReason(signal);
840
840
  }
841
+ // The rgb-as-rgba warning is decided here, on the caller's side and before a transfer can empty the
842
+ // array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
843
+ // silenced (PRINCIPLES "Warnings").
844
+ const warning = bareRgbWarning(image);
845
+ const byteLength = warning ? image.byteLength : 0;
841
846
  let sent = send(image);
842
847
  if (!ready()) {
843
848
  sent = take(sent);
@@ -847,6 +852,9 @@ const makeWorker = (options, allowScript) => {
847
852
  signal,
848
853
  onProgress
849
854
  });
855
+ if (warning) {
856
+ warnOnce(warning, byteLength);
857
+ }
850
858
  return mapped ? rebuild(image)(result) : result;
851
859
  })();
852
860
  };
@@ -896,6 +904,8 @@ const makeWorker = (options, allowScript) => {
896
904
  throw abortReason(signal);
897
905
  }
898
906
  const id = nextHandle++;
907
+ const warning = bareRgbWarning(image);
908
+ const byteLength = warning ? image.byteLength : 0;
899
909
  const sent = ready() ? send(image) : take(send(image));
900
910
  // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
901
911
  // existing (see `abandoned`).
@@ -915,6 +925,9 @@ const makeWorker = (options, allowScript) => {
915
925
  }
916
926
  throw error;
917
927
  }
928
+ if (warning) {
929
+ warnOnce(warning, byteLength);
930
+ }
918
931
  const output = rebuild(image);
919
932
  let released = false;
920
933
  // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.4.2",
3
+ "version": "3.5.0",
4
4
  "description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
5
5
  "license": "MIT",
6
6
  "author": "Rohan Fredriksson",
@@ -103,6 +103,9 @@
103
103
  "@babel/core": "^7.27.4",
104
104
  "@babel/plugin-transform-modules-commonjs": "^7.27.1",
105
105
  "@babel/preset-env": "^7.27.2",
106
+ "@jsquash/jpeg": "^1.6.0",
107
+ "@jsquash/png": "^3.1.1",
108
+ "@jsquash/webp": "^1.5.0",
106
109
  "@parcel/config-default": "^2.16.4",
107
110
  "@parcel/core": "^2.16.4",
108
111
  "@types/node": "^22.20.5",
@@ -119,6 +122,7 @@
119
122
  "omggif": "^1.0.10",
120
123
  "playwright-core": "^1.56.1",
121
124
  "quantize": "^1.0.2",
125
+ "sharp": "^0.35.5",
122
126
  "typescript": "^5.9.3",
123
127
  "vite": "^8.0.10",
124
128
  "vitest": "^4.1.5",