agglomerative-clustering 3.0.0-beta.6 → 3.0.0-beta.7

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
@@ -39,7 +39,7 @@ import sharp from 'sharp';
39
39
  import { getPalette, quantize } from 'agglomerative-clustering';
40
40
 
41
41
  const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
42
- const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
42
+ const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
43
43
 
44
44
  const palette = await getPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
45
45
  const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
@@ -159,15 +159,15 @@ const clustering = await getClustering(image);
159
159
  const eight = await getSwatchesFromClustering(clustering, 8);
160
160
 
161
161
  // The smallest palette that keeps 99% of the image's colour variance (works the same in 'rgb' and 'oklab')
162
- const { explained } = await getClusteringInfo(clustering); // null only for a clustering from 2.x
163
- const k = (explained ?? []).findIndex((share) => share >= 0.99) + 1;
162
+ const { explained } = await getClusteringInfo(clustering);
163
+ const k = explained.findIndex((share) => share >= 0.99) + 1;
164
164
  ```
165
165
 
166
166
  How many to ask for: 5 to 8 for a set of swatches to show. To *pick* from them (an accent colour, a theme), ask for more, 12 to 16: a small vivid area, such as a red sign in a street scene, only gets a colour of its own once the bigger areas have been split. Each colour is the average of its cluster, so it is a little less saturated than the image's most vivid pixels, and a white background comes back as a near-white such as `[254, 254, 254]` rather than exactly `#ffffff`. On a smooth single-hue photo no colour has a large share (the shares fall as `k` grows), so judge the heaviest swatch against the others, not by a fixed share. See [Picking colours from swatches](#picking-colours-from-swatches).
167
167
 
168
168
  ### GIFs and palette PNGs
169
169
 
170
- `quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`.
170
+ `quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`; a colour is always kept besides it, so `k = 1` can give 2 entries.
171
171
 
172
172
  **A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
173
173
 
@@ -622,7 +622,7 @@ The entry is an ES module, with a CommonJS build for `require()` in Node and in
622
622
  ### TypeScript
623
623
  Both entries ship declarations, checked in CI under strict mode with `nodenext` (ES module and CommonJS importers), `bundler`, and a Node-only project without the DOM lib. The worker entry's declarations use `await using` for handles, so they need **TypeScript 5.2 or newer** (or `skipLibCheck: true`); the main entry works on older versions. Both entries have CommonJS declarations too, so a `.cts` file or a CommonJS project imports either.
624
624
 
625
- Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`, and checking `info.formatVersion === 3` makes `mse`, `explained` and `totalWeight` present. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
625
+ Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
626
626
 
627
627
  An image object assigned to a variable before it is passed widens `format: 'rgba'` to `string`, which no longer matches `RawImage`: write `format: 'rgba' as const`, or declare the variable as `RawImage`.
628
628
 
@@ -663,7 +663,7 @@ What a clustering holds: `{ formatVersion, colorSpace, precision, transparent, m
663
663
  - `mse[k - 1]`: the mean squared error per channel of the `k`-colour clustering, in 8-bit RGB values (OKLab units for an OKLab clustering). `mse[0]` is the image's variance, and `mse[maxColors - 1]` is 0 at the default `precision: 8` (below 8, it is the error that grouping colours discarded). It is an estimate from merge costs; mapping pixels to the palette usually lowers it by another 10–15%.
664
664
  - `explained[k - 1]`: `1 - mse[k - 1] / mse[0]`, the share of the image's variance the `k`-colour palette keeps, from 0 to 1. It has no units, so a target such as `0.99` means the same in both colour spaces.
665
665
 
666
- For a 2.x clustering, `formatVersion` is 2 and `totalWeight`, `mse` and `explained` are `null`; in TypeScript, checking `info.formatVersion === 3` narrows them to present.
666
+ It needs a clustering from 3.x, like `getSwatchesFromClustering`: a 2.x clustering recorded no weights, so it is rejected with `unsupported-version` (the palette and mapping functions still read it).
667
667
 
668
668
  ### `quantize(image, k, options?): Promise<the type of image>`
669
669
  Reduces the image to at most `k` colours.
@@ -714,7 +714,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
714
714
  `errorCodes` is a frozen array of every `code` the library's errors have (see [Errors](#errors)). `isCodedError(value)` is true when `value` has a string `message` and one of those codes; in TypeScript it narrows to `CodedError`. Both entries export both.
715
715
 
716
716
  ### `version: string` and `formatVersion: number`
717
- `version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: if a stored clustering's `getClusteringInfo(stored).formatVersion` differs, cluster the image again (2.x clusterings still load, but have no weights). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
717
+ `version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: a minor release may raise it, and every earlier format from 2 on stays readable. To keep stored clusterings current, cluster the image again when `getClusteringInfo(stored).formatVersion` is below it, or when `getClusteringInfo` rejects the clustering with `unsupported-version` (a 2.x clustering, which has no weights, or one from a newer version than this one). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
718
718
 
719
719
  ## Running it
720
720
 
@@ -812,7 +812,7 @@ Checked with Next.js 16, under Turbopack and webpack, in production builds:
812
812
 
813
813
  ### Angular, esbuild, Rollup and other bundlers
814
814
 
815
- The main entry works in all of them, except that an Angular production build needs `init({ wasm })` (below). The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's `dist/` files out as static assets and say where they are:
815
+ The main entry works in all of them, except that an Angular production build needs `init({ wasm })` (below). The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's whole `dist/` folder out as static assets and say where it is (copy all of it, not a list of files: which files the worker script imports isn't part of the API, and a minor release may change it):
816
816
 
817
817
  ```js
818
818
  import { createWorker } from 'agglomerative-clustering/worker';
@@ -825,9 +825,9 @@ const worker = createWorker({
825
825
  - **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above. Production builds don't emit `clustering.wasm` for the main entry either, so in the browser call `init({ wasm: '/assets/agglomerative-clustering/clustering.wasm' })` before the first call (the dev server works without it). With SSR, the server bundle finds the package's files from the directory the server starts in: start it from the project directory, or give the server its own `init({ wasm: path })`. zone.js needs nothing.
826
826
 
827
827
  ```json
828
- "assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
828
+ "assets": [{ "glob": "**/*", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
829
829
  ```
830
- - **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the same files into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
830
+ - **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the whole `dist/` folder into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
831
831
  - **Vite, webpack 5 and Rsbuild** find the script themselves. So does **Parcel 2**, once it reads package `exports` (without this it can't resolve `agglomerative-clustering/worker`):
832
832
 
833
833
  ```json
@@ -873,7 +873,7 @@ Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wa
873
873
  - **jsdom and happy-dom** have no `ImageData` (install `canvas`, `@napi-rs/canvas` or `skia-canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
874
874
  - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends (or until the garbage collector gets to a dropped `createWorker()`, which may not happen in a test run).
875
875
  - **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })` (`isCodedError` accepts them).
876
- - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and stay the same within a major version: snapshot them. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
876
+ - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and within a major version change only for a bug fix that the changelog names: snapshot them, and expect to update a snapshot when such a fix lands. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
877
877
  - Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
878
878
 
879
879
  ### Writing a package that wraps it
Binary file
package/dist/index.cjs CHANGED
@@ -174,6 +174,10 @@ const wasmLoadFailed = (cause, given) => {
174
174
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
175
175
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
176
176
  }
177
+ } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
178
+ // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
179
+ reason = `the .wasm file could not be fetched${where}: ${reason}`;
180
+ advice = "Check that this machine can reach that URL and that it serves this package's clustering.wasm. On a server, a path to the package's own copy (or its bytes) avoids the request.";
177
181
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
178
182
  // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
179
183
  reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
@@ -275,6 +279,14 @@ const nodeWasmFile = async wasm => {
275
279
  }
276
280
  const isFileUrl = /^file:/i.test(text);
277
281
  // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
282
+ // An http(s) URL is fetched here: the glue would read it as a file path in Node.
283
+ if (/^https?:/i.test(text)) {
284
+ const response = await fetch(text);
285
+ if (!response.ok) {
286
+ throw new Error(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`);
287
+ }
288
+ return new Uint8Array(await response.arrayBuffer());
289
+ }
278
290
  if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
279
291
  return null;
280
292
  }
@@ -371,7 +383,23 @@ const retireIfLarge = instance => {
371
383
  discard(instance);
372
384
  }
373
385
  };
374
- const outOfMemory = () => (0, _shared.fail)('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
386
+ // What to try depends on the call: a large input has to shrink whatever else changes, and `precision: 6` helps only a
387
+ // clustering (`precision` given) that isn't already at 6 or below.
388
+ const outOfMemory = (bytes, precision) => {
389
+ const large = bytes >= 2 ** 28;
390
+ const tries = [];
391
+ if (large) {
392
+ tries.push(`scale the image down (its pixels alone are ${(0, _shared.sizeText)(bytes)}; a few megapixels give as good a palette)`);
393
+ }
394
+ if (precision > 6) {
395
+ tries.push('try `precision: 6`, which bounds the memory an image with very many colours needs');
396
+ }
397
+ if (!large) {
398
+ tries.push('use a smaller image');
399
+ }
400
+ const text = tries.join(', or ');
401
+ return (0, _shared.fail)('out-of-memory', `The WebAssembly module ran out of memory (it can use up to 2 GB for one image). ${text[0].toUpperCase()}${text.slice(1)}.`);
402
+ };
375
403
  const unpack = (wasm, pointer) => {
376
404
  const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
377
405
  const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
@@ -722,28 +750,21 @@ const checkNotEmpty = (palette, image, cutoff) => {
722
750
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
723
751
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
724
752
 
725
- // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
726
- // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
727
- // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
728
- const maxBytes = 2 ** 31;
729
- const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
730
- const tooLarge = bytes => (0, _shared.fail)('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
731
-
732
753
  // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
733
754
  const allocate = (wasm, length) => {
734
- if (length >= maxBytes) {
735
- throw tooLarge(length);
755
+ if (length >= _shared.maxBytes) {
756
+ throw (0, _shared.tooLarge)(length);
736
757
  }
737
758
  const pointer = wasm._malloc(length);
738
759
  if (!pointer) {
739
- throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
760
+ throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${(0, _shared.sizeText)(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
740
761
  }
741
762
  return pointer;
742
763
  };
743
764
 
744
765
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
745
- // freeing everything afterwards.
746
- const call = (wasm, buffers, fn) => {
766
+ // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
767
+ const call = (wasm, buffers, fn, precision) => {
747
768
  const pointers = [];
748
769
  let outputPointer = 0;
749
770
  let aborted = false;
@@ -766,7 +787,7 @@ const call = (wasm, buffers, fn) => {
766
787
  }
767
788
  aborted = true;
768
789
  discard(wasm);
769
- throw outOfMemory();
790
+ throw outOfMemory(buffers[0].length, precision);
770
791
  } finally {
771
792
  // After an abort the instance is being thrown away, and its allocator can't be trusted.
772
793
  if (!aborted) {
@@ -862,7 +883,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
862
883
  }
863
884
  aborted = true;
864
885
  discard(wasm);
865
- throw outOfMemory();
886
+ throw outOfMemory(image.data.length, o.precision);
866
887
  } finally {
867
888
  if (!aborted) {
868
889
  if (job) {
@@ -896,7 +917,7 @@ const getClustering = async (image, options) => {
896
917
  report(1);
897
918
  return (0, _shared.markClustering)(clustering);
898
919
  }
899
- return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
920
+ return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
900
921
  };
901
922
  exports.getClustering = getClustering;
902
923
  const getPalette = async (image, k, options) => {
@@ -912,7 +933,7 @@ const getPalette = async (image, k, options) => {
912
933
  report(1);
913
934
  return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
914
935
  }
915
- return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent)), (0, _shared.colorSpaceName)(o.colorSpace));
936
+ return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), (0, _shared.colorSpaceName)(o.colorSpace));
916
937
  };
917
938
  exports.getPalette = getPalette;
918
939
  const getPaletteFromClustering = async (clustering, k, ...extra) => {
@@ -934,6 +955,14 @@ const weightsOf = (wasm, clustering, header, k) => {
934
955
  return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
935
956
  };
936
957
 
958
+ // The functions that report weights (swatches, the error curve) need a clustering from 3.x: 2.x recorded none. The others
959
+ // (palettes and mapping) still read 2.x clusterings.
960
+ const needsWeights = header => {
961
+ if (header.version < 3) {
962
+ throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
963
+ }
964
+ };
965
+
937
966
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
938
967
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
939
968
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
@@ -941,9 +970,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
941
970
  const header = (0, _shared.readHeader)(clustering);
942
971
  k = check(k);
943
972
  noOptions('getSwatchesFromClustering', extra);
944
- if (header.version < 3) {
945
- throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
946
- }
973
+ needsWeights(header);
947
974
  clustering = held(clustering);
948
975
  const wasm = Module || (await acquire());
949
976
  const palette = (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
@@ -981,6 +1008,7 @@ exports.getSwatches = getSwatches;
981
1008
  const getClusteringInfo = async (clustering, ...extra) => {
982
1009
  const header = (0, _shared.readHeader)(clustering);
983
1010
  noOptions('getClusteringInfo', extra);
1011
+ needsWeights(header);
984
1012
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
985
1013
  const info = {
986
1014
  formatVersion: header.version,
@@ -988,13 +1016,10 @@ const getClusteringInfo = async (clustering, ...extra) => {
988
1016
  precision: header.precision,
989
1017
  transparent: header.transparent === 0 ? false : header.transparent,
990
1018
  maxColors: colors,
991
- totalWeight: null,
1019
+ totalWeight: 0,
992
1020
  mse: null,
993
1021
  explained: null
994
1022
  };
995
- if (header.version < 3) {
996
- return info;
997
- }
998
1023
  const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
999
1024
  const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
1000
1025
  const total = view.getUint32(8, true);
@@ -1038,7 +1063,7 @@ const quantize = async (image, k, options) => {
1038
1063
  report(1);
1039
1064
  return mapped;
1040
1065
  }
1041
- 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.width, o.transparent)));
1066
+ 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.width, o.transparent), o.precision));
1042
1067
  };
1043
1068
  exports.quantize = quantize;
1044
1069
  const quantizeFromClustering = async (image, clustering, k, options) => {
@@ -1083,7 +1108,7 @@ const quantizeToIndices = async (image, k, options) => {
1083
1108
  report(1);
1084
1109
  return indexed;
1085
1110
  }
1086
- 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.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
1111
+ 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.width, o.transparent), o.precision), original, (0, _shared.colorSpaceName)(o.colorSpace));
1087
1112
  };
1088
1113
  exports.quantizeToIndices = quantizeToIndices;
1089
1114
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
package/dist/index.d.cts CHANGED
@@ -250,9 +250,9 @@ interface IndexedImageFields {
250
250
  /** The index of the entry for fully transparent pixels, or `null` if there is none. */
251
251
  transparentIndex: number | null;
252
252
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
253
- width?: number;
253
+ width?: number | undefined;
254
254
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
255
- height?: number;
255
+ height?: number | undefined;
256
256
  }
257
257
 
258
258
  /**
@@ -282,10 +282,10 @@ export const version: string;
282
282
  /**
283
283
  * The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
284
284
  * reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
285
- * changes only when the stored format does, so a new release that keeps the format keeps this number. This build reads
286
- * this format and the one before it (2).
285
+ * changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
286
+ * may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
287
287
  */
288
- export const formatVersion: 3;
288
+ export const formatVersion: number;
289
289
 
290
290
  /**
291
291
  * Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
356
356
  */
357
357
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
358
358
 
359
- interface ClusteringInfoFields {
359
+ /** What a clustering holds (`getClusteringInfo`). */
360
+ export interface ClusteringInfo {
361
+ /**
362
+ * The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
363
+ * build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
364
+ */
365
+ formatVersion: number;
360
366
  colorSpace: ColorSpace;
361
367
  /** Bits per channel it was clustered with. */
362
368
  precision: number;
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
367
373
  transparent: false | number;
368
374
  /** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
369
375
  maxColors: number;
370
- }
371
-
372
- /** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
373
- export interface ClusteringInfoV3 extends ClusteringInfoFields {
374
- /** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
375
- formatVersion: 3;
376
376
  /** Total weight in pixels (opacity-weighted). */
377
377
  totalWeight: number;
378
378
  /**
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
392
392
  explained: Float64Array;
393
393
  }
394
394
 
395
- /** What a 2.x clustering holds: no weights, so no error curve. */
396
- export interface ClusteringInfoV2 extends ClusteringInfoFields {
397
- /** The format of the clustering's bytes (see `ClusteringInfoV3.formatVersion`). */
398
- formatVersion: 2;
399
- totalWeight: null;
400
- mse: null;
401
- explained: null;
402
- }
403
-
404
- /** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
405
- export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
406
-
407
- /** Reads what a clustering holds, including its error curve for choosing a palette size. */
395
+ /**
396
+ * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
397
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
398
+ * the palette and mapping functions still read it.
399
+ */
408
400
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
409
401
 
410
402
  /**
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
442
434
  *
443
435
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
444
436
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
437
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
445
438
  */
446
439
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
447
440
 
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
450
443
  *
451
444
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
452
445
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
446
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
453
447
  */
454
448
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
455
449
 
package/dist/index.d.ts CHANGED
@@ -250,9 +250,9 @@ interface IndexedImageFields {
250
250
  /** The index of the entry for fully transparent pixels, or `null` if there is none. */
251
251
  transparentIndex: number | null;
252
252
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
253
- width?: number;
253
+ width?: number | undefined;
254
254
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
255
- height?: number;
255
+ height?: number | undefined;
256
256
  }
257
257
 
258
258
  /**
@@ -282,10 +282,10 @@ export const version: string;
282
282
  /**
283
283
  * The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
284
284
  * reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
285
- * changes only when the stored format does, so a new release that keeps the format keeps this number. This build reads
286
- * this format and the one before it (2).
285
+ * changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
286
+ * may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
287
287
  */
288
- export const formatVersion: 3;
288
+ export const formatVersion: number;
289
289
 
290
290
  /**
291
291
  * Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
356
356
  */
357
357
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
358
358
 
359
- interface ClusteringInfoFields {
359
+ /** What a clustering holds (`getClusteringInfo`). */
360
+ export interface ClusteringInfo {
361
+ /**
362
+ * The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
363
+ * build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
364
+ */
365
+ formatVersion: number;
360
366
  colorSpace: ColorSpace;
361
367
  /** Bits per channel it was clustered with. */
362
368
  precision: number;
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
367
373
  transparent: false | number;
368
374
  /** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
369
375
  maxColors: number;
370
- }
371
-
372
- /** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
373
- export interface ClusteringInfoV3 extends ClusteringInfoFields {
374
- /** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
375
- formatVersion: 3;
376
376
  /** Total weight in pixels (opacity-weighted). */
377
377
  totalWeight: number;
378
378
  /**
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
392
392
  explained: Float64Array;
393
393
  }
394
394
 
395
- /** What a 2.x clustering holds: no weights, so no error curve. */
396
- export interface ClusteringInfoV2 extends ClusteringInfoFields {
397
- /** The format of the clustering's bytes (see `ClusteringInfoV3.formatVersion`). */
398
- formatVersion: 2;
399
- totalWeight: null;
400
- mse: null;
401
- explained: null;
402
- }
403
-
404
- /** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
405
- export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
406
-
407
- /** Reads what a clustering holds, including its error curve for choosing a palette size. */
395
+ /**
396
+ * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
397
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
398
+ * the palette and mapping functions still read it.
399
+ */
408
400
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
409
401
 
410
402
  /**
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
442
434
  *
443
435
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
444
436
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
437
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
445
438
  */
446
439
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
447
440
 
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
450
443
  *
451
444
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
452
445
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
446
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
453
447
  */
454
448
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
455
449
 
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
2
+ import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } 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 } from "./shared.mjs";
@@ -131,6 +131,10 @@ const wasmLoadFailed = (cause, given) => {
131
131
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
132
132
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
133
133
  }
134
+ } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
135
+ // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
136
+ reason = `the .wasm file could not be fetched${where}: ${reason}`;
137
+ advice = "Check that this machine can reach that URL and that it serves this package's clustering.wasm. On a server, a path to the package's own copy (or its bytes) avoids the request.";
134
138
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
135
139
  // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
136
140
  reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
@@ -232,6 +236,14 @@ const nodeWasmFile = async wasm => {
232
236
  }
233
237
  const isFileUrl = /^file:/i.test(text);
234
238
  // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
239
+ // An http(s) URL is fetched here: the glue would read it as a file path in Node.
240
+ if (/^https?:/i.test(text)) {
241
+ const response = await fetch(text);
242
+ if (!response.ok) {
243
+ throw new Error(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`);
244
+ }
245
+ return new Uint8Array(await response.arrayBuffer());
246
+ }
235
247
  if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
236
248
  return null;
237
249
  }
@@ -327,7 +339,23 @@ const retireIfLarge = instance => {
327
339
  discard(instance);
328
340
  }
329
341
  };
330
- const outOfMemory = () => fail('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
342
+ // What to try depends on the call: a large input has to shrink whatever else changes, and `precision: 6` helps only a
343
+ // clustering (`precision` given) that isn't already at 6 or below.
344
+ const outOfMemory = (bytes, precision) => {
345
+ const large = bytes >= 2 ** 28;
346
+ const tries = [];
347
+ if (large) {
348
+ tries.push(`scale the image down (its pixels alone are ${sizeText(bytes)}; a few megapixels give as good a palette)`);
349
+ }
350
+ if (precision > 6) {
351
+ tries.push('try `precision: 6`, which bounds the memory an image with very many colours needs');
352
+ }
353
+ if (!large) {
354
+ tries.push('use a smaller image');
355
+ }
356
+ const text = tries.join(', or ');
357
+ return fail('out-of-memory', `The WebAssembly module ran out of memory (it can use up to 2 GB for one image). ${text[0].toUpperCase()}${text.slice(1)}.`);
358
+ };
331
359
  const unpack = (wasm, pointer) => {
332
360
  const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
333
361
  const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
@@ -678,13 +706,6 @@ const checkNotEmpty = (palette, image, cutoff) => {
678
706
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
679
707
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
680
708
 
681
- // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
682
- // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
683
- // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
684
- const maxBytes = 2 ** 31;
685
- const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
686
- const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
687
-
688
709
  // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
689
710
  const allocate = (wasm, length) => {
690
711
  if (length >= maxBytes) {
@@ -698,8 +719,8 @@ const allocate = (wasm, length) => {
698
719
  };
699
720
 
700
721
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
701
- // freeing everything afterwards.
702
- const call = (wasm, buffers, fn) => {
722
+ // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
723
+ const call = (wasm, buffers, fn, precision) => {
703
724
  const pointers = [];
704
725
  let outputPointer = 0;
705
726
  let aborted = false;
@@ -722,7 +743,7 @@ const call = (wasm, buffers, fn) => {
722
743
  }
723
744
  aborted = true;
724
745
  discard(wasm);
725
- throw outOfMemory();
746
+ throw outOfMemory(buffers[0].length, precision);
726
747
  } finally {
727
748
  // After an abort the instance is being thrown away, and its allocator can't be trusted.
728
749
  if (!aborted) {
@@ -818,7 +839,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
818
839
  }
819
840
  aborted = true;
820
841
  discard(wasm);
821
- throw outOfMemory();
842
+ throw outOfMemory(image.data.length, o.precision);
822
843
  } finally {
823
844
  if (!aborted) {
824
845
  if (job) {
@@ -852,7 +873,7 @@ export const getClustering = async (image, options) => {
852
873
  report(1);
853
874
  return markClustering(clustering);
854
875
  }
855
- return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
876
+ return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
856
877
  };
857
878
  export const getPalette = async (image, k, options) => {
858
879
  image = load(image);
@@ -867,7 +888,7 @@ export const getPalette = async (image, k, options) => {
867
888
  report(1);
868
889
  return markPalette(palette, colorSpaceName(o.colorSpace));
869
890
  }
870
- return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent)), colorSpaceName(o.colorSpace));
891
+ return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
871
892
  };
872
893
  export const getPaletteFromClustering = async (clustering, k, ...extra) => {
873
894
  const header = readHeader(clustering);
@@ -887,6 +908,14 @@ const weightsOf = (wasm, clustering, header, k) => {
887
908
  return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
888
909
  };
889
910
 
911
+ // The functions that report weights (swatches, the error curve) need a clustering from 3.x: 2.x recorded none. The others
912
+ // (palettes and mapping) still read 2.x clusterings.
913
+ const needsWeights = header => {
914
+ if (header.version < 3) {
915
+ throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
916
+ }
917
+ };
918
+
890
919
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
891
920
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
892
921
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
@@ -894,9 +923,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
894
923
  const header = readHeader(clustering);
895
924
  k = check(k);
896
925
  noOptions('getSwatchesFromClustering', extra);
897
- if (header.version < 3) {
898
- throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
899
- }
926
+ needsWeights(header);
900
927
  clustering = held(clustering);
901
928
  const wasm = Module || (await acquire());
902
929
  const palette = markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
@@ -932,6 +959,7 @@ export const getSwatches = async (image, k, options) => {
932
959
  export const getClusteringInfo = async (clustering, ...extra) => {
933
960
  const header = readHeader(clustering);
934
961
  noOptions('getClusteringInfo', extra);
962
+ needsWeights(header);
935
963
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
936
964
  const info = {
937
965
  formatVersion: header.version,
@@ -939,13 +967,10 @@ export const getClusteringInfo = async (clustering, ...extra) => {
939
967
  precision: header.precision,
940
968
  transparent: header.transparent === 0 ? false : header.transparent,
941
969
  maxColors: colors,
942
- totalWeight: null,
970
+ totalWeight: 0,
943
971
  mse: null,
944
972
  explained: null
945
973
  };
946
- if (header.version < 3) {
947
- return info;
948
- }
949
974
  const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
950
975
  const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
951
976
  const total = view.getUint32(8, true);
@@ -988,7 +1013,7 @@ export const quantize = async (image, k, options) => {
988
1013
  report(1);
989
1014
  return mapped;
990
1015
  }
991
- 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.width, o.transparent)));
1016
+ 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.width, o.transparent), o.precision));
992
1017
  };
993
1018
  export const quantizeFromClustering = async (image, clustering, k, options) => {
994
1019
  const wrap = getWrapper(image);
@@ -1030,7 +1055,7 @@ export const quantizeToIndices = async (image, k, options) => {
1030
1055
  report(1);
1031
1056
  return indexed;
1032
1057
  }
1033
- 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.width, o.transparent)), original, colorSpaceName(o.colorSpace));
1058
+ 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.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
1034
1059
  };
1035
1060
  export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1036
1061
  const original = image;
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.snapshot = exports.revive = exports.readHeader = 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.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = void 0;
9
+ exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = 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.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = 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.0.0-beta.6';
16
+ const version = exports.version = '3.0.0-beta.7';
17
17
  const colorSpaces = exports.colorSpaces = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -42,9 +42,19 @@ const fail = (code, message, argument) => Object.assign(new Error(message), argu
42
42
  argument
43
43
  });
44
44
 
45
+ // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
46
+ // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
47
+ // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
48
+ // worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
49
+ exports.fail = fail;
50
+ const maxBytes = exports.maxBytes = 2 ** 31;
51
+ const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
52
+ exports.sizeText = sizeText;
53
+ const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
54
+
45
55
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
46
56
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
47
- exports.fail = fail;
57
+ exports.tooLarge = tooLarge;
48
58
  const tag = value => Object.prototype.toString.call(value);
49
59
  const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
50
60
  exports.isUint8Array = isUint8Array;
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.0.0-beta.6';
7
+ export const version = '3.0.0-beta.7';
8
8
  export const colorSpaces = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -31,6 +31,14 @@ export const fail = (code, message, argument) => Object.assign(new Error(message
31
31
  argument
32
32
  });
33
33
 
34
+ // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
35
+ // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
36
+ // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
37
+ // worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
38
+ export const maxBytes = 2 ** 31;
39
+ export const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
40
+ export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
41
+
34
42
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
35
43
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
36
44
  const tag = value => Object.prototype.toString.call(value);
package/dist/worker.cjs CHANGED
@@ -293,6 +293,10 @@ const send = image => {
293
293
  if (pixels && (0, _shared.isDetached)(pixels)) {
294
294
  throw (0, _shared.fail)('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
295
295
  }
296
+ // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
297
+ if (pixels && pixels.byteLength >= _shared.maxBytes) {
298
+ throw (0, _shared.tooLarge)(pixels.byteLength);
299
+ }
296
300
  if ((0, _shared.isImageData)(image)) {
297
301
  (0, _shared.checkImageDataPixels)(image);
298
302
  const data = image.data;
@@ -672,8 +676,8 @@ const makeWorker = (options, allowScript) => {
672
676
  }
673
677
  const waitingFor = startingGeneration;
674
678
  const started = await starting;
679
+ // terminate() stops the worker that was starting itself, once (not once per call that waited for it).
675
680
  if (terminated) {
676
- started.terminate();
677
681
  throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
678
682
  }
679
683
  // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
@@ -946,11 +950,10 @@ const makeWorker = (options, allowScript) => {
946
950
  })();
947
951
  };
948
952
 
949
- // Stops the worker. Calls still waiting are rejected, and later calls fail.
950
- const stop = async () => {
951
- if (terminated) {
952
- return;
953
- }
953
+ // Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
954
+ // so a second terminate() made while the first is running also waits until the thread has gone.
955
+ let stopping = null;
956
+ const stop = () => stopping = stopping || (async () => {
954
957
  terminated = true;
955
958
  for (const call of pending.values()) {
956
959
  call.cleanup();
@@ -964,7 +967,7 @@ const makeWorker = (options, allowScript) => {
964
967
  (await starting).terminate();
965
968
  } catch (ignored) {/* it never started */}
966
969
  }
967
- };
970
+ })();
968
971
  // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
969
972
  const stopIfAbandoned = () => {
970
973
  if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
package/dist/worker.d.cts CHANGED
@@ -24,11 +24,11 @@ export { isCodedError } from './index.cjs';
24
24
  export const version: string;
25
25
 
26
26
  /** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
27
- export const formatVersion: 3;
27
+ export const formatVersion: number;
28
28
 
29
29
  export type {
30
30
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
31
- ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
31
+ ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
32
32
  } from './index.cjs';
33
33
 
34
34
  /** Options for `createWorker`. */
package/dist/worker.d.ts CHANGED
@@ -24,11 +24,11 @@ export { isCodedError } from './index.js';
24
24
  export const version: string;
25
25
 
26
26
  /** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
27
- export const formatVersion: 3;
27
+ export const formatVersion: number;
28
28
 
29
29
  export type {
30
30
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
31
- ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
31
+ ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
32
32
  } from './index.js';
33
33
 
34
34
  /** Options for `createWorker`. */
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, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
7
+ import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } 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 } from "./shared.mjs";
@@ -256,6 +256,10 @@ const send = image => {
256
256
  if (pixels && isDetached(pixels)) {
257
257
  throw fail('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
258
258
  }
259
+ // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
260
+ if (pixels && pixels.byteLength >= maxBytes) {
261
+ throw tooLarge(pixels.byteLength);
262
+ }
259
263
  if (isImageData(image)) {
260
264
  checkImageDataPixels(image);
261
265
  const data = image.data;
@@ -635,8 +639,8 @@ const makeWorker = (options, allowScript) => {
635
639
  }
636
640
  const waitingFor = startingGeneration;
637
641
  const started = await starting;
642
+ // terminate() stops the worker that was starting itself, once (not once per call that waited for it).
638
643
  if (terminated) {
639
- started.terminate();
640
644
  throw fail('worker-terminated', "Worker terminated.");
641
645
  }
642
646
  // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
@@ -909,11 +913,10 @@ const makeWorker = (options, allowScript) => {
909
913
  })();
910
914
  };
911
915
 
912
- // Stops the worker. Calls still waiting are rejected, and later calls fail.
913
- const stop = async () => {
914
- if (terminated) {
915
- return;
916
- }
916
+ // Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
917
+ // so a second terminate() made while the first is running also waits until the thread has gone.
918
+ let stopping = null;
919
+ const stop = () => stopping = stopping || (async () => {
917
920
  terminated = true;
918
921
  for (const call of pending.values()) {
919
922
  call.cleanup();
@@ -927,7 +930,7 @@ const makeWorker = (options, allowScript) => {
927
930
  (await starting).terminate();
928
931
  } catch (ignored) {/* it never started */}
929
932
  }
930
- };
933
+ })();
931
934
  // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
932
935
  const stopIfAbandoned = () => {
933
936
  if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.0.0-beta.6",
3
+ "version": "3.0.0-beta.7",
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",