agglomerative-clustering 3.3.0 → 3.4.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 +17 -15
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +16 -9
- package/dist/index.d.cts +14 -8
- package/dist/index.d.ts +14 -8
- package/dist/index.mjs +12 -6
- package/dist/shared.cjs +8 -8
- package/dist/shared.mjs +8 -8
- package/dist/worker-thread.mjs +21 -5
- package/dist/worker.cjs +82 -26
- package/dist/worker.d.cts +18 -3
- package/dist/worker.d.ts +18 -3
- package/dist/worker.mjs +79 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
16
16
|
- **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
|
|
17
17
|
- **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
|
|
18
18
|
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
|
|
19
|
-
- **Small and portable.**
|
|
19
|
+
- **Small and portable.** About 127 KB of WebAssembly (52 KB gzipped), Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
|
|
20
20
|
|
|
21
21
|
## Install
|
|
22
22
|
|
|
@@ -24,7 +24,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
24
24
|
npm install agglomerative-clustering
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
-
Upgrading
|
|
27
|
+
Upgrading? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.3, three functions have new names, and the old ones keep working until 4.0. From 2.x, one function was renamed, and palettes and images are the same as 2.0's, with one documented exception.
|
|
28
28
|
|
|
29
29
|
It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4). Deno, Bun, Cloudflare Workers, serverless functions, Electron and browser extensions work too: see [Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).
|
|
30
30
|
|
|
@@ -34,12 +34,12 @@ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome
|
|
|
34
34
|
|
|
35
35
|
```js
|
|
36
36
|
import sharp from 'sharp';
|
|
37
|
-
import {
|
|
37
|
+
import { buildPalette, quantize } from 'agglomerative-clustering';
|
|
38
38
|
|
|
39
39
|
const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
40
40
|
const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
|
|
41
41
|
|
|
42
|
-
const palette = await
|
|
42
|
+
const palette = await buildPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
|
|
43
43
|
const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
|
|
44
44
|
|
|
45
45
|
await sharp(Buffer.from(reduced.data), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-16.png');
|
|
@@ -59,9 +59,9 @@ ctx.putImageData(await quantize(imageData, 16, { dither: true }), 0, 0); // Im
|
|
|
59
59
|
**Swatches, with each colour's share of the image:**
|
|
60
60
|
|
|
61
61
|
```js
|
|
62
|
-
import {
|
|
62
|
+
import { buildSwatches } from 'agglomerative-clustering';
|
|
63
63
|
|
|
64
|
-
const { palette, shares } = await
|
|
64
|
+
const { palette, shares } = await buildSwatches(imageData, 6); // six colours; the shares sum to 1
|
|
65
65
|
shares.forEach((share, i) => {
|
|
66
66
|
console.log(`rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`, `${(share * 100).toFixed(1)}%`);
|
|
67
67
|
});
|
|
@@ -70,9 +70,9 @@ shares.forEach((share, i) => {
|
|
|
70
70
|
**A colour-count slider:** cluster once, then cut and map as often as you like.
|
|
71
71
|
|
|
72
72
|
```js
|
|
73
|
-
import {
|
|
73
|
+
import { buildClustering, quantizeWithPalette } from 'agglomerative-clustering';
|
|
74
74
|
|
|
75
|
-
const clustering = await
|
|
75
|
+
const clustering = await buildClustering(imageData); // the expensive step, done once
|
|
76
76
|
|
|
77
77
|
slider.oninput = async () => {
|
|
78
78
|
const palette = await clustering.getPalette(Number(slider.value)); // ~0.4 ms for any k
|
|
@@ -85,22 +85,24 @@ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `
|
|
|
85
85
|
## How it works
|
|
86
86
|
|
|
87
87
|
```
|
|
88
|
-
image ──▶
|
|
89
|
-
once, ~70 ms
|
|
90
|
-
|
|
88
|
+
image ──▶ buildClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
|
|
89
|
+
once, ~70 ms bytes you can under 1 ms, flat RGB a few ms,
|
|
90
|
+
store any k bytes any palette
|
|
91
91
|
```
|
|
92
92
|
|
|
93
|
-
The one-shot functions (`
|
|
93
|
+
The one-shot functions (`buildPalette`, `quantize`, …) do every step for you. To try many palette sizes, call `buildClustering` once and cut it as often as you like.
|
|
94
94
|
|
|
95
95
|
| You want | from the image | from a clustering you hold¹ | with a palette you supply |
|
|
96
96
|
|---|---|---|---|
|
|
97
|
-
| a palette (flat RGB) | `
|
|
98
|
-
| a palette with each colour's share | `
|
|
97
|
+
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)` (`getPaletteFromClustering`) | |
|
|
98
|
+
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)` (`getSwatchesFromClustering`) | |
|
|
99
99
|
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` (`quantizeFromClustering`) | `quantizeWithPalette` |
|
|
100
100
|
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` (`quantizeToIndicesFromClustering`) | `quantizeToIndicesWithPalette` |
|
|
101
101
|
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` (`getClusteringInfo`) | |
|
|
102
102
|
|
|
103
|
-
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `
|
|
103
|
+
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
104
|
+
|
|
105
|
+
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. The `build…` names arrived in 3.4.0; [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) has the old ones.
|
|
104
106
|
|
|
105
107
|
**Methods or functions?** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **In a worker, use a handle** (`createWorker().cluster(image)`, below) or the worker entry's function forms: the methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
|
|
106
108
|
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ Object.defineProperty(exports, "alphaModes", {
|
|
|
21
21
|
return _shared.alphaModes;
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
|
+
exports.buildSwatches = exports.buildPalette = exports.buildClustering = void 0;
|
|
24
25
|
Object.defineProperty(exports, "colorSpaces", {
|
|
25
26
|
enumerable: true,
|
|
26
27
|
get: function () {
|
|
@@ -553,7 +554,7 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
553
554
|
};
|
|
554
555
|
const load = image => {
|
|
555
556
|
if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
|
|
556
|
-
const what = (0, _shared.isClustering)(image) ? 'a clustering (from
|
|
557
|
+
const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
557
558
|
const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
558
559
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
559
560
|
}
|
|
@@ -712,7 +713,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
712
713
|
options = (0, _shared.snapshot)(options);
|
|
713
714
|
for (const key of Object.keys(options)) {
|
|
714
715
|
if (!allowed.includes(key)) {
|
|
715
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
716
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal: they finish in milliseconds, with no progress to report.' : '';
|
|
716
717
|
throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
717
718
|
}
|
|
718
719
|
}
|
|
@@ -976,7 +977,7 @@ const noOptions = (name, extra) => {
|
|
|
976
977
|
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
977
978
|
// happens before the call returns.
|
|
978
979
|
|
|
979
|
-
const
|
|
980
|
+
const buildClustering = async (image, options) => {
|
|
980
981
|
image = load(image);
|
|
981
982
|
const o = parseOptions(options, clusterOptions, image);
|
|
982
983
|
const wasm = Module || (await acquire());
|
|
@@ -988,8 +989,10 @@ const getClustering = async (image, options) => {
|
|
|
988
989
|
}
|
|
989
990
|
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));
|
|
990
991
|
};
|
|
991
|
-
|
|
992
|
-
|
|
992
|
+
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
993
|
+
exports.buildClustering = buildClustering;
|
|
994
|
+
const getClustering = exports.getClustering = buildClustering;
|
|
995
|
+
const buildPalette = async (image, k, options) => {
|
|
993
996
|
image = load(image);
|
|
994
997
|
k = check(k);
|
|
995
998
|
const o = parseOptions(options, clusterOptions, image);
|
|
@@ -1004,9 +1007,11 @@ const getPalette = async (image, k, options) => {
|
|
|
1004
1007
|
}
|
|
1005
1008
|
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));
|
|
1006
1009
|
};
|
|
1010
|
+
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
1011
|
+
exports.buildPalette = buildPalette;
|
|
1012
|
+
const getPalette = exports.getPalette = buildPalette;
|
|
1007
1013
|
|
|
1008
1014
|
// The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
|
|
1009
|
-
exports.getPalette = getPalette;
|
|
1010
1015
|
const cutPalette = async (name, clustering, k, extra) => {
|
|
1011
1016
|
const header = (0, _shared.readHeader)(clustering);
|
|
1012
1017
|
k = check(k);
|
|
@@ -1067,17 +1072,19 @@ const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getS
|
|
|
1067
1072
|
|
|
1068
1073
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
1069
1074
|
exports.getSwatchesFromClustering = getSwatchesFromClustering;
|
|
1070
|
-
const
|
|
1075
|
+
const buildSwatches = async (image, k, options) => {
|
|
1071
1076
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
1072
1077
|
load(image);
|
|
1073
1078
|
k = check(k);
|
|
1074
|
-
return getSwatchesFromClustering(await
|
|
1079
|
+
return getSwatchesFromClustering(await buildClustering(image, options), k);
|
|
1075
1080
|
};
|
|
1081
|
+
/** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
|
|
1082
|
+
exports.buildSwatches = buildSwatches;
|
|
1083
|
+
const getSwatches = exports.getSwatches = buildSwatches;
|
|
1076
1084
|
|
|
1077
1085
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
1078
1086
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
1079
1087
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
1080
|
-
exports.getSwatches = getSwatches;
|
|
1081
1088
|
const readInfo = async (name, clustering, extra) => {
|
|
1082
1089
|
const header = (0, _shared.readHeader)(clustering);
|
|
1083
1090
|
noOptions(name, extra);
|
package/dist/index.d.cts
CHANGED
|
@@ -125,7 +125,7 @@ export class Palette extends Uint8Array {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* The bytes of a clustering, as `
|
|
128
|
+
* The bytes of a clustering, as `buildClustering` returns them: an opaque `Uint8Array` (tagged, like `Palette`) that you can
|
|
129
129
|
* store (a file, IndexedDB, next to the image) and cut to a palette of any size later. It is a type of its own, so a
|
|
130
130
|
* clustering can't be passed where a palette goes (or the other way round): TypeScript says so, and at run time a
|
|
131
131
|
* `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
|
|
@@ -200,7 +200,7 @@ export interface ProgressOptions extends CancelOptions {
|
|
|
200
200
|
onProgress?: ((progress: number) => void) | undefined;
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
/** Options for building the colour hierarchy: `
|
|
203
|
+
/** Options for building the colour hierarchy: `buildClustering`, `buildPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
|
|
204
204
|
export interface ClusteringOptions extends ProgressOptions {
|
|
205
205
|
/**
|
|
206
206
|
* `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
|
|
@@ -223,7 +223,7 @@ export interface ClusteringOptions extends ProgressOptions {
|
|
|
223
223
|
* `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
|
|
224
224
|
* below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
|
|
225
225
|
* whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
|
|
226
|
-
* PNG), and it gives the same palette everywhere: `
|
|
226
|
+
* PNG), and it gives the same palette everywhere: `buildPalette(image, k, { transparent })` is the palette
|
|
227
227
|
* `quantizeToIndices(image, k, { transparent })` uses, apart from that function's extra transparent entry.
|
|
228
228
|
* Cluster with it to get the palette you will map with (see `IndexOptions.transparent`). The cutoff is recorded in the
|
|
229
229
|
* clustering (see `ClusteringInfo.transparent`), and `quantizeToIndicesFromClustering` uses it unless you name one.
|
|
@@ -293,7 +293,7 @@ export interface IndexOptions {
|
|
|
293
293
|
* opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
|
|
294
294
|
* transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
|
|
295
295
|
* this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
|
|
296
|
-
* `ClusteringOptions.transparent`), so its palette is `
|
|
296
|
+
* `ClusteringOptions.transparent`), so its palette is `buildPalette(image, k - 1, { transparent })`'s. With a palette
|
|
297
297
|
* you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
|
|
298
298
|
* `quantizeToIndicesFromClustering` the default is the cutoff the clustering was made with.
|
|
299
299
|
*/
|
|
@@ -352,7 +352,7 @@ export interface InitOptions {
|
|
|
352
352
|
export const version: string;
|
|
353
353
|
|
|
354
354
|
/**
|
|
355
|
-
* The version of the data this library stores: the format of the clusterings `
|
|
355
|
+
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`getClusteringInfo`
|
|
356
356
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
357
357
|
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
358
358
|
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
@@ -371,16 +371,20 @@ export function init(options?: InitOptions): Promise<void>;
|
|
|
371
371
|
* cache or store next to the image. Cut it to a palette of any size with `getPaletteFromClustering`, or map pixels
|
|
372
372
|
* with `quantizeFromClustering`. An image with no visible pixels gives a clustering that cuts to an empty palette.
|
|
373
373
|
*/
|
|
374
|
+
export function buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
374
376
|
export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
377
|
|
|
376
378
|
/**
|
|
377
379
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
378
|
-
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `
|
|
380
|
+
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
379
381
|
* once and cut it.
|
|
380
382
|
*
|
|
381
383
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
382
384
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
383
385
|
*/
|
|
386
|
+
export function buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
387
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
384
388
|
export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
385
389
|
|
|
386
390
|
/**
|
|
@@ -417,10 +421,12 @@ export interface Swatches {
|
|
|
417
421
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
418
422
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
419
423
|
*/
|
|
424
|
+
export function buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
425
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
420
426
|
export function getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
421
427
|
|
|
422
428
|
/**
|
|
423
|
-
* The same as `
|
|
429
|
+
* The same as `buildSwatches` from a clustering you already have, so trying another `k` costs well under a millisecond.
|
|
424
430
|
* Needs a clustering from 3.x; a 2.x clustering has no weights and is rejected.
|
|
425
431
|
*
|
|
426
432
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -501,7 +507,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
501
507
|
|
|
502
508
|
/**
|
|
503
509
|
* Like `quantize`, but returns each pixel's palette index instead of its colour, with the palette (for palette
|
|
504
|
-
* PNGs, pixel art and pattern generators). The palette is the one `
|
|
510
|
+
* PNGs, pixel art and pattern generators). The palette is the one `buildPalette` gives, except that with `transparent`
|
|
505
511
|
* pixels below the cutoff are left out of it.
|
|
506
512
|
*
|
|
507
513
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
package/dist/index.d.ts
CHANGED
|
@@ -125,7 +125,7 @@ export class Palette extends Uint8Array {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* The bytes of a clustering, as `
|
|
128
|
+
* The bytes of a clustering, as `buildClustering` returns them: an opaque `Uint8Array` (tagged, like `Palette`) that you can
|
|
129
129
|
* store (a file, IndexedDB, next to the image) and cut to a palette of any size later. It is a type of its own, so a
|
|
130
130
|
* clustering can't be passed where a palette goes (or the other way round): TypeScript says so, and at run time a
|
|
131
131
|
* `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
|
|
@@ -200,7 +200,7 @@ export interface ProgressOptions extends CancelOptions {
|
|
|
200
200
|
onProgress?: ((progress: number) => void) | undefined;
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
/** Options for building the colour hierarchy: `
|
|
203
|
+
/** Options for building the colour hierarchy: `buildClustering`, `buildPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
|
|
204
204
|
export interface ClusteringOptions extends ProgressOptions {
|
|
205
205
|
/**
|
|
206
206
|
* `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
|
|
@@ -223,7 +223,7 @@ export interface ClusteringOptions extends ProgressOptions {
|
|
|
223
223
|
* `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
|
|
224
224
|
* below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
|
|
225
225
|
* whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
|
|
226
|
-
* PNG), and it gives the same palette everywhere: `
|
|
226
|
+
* PNG), and it gives the same palette everywhere: `buildPalette(image, k, { transparent })` is the palette
|
|
227
227
|
* `quantizeToIndices(image, k, { transparent })` uses, apart from that function's extra transparent entry.
|
|
228
228
|
* Cluster with it to get the palette you will map with (see `IndexOptions.transparent`). The cutoff is recorded in the
|
|
229
229
|
* clustering (see `ClusteringInfo.transparent`), and `quantizeToIndicesFromClustering` uses it unless you name one.
|
|
@@ -293,7 +293,7 @@ export interface IndexOptions {
|
|
|
293
293
|
* opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
|
|
294
294
|
* transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
|
|
295
295
|
* this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
|
|
296
|
-
* `ClusteringOptions.transparent`), so its palette is `
|
|
296
|
+
* `ClusteringOptions.transparent`), so its palette is `buildPalette(image, k - 1, { transparent })`'s. With a palette
|
|
297
297
|
* you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
|
|
298
298
|
* `quantizeToIndicesFromClustering` the default is the cutoff the clustering was made with.
|
|
299
299
|
*/
|
|
@@ -352,7 +352,7 @@ export interface InitOptions {
|
|
|
352
352
|
export const version: string;
|
|
353
353
|
|
|
354
354
|
/**
|
|
355
|
-
* The version of the data this library stores: the format of the clusterings `
|
|
355
|
+
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`getClusteringInfo`
|
|
356
356
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
357
357
|
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
358
358
|
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
@@ -371,16 +371,20 @@ export function init(options?: InitOptions): Promise<void>;
|
|
|
371
371
|
* cache or store next to the image. Cut it to a palette of any size with `getPaletteFromClustering`, or map pixels
|
|
372
372
|
* with `quantizeFromClustering`. An image with no visible pixels gives a clustering that cuts to an empty palette.
|
|
373
373
|
*/
|
|
374
|
+
export function buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
374
376
|
export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
377
|
|
|
376
378
|
/**
|
|
377
379
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
378
|
-
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `
|
|
380
|
+
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
379
381
|
* once and cut it.
|
|
380
382
|
*
|
|
381
383
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
382
384
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
383
385
|
*/
|
|
386
|
+
export function buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
387
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
384
388
|
export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
385
389
|
|
|
386
390
|
/**
|
|
@@ -417,10 +421,12 @@ export interface Swatches {
|
|
|
417
421
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
418
422
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
419
423
|
*/
|
|
424
|
+
export function buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
425
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
420
426
|
export function getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
421
427
|
|
|
422
428
|
/**
|
|
423
|
-
* The same as `
|
|
429
|
+
* The same as `buildSwatches` from a clustering you already have, so trying another `k` costs well under a millisecond.
|
|
424
430
|
* Needs a clustering from 3.x; a 2.x clustering has no weights and is rejected.
|
|
425
431
|
*
|
|
426
432
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -501,7 +507,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
501
507
|
|
|
502
508
|
/**
|
|
503
509
|
* Like `quantize`, but returns each pixel's palette index instead of its colour, with the palette (for palette
|
|
504
|
-
* PNGs, pixel art and pattern generators). The palette is the one `
|
|
510
|
+
* PNGs, pixel art and pattern generators). The palette is the one `buildPalette` gives, except that with `transparent`
|
|
505
511
|
* pixels below the cutoff are left out of it.
|
|
506
512
|
*
|
|
507
513
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
package/dist/index.mjs
CHANGED
|
@@ -478,7 +478,7 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
478
478
|
};
|
|
479
479
|
const load = image => {
|
|
480
480
|
if (isClustering(image) || isPalette(image)) {
|
|
481
|
-
const what = isClustering(image) ? 'a clustering (from
|
|
481
|
+
const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
482
482
|
const fix = isClustering(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
483
483
|
throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
484
484
|
}
|
|
@@ -637,7 +637,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
637
637
|
options = snapshot(options);
|
|
638
638
|
for (const key of Object.keys(options)) {
|
|
639
639
|
if (!allowed.includes(key)) {
|
|
640
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
640
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal: they finish in milliseconds, with no progress to report.' : '';
|
|
641
641
|
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
642
642
|
}
|
|
643
643
|
}
|
|
@@ -901,7 +901,7 @@ const noOptions = (name, extra) => {
|
|
|
901
901
|
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
902
902
|
// happens before the call returns.
|
|
903
903
|
|
|
904
|
-
export const
|
|
904
|
+
export const buildClustering = async (image, options) => {
|
|
905
905
|
image = load(image);
|
|
906
906
|
const o = parseOptions(options, clusterOptions, image);
|
|
907
907
|
const wasm = Module || (await acquire());
|
|
@@ -913,7 +913,9 @@ export const getClustering = async (image, options) => {
|
|
|
913
913
|
}
|
|
914
914
|
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));
|
|
915
915
|
};
|
|
916
|
-
|
|
916
|
+
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
917
|
+
export const getClustering = buildClustering;
|
|
918
|
+
export const buildPalette = async (image, k, options) => {
|
|
917
919
|
image = load(image);
|
|
918
920
|
k = check(k);
|
|
919
921
|
const o = parseOptions(options, clusterOptions, image);
|
|
@@ -928,6 +930,8 @@ export const getPalette = async (image, k, options) => {
|
|
|
928
930
|
}
|
|
929
931
|
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));
|
|
930
932
|
};
|
|
933
|
+
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
934
|
+
export const getPalette = buildPalette;
|
|
931
935
|
|
|
932
936
|
// The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
|
|
933
937
|
const cutPalette = async (name, clustering, k, extra) => {
|
|
@@ -988,12 +992,14 @@ const cutSwatches = async (name, clustering, k, extra) => {
|
|
|
988
992
|
export const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
|
|
989
993
|
|
|
990
994
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
991
|
-
export const
|
|
995
|
+
export const buildSwatches = async (image, k, options) => {
|
|
992
996
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
993
997
|
load(image);
|
|
994
998
|
k = check(k);
|
|
995
|
-
return getSwatchesFromClustering(await
|
|
999
|
+
return getSwatchesFromClustering(await buildClustering(image, options), k);
|
|
996
1000
|
};
|
|
1001
|
+
/** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
|
|
1002
|
+
export const getSwatches = buildSwatches;
|
|
997
1003
|
|
|
998
1004
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
999
1005
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
package/dist/shared.cjs
CHANGED
|
@@ -13,7 +13,7 @@ exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = expor
|
|
|
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.
|
|
16
|
+
const version = exports.version = '3.4.0';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -470,7 +470,7 @@ function Clustering(...args) {
|
|
|
470
470
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
471
471
|
const isBuffer = isArrayBufferLike(source);
|
|
472
472
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
473
|
-
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from
|
|
473
|
+
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from buildClustering.", 'clustering');
|
|
474
474
|
}
|
|
475
475
|
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
476
476
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
@@ -549,26 +549,26 @@ const crc32 = bytes => {
|
|
|
549
549
|
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
550
550
|
};
|
|
551
551
|
const checked = new WeakSet();
|
|
552
|
-
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after
|
|
552
|
+
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after buildClustering made it. Cluster the image again.", 'clustering');
|
|
553
553
|
|
|
554
554
|
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
555
555
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
556
556
|
const notAClustering = clustering => {
|
|
557
557
|
const length = clustering.length;
|
|
558
558
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
559
|
-
return fail('invalid-clustering', "Invalid clustering: not a clustering from
|
|
559
|
+
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
560
560
|
}
|
|
561
561
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
562
562
|
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
563
563
|
}
|
|
564
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from
|
|
564
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
565
565
|
};
|
|
566
566
|
const readHeader = clustering => {
|
|
567
567
|
if (isPalette(clustering)) {
|
|
568
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from
|
|
568
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
|
|
569
569
|
}
|
|
570
570
|
if (!isUint8Array(clustering)) {
|
|
571
|
-
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from
|
|
571
|
+
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
572
572
|
}
|
|
573
573
|
const length = clustering.length;
|
|
574
574
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
@@ -632,7 +632,7 @@ const readHeader = clustering => {
|
|
|
632
632
|
exports.readHeader = readHeader;
|
|
633
633
|
const checkPalette = palette => {
|
|
634
634
|
if (isClustering(palette)) {
|
|
635
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from
|
|
635
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
|
|
636
636
|
}
|
|
637
637
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
638
638
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
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.
|
|
7
|
+
export const version = '3.4.0';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -436,7 +436,7 @@ export function Clustering(...args) {
|
|
|
436
436
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
437
437
|
const isBuffer = isArrayBufferLike(source);
|
|
438
438
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
439
|
-
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from
|
|
439
|
+
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from buildClustering.", 'clustering');
|
|
440
440
|
}
|
|
441
441
|
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
442
442
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
@@ -515,26 +515,26 @@ const crc32 = bytes => {
|
|
|
515
515
|
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
516
516
|
};
|
|
517
517
|
const checked = new WeakSet();
|
|
518
|
-
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after
|
|
518
|
+
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after buildClustering made it. Cluster the image again.", 'clustering');
|
|
519
519
|
|
|
520
520
|
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
521
521
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
522
522
|
const notAClustering = clustering => {
|
|
523
523
|
const length = clustering.length;
|
|
524
524
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
525
|
-
return fail('invalid-clustering', "Invalid clustering: not a clustering from
|
|
525
|
+
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
526
526
|
}
|
|
527
527
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
528
528
|
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
529
529
|
}
|
|
530
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from
|
|
530
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
531
531
|
};
|
|
532
532
|
export const readHeader = clustering => {
|
|
533
533
|
if (isPalette(clustering)) {
|
|
534
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from
|
|
534
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
|
|
535
535
|
}
|
|
536
536
|
if (!isUint8Array(clustering)) {
|
|
537
|
-
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from
|
|
537
|
+
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
538
538
|
}
|
|
539
539
|
const length = clustering.length;
|
|
540
540
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
@@ -597,7 +597,7 @@ export const readHeader = clustering => {
|
|
|
597
597
|
// image, and quantize maps such an image the same way.
|
|
598
598
|
export const checkPalette = palette => {
|
|
599
599
|
if (isClustering(palette)) {
|
|
600
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from
|
|
600
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
|
|
601
601
|
}
|
|
602
602
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
603
603
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -109,20 +109,29 @@ const nextTurn = typeof setImmediate === 'function' ? () => new Promise(resolve
|
|
|
109
109
|
channel.port2.postMessage(null);
|
|
110
110
|
});
|
|
111
111
|
})() : () => new Promise(resolve => setTimeout(resolve, 0));
|
|
112
|
+
|
|
113
|
+
// A call sent only to check its arguments (its caller's signal was aborted before it was made): it runs with a signal that
|
|
114
|
+
// is already aborted, so the main entry validates the arguments, reports the first wrong one, and does no work.
|
|
115
|
+
const alreadyAborted = () => {
|
|
116
|
+
const controller = new AbortController();
|
|
117
|
+
controller.abort();
|
|
118
|
+
return controller;
|
|
119
|
+
};
|
|
112
120
|
const respond = async ({
|
|
113
121
|
id,
|
|
114
122
|
method,
|
|
115
123
|
args,
|
|
116
|
-
progress
|
|
124
|
+
progress,
|
|
125
|
+
check
|
|
117
126
|
}, post) => {
|
|
118
|
-
const controller = controllers.get(id);
|
|
127
|
+
const controller = check ? alreadyAborted() : controllers.get(id);
|
|
119
128
|
try {
|
|
120
129
|
// The call before this one may have run in one piece (mapping does), with no turn of the event loop for a cancel
|
|
121
130
|
// of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
|
|
122
131
|
if (controller && !controller.signal.aborted) {
|
|
123
132
|
await nextTurn();
|
|
124
133
|
}
|
|
125
|
-
if (controller && controller.signal.aborted) {
|
|
134
|
+
if (controller && controller.signal.aborted && !check) {
|
|
126
135
|
return;
|
|
127
136
|
}
|
|
128
137
|
if (!Object.prototype.hasOwnProperty.call(methods, method)) {
|
|
@@ -153,8 +162,8 @@ const respond = async ({
|
|
|
153
162
|
result
|
|
154
163
|
}, [...new Set(buffers(result))]);
|
|
155
164
|
} catch (error) {
|
|
156
|
-
// A cancelled call has already been rejected on the other side.
|
|
157
|
-
if (controller && controller.signal.aborted) {
|
|
165
|
+
// A cancelled call has already been rejected on the other side (a check reports what it found).
|
|
166
|
+
if (controller && controller.signal.aborted && !check) {
|
|
158
167
|
return;
|
|
159
168
|
}
|
|
160
169
|
// Errors cross as plain data: the caller's side rebuilds them with the same name, message and code.
|
|
@@ -189,6 +198,13 @@ const onMessage = (data, post) => {
|
|
|
189
198
|
}
|
|
190
199
|
return;
|
|
191
200
|
}
|
|
201
|
+
// A check runs at once, beside whatever is running: its caller has already aborted, so it must not wait for other calls.
|
|
202
|
+
// It only validates: every function checks its signal before it puts anything in the WebAssembly heap, so it can't
|
|
203
|
+
// disturb a clustering running in slices, or grow the heap.
|
|
204
|
+
if (data.check) {
|
|
205
|
+
respond(data, post).catch(() => {});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
192
208
|
if (data.cancellable) {
|
|
193
209
|
controllers.set(data.id, new AbortController());
|
|
194
210
|
}
|
package/dist/worker.cjs
CHANGED
|
@@ -23,6 +23,7 @@ Object.defineProperty(exports, "alphaModes", {
|
|
|
23
23
|
return _shared.alphaModes;
|
|
24
24
|
}
|
|
25
25
|
});
|
|
26
|
+
exports.buildSwatches = exports.buildPalette = exports.buildClustering = void 0;
|
|
26
27
|
Object.defineProperty(exports, "colorSpaces", {
|
|
27
28
|
enumerable: true,
|
|
28
29
|
get: function () {
|
|
@@ -491,15 +492,46 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
491
492
|
if (options.dither !== null && (typeof options.dither === 'object' || typeof options.dither === 'function' || typeof options.dither === 'symbol')) {
|
|
492
493
|
// One read of each setting (a getter could answer differently twice): the copy is what is checked and sent.
|
|
493
494
|
const copy = (0, _shared.isOptionsObject)(options.dither) ? Object.assign({}, (0, _shared.snapshot)(options.dither)) : options.dither;
|
|
494
|
-
|
|
495
|
+
// A wrong setting is the worker's to report, after the image and k, as the main entry orders its checks. Only a
|
|
496
|
+
// copy that can't be sent is reported here.
|
|
497
|
+
try {
|
|
498
|
+
(0, _shared.parseDither)(copy);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
if (!sendable(copy)) {
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
495
504
|
options.dither = copy;
|
|
496
505
|
}
|
|
506
|
+
// The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
|
|
507
|
+
// A wrong one (or a callback where only a signal is taken) crosses as `null` instead, which the worker's validation
|
|
508
|
+
// rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
|
|
509
|
+
// those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
|
|
497
510
|
const {
|
|
498
511
|
signal,
|
|
499
512
|
onProgress
|
|
500
513
|
} = options;
|
|
501
|
-
|
|
502
|
-
|
|
514
|
+
const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
|
|
515
|
+
const badProgress = onProgress !== undefined && (!progressAllowed || typeof onProgress !== 'function');
|
|
516
|
+
const {
|
|
517
|
+
signal: _signal,
|
|
518
|
+
onProgress: _onProgress,
|
|
519
|
+
...rest
|
|
520
|
+
} = options;
|
|
521
|
+
if (badSignal || badProgress) {
|
|
522
|
+
return {
|
|
523
|
+
options: {
|
|
524
|
+
...rest,
|
|
525
|
+
...(badSignal ? {
|
|
526
|
+
signal: null
|
|
527
|
+
} : {}),
|
|
528
|
+
...(badProgress ? {
|
|
529
|
+
onProgress: null
|
|
530
|
+
} : {})
|
|
531
|
+
},
|
|
532
|
+
signal: undefined,
|
|
533
|
+
onProgress: undefined
|
|
534
|
+
};
|
|
503
535
|
}
|
|
504
536
|
if (signal === undefined && onProgress === undefined) {
|
|
505
537
|
return {
|
|
@@ -508,17 +540,6 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
508
540
|
onProgress
|
|
509
541
|
};
|
|
510
542
|
}
|
|
511
|
-
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
512
|
-
throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
513
|
-
}
|
|
514
|
-
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
515
|
-
throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
516
|
-
}
|
|
517
|
-
const {
|
|
518
|
-
signal: _signal,
|
|
519
|
-
onProgress: _onProgress,
|
|
520
|
-
...rest
|
|
521
|
-
} = options;
|
|
522
543
|
return {
|
|
523
544
|
options: rest,
|
|
524
545
|
signal,
|
|
@@ -526,6 +547,19 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
526
547
|
};
|
|
527
548
|
};
|
|
528
549
|
|
|
550
|
+
// Whether a value survives being posted to the worker.
|
|
551
|
+
const sendable = value => {
|
|
552
|
+
if (typeof structuredClone !== 'function') {
|
|
553
|
+
return true;
|
|
554
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
structuredClone(value);
|
|
557
|
+
return true;
|
|
558
|
+
} catch (error) {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
|
|
529
563
|
// Where the options sit among a function's arguments after the image (see takeControls).
|
|
530
564
|
const optionsPosition = {
|
|
531
565
|
getClustering: 0,
|
|
@@ -764,7 +798,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
764
798
|
};
|
|
765
799
|
const post = (method, args, transferable, origin, {
|
|
766
800
|
signal,
|
|
767
|
-
onProgress
|
|
801
|
+
onProgress,
|
|
802
|
+
check
|
|
768
803
|
} = {}) => {
|
|
769
804
|
if (terminated) {
|
|
770
805
|
return Promise.reject((0, _shared.fail)('worker-terminated', "Worker terminated."));
|
|
@@ -813,7 +848,10 @@ const makeWorker = (options, allowScript) => {
|
|
|
813
848
|
method,
|
|
814
849
|
args: args.map(_shared.mark),
|
|
815
850
|
cancellable: signal !== undefined || onProgress !== undefined,
|
|
816
|
-
progress: onProgress !== undefined
|
|
851
|
+
progress: onProgress !== undefined,
|
|
852
|
+
...(check ? {
|
|
853
|
+
check
|
|
854
|
+
} : {})
|
|
817
855
|
};
|
|
818
856
|
try {
|
|
819
857
|
connection.post(message, transfer ? transferable : []);
|
|
@@ -851,14 +889,24 @@ const makeWorker = (options, allowScript) => {
|
|
|
851
889
|
signal,
|
|
852
890
|
onProgress
|
|
853
891
|
} = takeControls(rest[position], !mappingOnlyFunctions.includes(name), !clusteringOnlyFunctions.includes(name));
|
|
854
|
-
// Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
|
|
855
|
-
if (signal && signal.aborted) {
|
|
856
|
-
throw abortReason(signal);
|
|
857
|
-
}
|
|
858
892
|
let args = rest.slice();
|
|
859
893
|
if (position < args.length) {
|
|
860
894
|
args[position] = options;
|
|
861
895
|
}
|
|
896
|
+
if (signal && signal.aborted) {
|
|
897
|
+
// The main entry reports a wrong argument before an abort, so the worker checks the arguments (a
|
|
898
|
+
// copy, never transferred: an aborted call leaves the image with the caller) without doing the work.
|
|
899
|
+
try {
|
|
900
|
+
await invoke(name, [own(send(image)), ...args.map(own)], [], origin, {
|
|
901
|
+
check: true
|
|
902
|
+
});
|
|
903
|
+
} catch (error) {
|
|
904
|
+
if ((0, _shared.isCodedError)(error) && error.argument !== undefined) {
|
|
905
|
+
throw error;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
throw abortReason(signal);
|
|
909
|
+
}
|
|
862
910
|
let sent = send(image);
|
|
863
911
|
if (!ready()) {
|
|
864
912
|
sent = take(sent);
|
|
@@ -875,6 +923,11 @@ const makeWorker = (options, allowScript) => {
|
|
|
875
923
|
for (const name of otherFunctions) {
|
|
876
924
|
instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
|
|
877
925
|
}
|
|
926
|
+
// 3.4.0's names for the functions that cluster an image. The old names are the same functions, and they still name the
|
|
927
|
+
// call on the wire, so a worker script copied from an older version still understands it.
|
|
928
|
+
instance.buildClustering = instance.getClustering;
|
|
929
|
+
instance.buildPalette = instance.getPalette;
|
|
930
|
+
instance.buildSwatches = instance.getSwatches;
|
|
878
931
|
instance.init = initArgs => {
|
|
879
932
|
const origin = new Error();
|
|
880
933
|
let checked;
|
|
@@ -1052,14 +1105,17 @@ const terminate = async () => {
|
|
|
1052
1105
|
exports.terminate = terminate;
|
|
1053
1106
|
const init = (...args) => sharedWorker().init(...args);
|
|
1054
1107
|
exports.init = init;
|
|
1055
|
-
const
|
|
1056
|
-
exports.
|
|
1057
|
-
const
|
|
1058
|
-
|
|
1108
|
+
const buildClustering = (...args) => sharedWorker().buildClustering(...args);
|
|
1109
|
+
exports.buildClustering = buildClustering;
|
|
1110
|
+
const getClustering = exports.getClustering = buildClustering;
|
|
1111
|
+
const buildPalette = (...args) => sharedWorker().buildPalette(...args);
|
|
1112
|
+
exports.buildPalette = buildPalette;
|
|
1113
|
+
const getPalette = exports.getPalette = buildPalette;
|
|
1059
1114
|
const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
|
|
1060
1115
|
exports.getPaletteFromClustering = getPaletteFromClustering;
|
|
1061
|
-
const
|
|
1062
|
-
exports.
|
|
1116
|
+
const buildSwatches = (...args) => sharedWorker().buildSwatches(...args);
|
|
1117
|
+
exports.buildSwatches = buildSwatches;
|
|
1118
|
+
const getSwatches = exports.getSwatches = buildSwatches;
|
|
1063
1119
|
const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
|
|
1064
1120
|
exports.getSwatchesFromClustering = getSwatchesFromClustering;
|
|
1065
1121
|
const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
|
package/dist/worker.d.cts
CHANGED
|
@@ -92,9 +92,18 @@ export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
|
|
|
92
92
|
export interface AgglomerativeWorker {
|
|
93
93
|
/** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
|
|
94
94
|
init(options?: InitOptions): Promise<void>;
|
|
95
|
+
/** The main entry's `buildClustering`, run in this worker. */
|
|
96
|
+
buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
97
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
95
98
|
getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
99
|
+
/** The main entry's `buildPalette`, run in this worker. */
|
|
100
|
+
buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
101
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
96
102
|
getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
97
103
|
getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
104
|
+
/** The main entry's `buildSwatches`, run in this worker. */
|
|
105
|
+
buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
106
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
98
107
|
getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
99
108
|
getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
100
109
|
getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
@@ -129,13 +138,19 @@ export function terminate(): Promise<void>;
|
|
|
129
138
|
* shared worker's `script`, before any other call.
|
|
130
139
|
*/
|
|
131
140
|
export function init(options?: SharedInitOptions): Promise<void>;
|
|
132
|
-
/** The main entry's `
|
|
141
|
+
/** The main entry's `buildClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
142
|
+
export const buildClustering: AgglomerativeWorker['buildClustering'];
|
|
143
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
133
144
|
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
134
|
-
/** The main entry's `
|
|
145
|
+
/** The main entry's `buildPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
146
|
+
export const buildPalette: AgglomerativeWorker['buildPalette'];
|
|
147
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
135
148
|
export const getPalette: AgglomerativeWorker['getPalette'];
|
|
136
149
|
/** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
137
150
|
export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
|
|
138
|
-
/** The main entry's `
|
|
151
|
+
/** The main entry's `buildSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
152
|
+
export const buildSwatches: AgglomerativeWorker['buildSwatches'];
|
|
153
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
139
154
|
export const getSwatches: AgglomerativeWorker['getSwatches'];
|
|
140
155
|
/** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
141
156
|
export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
|
package/dist/worker.d.ts
CHANGED
|
@@ -92,9 +92,18 @@ export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
|
|
|
92
92
|
export interface AgglomerativeWorker {
|
|
93
93
|
/** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
|
|
94
94
|
init(options?: InitOptions): Promise<void>;
|
|
95
|
+
/** The main entry's `buildClustering`, run in this worker. */
|
|
96
|
+
buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
97
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
95
98
|
getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
99
|
+
/** The main entry's `buildPalette`, run in this worker. */
|
|
100
|
+
buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
101
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
96
102
|
getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
97
103
|
getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
104
|
+
/** The main entry's `buildSwatches`, run in this worker. */
|
|
105
|
+
buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
106
|
+
/** @deprecated Renamed {@link AgglomerativeWorker.buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
98
107
|
getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
99
108
|
getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
100
109
|
getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
@@ -129,13 +138,19 @@ export function terminate(): Promise<void>;
|
|
|
129
138
|
* shared worker's `script`, before any other call.
|
|
130
139
|
*/
|
|
131
140
|
export function init(options?: SharedInitOptions): Promise<void>;
|
|
132
|
-
/** The main entry's `
|
|
141
|
+
/** The main entry's `buildClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
142
|
+
export const buildClustering: AgglomerativeWorker['buildClustering'];
|
|
143
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
133
144
|
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
134
|
-
/** The main entry's `
|
|
145
|
+
/** The main entry's `buildPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
146
|
+
export const buildPalette: AgglomerativeWorker['buildPalette'];
|
|
147
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
135
148
|
export const getPalette: AgglomerativeWorker['getPalette'];
|
|
136
149
|
/** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
137
150
|
export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
|
|
138
|
-
/** The main entry's `
|
|
151
|
+
/** The main entry's `buildSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
152
|
+
export const buildSwatches: AgglomerativeWorker['buildSwatches'];
|
|
153
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
139
154
|
export const getSwatches: AgglomerativeWorker['getSwatches'];
|
|
140
155
|
/** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
141
156
|
export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
|
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, 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 } 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";
|
|
@@ -423,15 +423,46 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
423
423
|
if (options.dither !== null && (typeof options.dither === 'object' || typeof options.dither === 'function' || typeof options.dither === 'symbol')) {
|
|
424
424
|
// One read of each setting (a getter could answer differently twice): the copy is what is checked and sent.
|
|
425
425
|
const copy = isOptionsObject(options.dither) ? Object.assign({}, snapshot(options.dither)) : options.dither;
|
|
426
|
-
|
|
426
|
+
// A wrong setting is the worker's to report, after the image and k, as the main entry orders its checks. Only a
|
|
427
|
+
// copy that can't be sent is reported here.
|
|
428
|
+
try {
|
|
429
|
+
parseDither(copy);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (!sendable(copy)) {
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
427
435
|
options.dither = copy;
|
|
428
436
|
}
|
|
437
|
+
// The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
|
|
438
|
+
// A wrong one (or a callback where only a signal is taken) crosses as `null` instead, which the worker's validation
|
|
439
|
+
// rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
|
|
440
|
+
// those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
|
|
429
441
|
const {
|
|
430
442
|
signal,
|
|
431
443
|
onProgress
|
|
432
444
|
} = options;
|
|
433
|
-
|
|
434
|
-
|
|
445
|
+
const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
|
|
446
|
+
const badProgress = onProgress !== undefined && (!progressAllowed || typeof onProgress !== 'function');
|
|
447
|
+
const {
|
|
448
|
+
signal: _signal,
|
|
449
|
+
onProgress: _onProgress,
|
|
450
|
+
...rest
|
|
451
|
+
} = options;
|
|
452
|
+
if (badSignal || badProgress) {
|
|
453
|
+
return {
|
|
454
|
+
options: {
|
|
455
|
+
...rest,
|
|
456
|
+
...(badSignal ? {
|
|
457
|
+
signal: null
|
|
458
|
+
} : {}),
|
|
459
|
+
...(badProgress ? {
|
|
460
|
+
onProgress: null
|
|
461
|
+
} : {})
|
|
462
|
+
},
|
|
463
|
+
signal: undefined,
|
|
464
|
+
onProgress: undefined
|
|
465
|
+
};
|
|
435
466
|
}
|
|
436
467
|
if (signal === undefined && onProgress === undefined) {
|
|
437
468
|
return {
|
|
@@ -440,17 +471,6 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
440
471
|
onProgress
|
|
441
472
|
};
|
|
442
473
|
}
|
|
443
|
-
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
444
|
-
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
445
|
-
}
|
|
446
|
-
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
447
|
-
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
448
|
-
}
|
|
449
|
-
const {
|
|
450
|
-
signal: _signal,
|
|
451
|
-
onProgress: _onProgress,
|
|
452
|
-
...rest
|
|
453
|
-
} = options;
|
|
454
474
|
return {
|
|
455
475
|
options: rest,
|
|
456
476
|
signal,
|
|
@@ -458,6 +478,19 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
458
478
|
};
|
|
459
479
|
};
|
|
460
480
|
|
|
481
|
+
// Whether a value survives being posted to the worker.
|
|
482
|
+
const sendable = value => {
|
|
483
|
+
if (typeof structuredClone !== 'function') {
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
486
|
+
try {
|
|
487
|
+
structuredClone(value);
|
|
488
|
+
return true;
|
|
489
|
+
} catch (error) {
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
461
494
|
// Where the options sit among a function's arguments after the image (see takeControls).
|
|
462
495
|
const optionsPosition = {
|
|
463
496
|
getClustering: 0,
|
|
@@ -696,7 +729,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
696
729
|
};
|
|
697
730
|
const post = (method, args, transferable, origin, {
|
|
698
731
|
signal,
|
|
699
|
-
onProgress
|
|
732
|
+
onProgress,
|
|
733
|
+
check
|
|
700
734
|
} = {}) => {
|
|
701
735
|
if (terminated) {
|
|
702
736
|
return Promise.reject(fail('worker-terminated', "Worker terminated."));
|
|
@@ -745,7 +779,10 @@ const makeWorker = (options, allowScript) => {
|
|
|
745
779
|
method,
|
|
746
780
|
args: args.map(mark),
|
|
747
781
|
cancellable: signal !== undefined || onProgress !== undefined,
|
|
748
|
-
progress: onProgress !== undefined
|
|
782
|
+
progress: onProgress !== undefined,
|
|
783
|
+
...(check ? {
|
|
784
|
+
check
|
|
785
|
+
} : {})
|
|
749
786
|
};
|
|
750
787
|
try {
|
|
751
788
|
connection.post(message, transfer ? transferable : []);
|
|
@@ -783,14 +820,24 @@ const makeWorker = (options, allowScript) => {
|
|
|
783
820
|
signal,
|
|
784
821
|
onProgress
|
|
785
822
|
} = takeControls(rest[position], !mappingOnlyFunctions.includes(name), !clusteringOnlyFunctions.includes(name));
|
|
786
|
-
// Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
|
|
787
|
-
if (signal && signal.aborted) {
|
|
788
|
-
throw abortReason(signal);
|
|
789
|
-
}
|
|
790
823
|
let args = rest.slice();
|
|
791
824
|
if (position < args.length) {
|
|
792
825
|
args[position] = options;
|
|
793
826
|
}
|
|
827
|
+
if (signal && signal.aborted) {
|
|
828
|
+
// The main entry reports a wrong argument before an abort, so the worker checks the arguments (a
|
|
829
|
+
// copy, never transferred: an aborted call leaves the image with the caller) without doing the work.
|
|
830
|
+
try {
|
|
831
|
+
await invoke(name, [own(send(image)), ...args.map(own)], [], origin, {
|
|
832
|
+
check: true
|
|
833
|
+
});
|
|
834
|
+
} catch (error) {
|
|
835
|
+
if (isCodedError(error) && error.argument !== undefined) {
|
|
836
|
+
throw error;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
throw abortReason(signal);
|
|
840
|
+
}
|
|
794
841
|
let sent = send(image);
|
|
795
842
|
if (!ready()) {
|
|
796
843
|
sent = take(sent);
|
|
@@ -807,6 +854,11 @@ const makeWorker = (options, allowScript) => {
|
|
|
807
854
|
for (const name of otherFunctions) {
|
|
808
855
|
instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
|
|
809
856
|
}
|
|
857
|
+
// 3.4.0's names for the functions that cluster an image. The old names are the same functions, and they still name the
|
|
858
|
+
// call on the wire, so a worker script copied from an older version still understands it.
|
|
859
|
+
instance.buildClustering = instance.getClustering;
|
|
860
|
+
instance.buildPalette = instance.getPalette;
|
|
861
|
+
instance.buildSwatches = instance.getSwatches;
|
|
810
862
|
instance.init = initArgs => {
|
|
811
863
|
const origin = new Error();
|
|
812
864
|
let checked;
|
|
@@ -981,10 +1033,13 @@ export const terminate = async () => {
|
|
|
981
1033
|
await stopping.terminate();
|
|
982
1034
|
};
|
|
983
1035
|
export const init = (...args) => sharedWorker().init(...args);
|
|
984
|
-
export const
|
|
985
|
-
export const
|
|
1036
|
+
export const buildClustering = (...args) => sharedWorker().buildClustering(...args);
|
|
1037
|
+
export const getClustering = buildClustering;
|
|
1038
|
+
export const buildPalette = (...args) => sharedWorker().buildPalette(...args);
|
|
1039
|
+
export const getPalette = buildPalette;
|
|
986
1040
|
export const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
|
|
987
|
-
export const
|
|
1041
|
+
export const buildSwatches = (...args) => sharedWorker().buildSwatches(...args);
|
|
1042
|
+
export const getSwatches = buildSwatches;
|
|
988
1043
|
export const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
|
|
989
1044
|
export const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
|
|
990
1045
|
export const quantize = (...args) => sharedWorker().quantize(...args);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.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",
|