agglomerative-clustering 3.7.1 → 3.8.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/dist/index.d.ts CHANGED
@@ -147,16 +147,33 @@ export class Clustering extends Uint8Array {
147
147
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
148
148
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
149
149
  readonly [clusteringBrand]: true;
150
- /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
150
+ /** The k-colour palette of this clustering. Takes no options. Runs on the calling thread, with the main entry. */
151
151
  getPalette(this: Clustering, k: number): Promise<Palette>;
152
- /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
152
+ /** Palette, weights and shares of the k-colour cut. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
153
  getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
- /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
154
+ /** The error curve and totals of this clustering. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
155
  getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
- /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
156
+ /** Maps `image` to this clustering's k-colour palette, returning the image's type. Runs on the calling thread, with the main entry. */
157
157
  quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
- /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
158
+ /** Maps `image` to this clustering's k-colour palette as palette indices. Runs on the calling thread, with the main entry. */
159
159
  quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
160
+ /** Chooses the k entries of `palette` that best represent the clustered image: their positions and colours. Runs on the calling thread, with the main entry. */
161
+ chooseFrom(this: Clustering, palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
162
+ }
163
+
164
+ /** Options of `clustering.chooseFrom`. */
165
+ export interface ChooseOptions {
166
+ /** The space the search measures distance in: 'rgb' (default) or 'oklab'. It doesn't follow the clustering's space. */
167
+ colorSpace?: ColorSpace | undefined;
168
+ signal?: AbortSignal | undefined;
169
+ }
170
+
171
+ /** What `clustering.chooseFrom` returns. */
172
+ export interface PaletteChoice {
173
+ /** Exactly k positions in the palette given, ascending: no ranking (count the mapped pixels for a legend). */
174
+ indices: number[];
175
+ /** The chosen colours, in the order of `indices`: map with it, and index s of the result is entry indices[s]. */
176
+ palette: Palette;
160
177
  }
161
178
 
162
179
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
@@ -375,7 +392,7 @@ export function getClustering(image: ImageLike, options?: ClusteringOptions): Pr
375
392
 
376
393
  /**
377
394
  * 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 `buildClustering`
395
+ * order (see `clustering.getPalette(k)`). It clusters the image each time: to try several sizes, call `buildClustering`
379
396
  * once and cut it.
380
397
  *
381
398
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
@@ -392,6 +409,8 @@ export function getPalette(image: ImageLike, k: number, options?: ClusteringOpti
392
409
  *
393
410
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
394
411
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
412
+ *
413
+ * @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
395
414
  */
396
415
  export function getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
397
416
 
@@ -400,7 +419,7 @@ export function getPaletteFromClustering(clustering: Clustering, k: number): Pro
400
419
  * from one cut of one clustering, so they line up by construction: entry `i` of each describes the same colour.
401
420
  */
402
421
  export interface Swatches {
403
- /** The colours in split order, exactly what `getPaletteFromClustering` gives for the same `k`. */
422
+ /** The colours in split order, exactly what `clustering.getPalette(k)` gives for the same `k`. */
404
423
  palette: Palette;
405
424
  /**
406
425
  * Pixels per colour, counted as in clustering: by default fully transparent pixels count 0 and partly transparent ones
@@ -414,7 +433,7 @@ export interface Swatches {
414
433
 
415
434
  /**
416
435
  * The palette for `image` at `k` colours with each colour's weight and share: one call for swatches with percentages.
417
- * It clusters the image each time; if you already have a clustering, use `getSwatchesFromClustering`.
436
+ * It clusters the image each time; if you already have a clustering, use `clustering.getSwatches(k)`.
418
437
  *
419
438
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
420
439
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
@@ -429,6 +448,8 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
429
448
  *
430
449
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
431
450
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
451
+ *
452
+ * @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
432
453
  */
433
454
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
434
455
 
@@ -470,8 +491,10 @@ export interface ClusteringInfo {
470
491
 
471
492
  /**
472
493
  * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
473
- * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
494
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `clustering.getSwatches(k)` rejects it);
474
495
  * the palette and mapping functions still read it.
496
+ *
497
+ * @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
475
498
  */
476
499
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
477
500
 
@@ -492,6 +515,8 @@ export function quantize<I extends ImageLike>(image: I, k: number, options?: Qua
492
515
  *
493
516
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
494
517
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
518
+ *
519
+ * @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
495
520
  */
496
521
  export function quantizeFromClustering<I extends ImageLike>(image: I, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
497
522
 
@@ -516,12 +541,14 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
516
541
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
517
542
 
518
543
  /**
519
- * Like `quantizeFromClustering`, but returns palette indices. The palette is `getPaletteFromClustering`'s.
544
+ * Like `quantizeFromClustering`, but returns palette indices. The palette is `clustering.getPalette(k)`'s.
520
545
  *
521
546
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
522
547
  * 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.
523
548
  * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
524
549
  * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
550
+ *
551
+ * @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
525
552
  */
526
553
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
527
554
 
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
+ import { choose } from "./choose.mjs";
2
3
  import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge, sniffImageFormat, bareImageWarning, warnOnce } from "./shared.mjs";
3
4
 
4
5
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
@@ -93,6 +94,10 @@ const wasmSettings = (wasm, onError) => {
93
94
  throw fail('invalid-argument', "Invalid wasm: must be a URL or path string, a URL, an ArrayBuffer or typed array of the .wasm bytes, or a WebAssembly.Module.", 'options.wasm');
94
95
  };
95
96
 
97
+ // How each engine words a URL that can't be resolved: Chromium and Node "Invalid URL", Firefox "… is not a valid URL",
98
+ // WebKit "… cannot be parsed as a URL".
99
+ const badUrl = /Invalid URL|not a valid URL|cannot be parsed as a URL/i;
100
+
96
101
  // A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
97
102
  // bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
98
103
  // says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
@@ -185,16 +190,21 @@ const wasmLoadFailed = (cause, given, gzipped = false) => {
185
190
  advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
186
191
  } else if (isNodeLike) {
187
192
  // The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
188
- if (/Invalid URL/i.test(reason)) {
193
+ if (badUrl.test(reason)) {
189
194
  reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
190
195
  }
191
196
  advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
192
197
  } else if (!isBrowserLike()) {
193
198
  // A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
194
- if (/Invalid URL/i.test(reason)) {
199
+ if (badUrl.test(reason)) {
195
200
  reason = "the package can't tell where clustering.wasm is in this runtime";
196
201
  }
197
202
  advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the docs show how for Cloudflare Workers and Next.js: https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md); elsewhere its bytes or URL.";
203
+ } else if (badUrl.test(reason) && /^(data|blob|about):$/.test(String(globalThis.location && globalThis.location.protocol))) {
204
+ // The code runs from a data: or blob: URL (a bundled worker script in a single-file host) or an about:srcdoc page, so
205
+ // there is nothing to find clustering.wasm next to. (In a worker, location is the worker script's own URL.)
206
+ reason = `the package can't tell where clustering.wasm is: it runs from a ${globalThis.location.protocol} URL, with nothing next to it (${reason})`;
207
+ advice = "Pass the module itself: createWorker({ script, wasm: bytes }) for a worker you start, init({ wasm: bytes }) for the main entry or the worker entry's shared worker (the bytes, a URL, or a compiled module; see \"Plugins and single-file hosts\" in https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
198
208
  } else {
199
209
  advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
200
210
  }
@@ -1233,11 +1243,57 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1233
1243
  return result;
1234
1244
  };
1235
1245
 
1246
+ // clustering.chooseFrom: validates everything before its first await (the palette is copied, so the caller may change it
1247
+ // at once), then runs the search in choose.js on this thread with the cuts above.
1248
+ const chooseFrom = async (name, clustering, palette, k, options) => {
1249
+ const header = readHeader(clustering);
1250
+ checkPalette(palette);
1251
+ if (palette.length === 0) {
1252
+ throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1253
+ }
1254
+ const entries = Uint8Array.from(palette);
1255
+ const count = entries.length / 3;
1256
+ k = check(k);
1257
+ if (k > count) {
1258
+ throw fail('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
1259
+ }
1260
+ const o = parseOptions(options, ['colorSpace', 'signal']);
1261
+ needsWeights(header);
1262
+ clustering = held(clustering);
1263
+ checkAborted(o.signal);
1264
+ const pause = async () => {
1265
+ checkAborted(o.signal);
1266
+ if (o.signal) {
1267
+ await yieldNow();
1268
+ checkAborted(o.signal);
1269
+ }
1270
+ };
1271
+ const indices = await choose({
1272
+ cut: size => cutPalette(name, clustering, size, []),
1273
+ swatches: () => cutSwatches(name, clustering, 1024, []),
1274
+ snap: async colours => (await quantizeToIndicesWithPalette({
1275
+ data: colours,
1276
+ format: 'rgb'
1277
+ }, entries, {
1278
+ colorSpace: 'rgb'
1279
+ })).indices,
1280
+ pause
1281
+ }, entries, k, colorSpaceName(o.colorSpace));
1282
+ indices.sort((x, y) => x - y);
1283
+ const chosen = new Uint8Array(3 * indices.length);
1284
+ indices.forEach((j, s) => chosen.set(entries.subarray(3 * j, 3 * j + 3), 3 * s));
1285
+ return {
1286
+ indices,
1287
+ palette: markPalette(chosen, 'rgb')
1288
+ };
1289
+ };
1290
+
1236
1291
  // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1237
1292
  setEngine({
1238
1293
  cut: cutPalette,
1239
1294
  cutSwatches,
1240
1295
  info: readInfo,
1241
1296
  quantizeFromClustering,
1242
- quantizeToIndicesFromClustering
1297
+ quantizeToIndicesFromClustering,
1298
+ chooseFrom
1243
1299
  });
package/dist/shared.cjs CHANGED
@@ -13,7 +13,7 @@ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat
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.7.1';
16
+ const version = exports.version = '3.8.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -597,7 +597,8 @@ const methodNames = {
597
597
  getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
598
598
  getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
599
599
  quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
600
- quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
600
+ quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)'],
601
+ chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
601
602
  };
602
603
  // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
603
604
  // the worker handle's `k`, then that the main entry is loaded.
@@ -611,7 +612,7 @@ const receive = (name, receiver, image) => {
611
612
  checkImageFirst(name, image.value);
612
613
  }
613
614
  if (engine === null) {
614
- throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
615
+ throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or ${form.startsWith('a ') ? `use ${form}` : `call ${form} from 'agglomerative-clustering/worker'`}, which runs in the worker.`);
615
616
  }
616
617
  return engine;
617
618
  };
@@ -661,6 +662,13 @@ const methods = {
661
662
  } catch (error) {
662
663
  return Promise.reject(error);
663
664
  }
665
+ },
666
+ chooseFrom(palette, k, options) {
667
+ try {
668
+ return receive('chooseFrom', this).chooseFrom('clustering.chooseFrom', this, palette, k, options);
669
+ } catch (error) {
670
+ return Promise.reject(error);
671
+ }
664
672
  }
665
673
  };
666
674
  // Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
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.1';
7
+ export const version = '3.8.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -557,7 +557,8 @@ const methodNames = {
557
557
  getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
558
558
  getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
559
559
  quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
560
- quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
560
+ quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)'],
561
+ chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
561
562
  };
562
563
  // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
563
564
  // the worker handle's `k`, then that the main entry is loaded.
@@ -571,7 +572,7 @@ const receive = (name, receiver, image) => {
571
572
  checkImageFirst(name, image.value);
572
573
  }
573
574
  if (engine === null) {
574
- throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
575
+ throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or ${form.startsWith('a ') ? `use ${form}` : `call ${form} from 'agglomerative-clustering/worker'`}, which runs in the worker.`);
575
576
  }
576
577
  return engine;
577
578
  };
@@ -621,6 +622,13 @@ const methods = {
621
622
  } catch (error) {
622
623
  return Promise.reject(error);
623
624
  }
625
+ },
626
+ chooseFrom(palette, k, options) {
627
+ try {
628
+ return receive('chooseFrom', this).chooseFrom('clustering.chooseFrom', this, palette, k, options);
629
+ } catch (error) {
630
+ return Promise.reject(error);
631
+ }
624
632
  }
625
633
  };
626
634
  // Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
@@ -6,7 +6,7 @@ import { MARK, mark, revive, isPalette, silenceWarnings } from "./shared.mjs";
6
6
  // The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
7
7
  silenceWarnings();
8
8
 
9
- // Images kept in the worker by `cluster`, with their clusterings, by handle id.
9
+ // Images kept in the worker by `cluster`, with their clusterings, and clusterings alone from `load`, by handle id.
10
10
  const handles = new Map();
11
11
  const handle = id => {
12
12
  const entry = handles.get(id);
@@ -50,6 +50,11 @@ const methods = {
50
50
  clustering: await ac.getClustering(image, options)
51
51
  });
52
52
  },
53
+ load: async (id, clustering) => {
54
+ handles.set(id, {
55
+ clustering: new ac.Clustering(clustering)
56
+ });
57
+ },
53
58
  release: async id => {
54
59
  handles.delete(id);
55
60
  },
@@ -57,8 +62,11 @@ const methods = {
57
62
  handleGetPalette: async (id, k) => ac.getPaletteFromClustering(handle(id).clustering, k),
58
63
  handleGetSwatches: async (id, k) => ac.getSwatchesFromClustering(handle(id).clustering, k),
59
64
  handleGetClusteringInfo: async id => ac.getClusteringInfo(handle(id).clustering),
65
+ handleChooseFrom: async (id, palette, k, options) => handle(id).clustering.chooseFrom(palette, k, options),
60
66
  handleQuantize: async (id, k, options) => ac.quantizeFromClustering(handle(id).image, handle(id).clustering, k, options),
61
67
  handleQuantizeToIndices: async (id, k, options) => ac.quantizeToIndicesFromClustering(handle(id).image, handle(id).clustering, k, options),
68
+ handleQuantizeImage: async (id, image, k, options) => ac.quantizeFromClustering(image, handle(id).clustering, k, options),
69
+ handleQuantizeToIndicesImage: async (id, image, k, options) => ac.quantizeToIndicesFromClustering(image, handle(id).clustering, k, options),
62
70
  handleQuantizeWithPalette: async (id, palette, options) => ac.quantizeWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette)),
63
71
  handleQuantizeToIndicesWithPalette: async (id, palette, options) => ac.quantizeToIndicesWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette))
64
72
  };
@@ -92,7 +100,10 @@ const optionsIndex = {
92
100
  handleQuantize: 2,
93
101
  handleQuantizeToIndices: 2,
94
102
  handleQuantizeWithPalette: 2,
95
- handleQuantizeToIndicesWithPalette: 2
103
+ handleQuantizeToIndicesWithPalette: 2,
104
+ handleChooseFrom: 3,
105
+ handleQuantizeImage: 3,
106
+ handleQuantizeToIndicesImage: 3
96
107
  };
97
108
 
98
109
  // One AbortController per call that can be cancelled, by call id. It exists from the moment the call arrives, so a call
package/dist/worker.cjs CHANGED
@@ -207,7 +207,7 @@ const start = async (receive, chosen) => {
207
207
  // A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
208
208
  // start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
209
209
  const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
210
- const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
210
+ const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
211
211
  let worker,
212
212
  source = null;
213
213
  try {
@@ -243,7 +243,9 @@ const start = async (receive, chosen) => {
243
243
  }
244
244
  worker.addEventListener('message', event => receive(event.data));
245
245
  worker.addEventListener('error', event => receive({
246
- failure: event.message ? `${event.message} ${scriptHint}` : crossOrigin ? `The worker failed to start: its script comes from another origin (${script.origin}), so it was started through a blob: URL, which also failed. Check that the server sends CORS headers, and that a Content-Security-Policy allows the worker: worker-src needs both blob: and ${script.origin} (the blob: worker imports the script from there). Or serve a copy of dist/ from this origin and say where with createWorker({ script }) or init({ script }).` : opaque ? `The worker failed to start from this page, whose origin is opaque (a sandboxed iframe): it was started from a data: URL importing ${script.href}, which needs CORS headers on that script and on what it imports. Or bundle worker-thread.mjs and its imports into one file, and pass it as a data: URL with createWorker({ script }).` : `The worker failed to start${chosen ? ` from ${script.href}` : ''}. ${scriptHint} A Content-Security-Policy must also allow it as a worker (worker-src).`
246
+ failure: event.message ? `${event.message} ${scriptHint}` : crossOrigin ? `The worker failed to start: its script comes from another origin (${script.origin}), so it was started through a blob: URL, which also failed. Check that the server sends CORS headers, and that a Content-Security-Policy allows the worker: worker-src needs both blob: and ${script.origin} (the blob: worker imports the script from there). Or serve a copy of dist/ from this origin and say where with createWorker({ script }) or init({ script }).` : opaque ? `The worker failed to start from this page, whose origin is opaque (a sandboxed iframe): it was started from a data: URL importing ${script.href}, which needs CORS headers on that script and on what it imports. Or bundle worker-thread.mjs and its imports into one file, and pass it as a data: URL with createWorker({ script }).` : script.protocol === 'blob:' && isOpaqueOrigin()
247
+ // Chromium refuses blob: workers in an opaque origin; the docs' single-file recipe uses a data: URL.
248
+ ? `The worker failed to start from ${script.href}: in a sandboxed iframe (an opaque origin, as plugin hosts such as Figma use) Chromium can't start a worker from a blob: URL. Pass the bundled worker script as a data: URL instead, createWorker({ script: 'data:text/javascript;base64,…', wasm: bytes }) (see "Plugins and single-file hosts" in https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).` : `The worker failed to start${chosen ? ` from ${script.href}` : ''}. ${scriptHint} A Content-Security-Policy must also allow it as a worker (worker-src).`
247
249
  }));
248
250
  return {
249
251
  post: (message, transfer) => worker.postMessage(message, transfer),
@@ -266,7 +268,7 @@ const start = async (receive, chosen) => {
266
268
  // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
267
269
  const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
268
270
  worker.on('error', error => receive({
269
- failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
271
+ failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
270
272
  }));
271
273
  worker.on('exit', code => receive({
272
274
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -958,6 +960,152 @@ const makeWorker = (options, allowScript) => {
958
960
  return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
959
961
  };
960
962
 
963
+ // Whether a value is an image where a palette size was expected (a pixel array, an ImageData or `{data, ...}`).
964
+ const looksLikeImage = value => value !== null && typeof value === 'object' && ((0, _shared.isUint8Array)(value) || (0, _shared.isUint8ClampedArray)(value) || (0, _shared.isImageData)(value) || 'data' in value);
965
+ // Builds the handle object for what the worker keeps under `id`: `kind` is 'image' (from `cluster`: an image and its
966
+ // clustering) or 'clustering' (from `load`: a clustering alone). `output` turns a mapped result back into the type of the image given.
967
+ const makeHandle = (id, kind, output) => {
968
+ let released = false;
969
+ // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
970
+ // keeps it alive and it is not reclaimed while still in use.
971
+ const use = (method, args, controls) => {
972
+ if (released || !handle) {
973
+ return Promise.reject((0, _shared.fail)('invalid-handle', "Invalid handle: it was released."));
974
+ }
975
+ return invoke(method, [id, ...args], [], new Error(), controls);
976
+ };
977
+ // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
978
+ const withControls = (method, leading, mapOptions) => {
979
+ let taken;
980
+ try {
981
+ taken = takeControls(mapOptions);
982
+ } catch (error) {
983
+ return Promise.reject(error);
984
+ }
985
+ return use(method, [...leading, taken.options], {
986
+ signal: taken.signal,
987
+ onProgress: taken.onProgress
988
+ });
989
+ };
990
+ // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
991
+ // as in the main entry, rather than silently ignored.
992
+ const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
993
+ // An image where k belongs is a mix-up between the two kinds of handle: say so, rather than "k must be an integer".
994
+ const imageAsK = (name, k) => looksLikeImage(k) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid k: this handle holds an image (from worker.cluster) and maps it with ${name}(k); pass k, not an image. To map other images with a stored clustering, use worker.load(clustering).`, 'k')) : null;
995
+ const handle = {
996
+ getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
997
+ getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
998
+ getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
999
+ // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given crosses as null for
1000
+ // the thread to reject with the main entry's own error.
1001
+ // That relies on the thread injecting a progress poster only for calls that have one (see `optionsIndex` in
1002
+ // worker-thread.js): the null is then the only onProgress it sees, so its own option check rejects it.
1003
+ chooseFrom: (palette, k, chooseOptions) => {
1004
+ let taken;
1005
+ try {
1006
+ taken = takeControls(chooseOptions, false);
1007
+ } catch (error) {
1008
+ return Promise.reject(error);
1009
+ }
1010
+ const sent = taken.onProgress !== undefined ? {
1011
+ ...taken.options,
1012
+ onProgress: null
1013
+ } : taken.options;
1014
+ return use('handleChooseFrom', [palette, k, sent], {
1015
+ signal: taken.signal
1016
+ });
1017
+ },
1018
+ release: async () => {
1019
+ if (released) {
1020
+ return;
1021
+ }
1022
+ released = true;
1023
+ liveHandles--;
1024
+ if (reclaim) {
1025
+ reclaim.unregister(handle);
1026
+ }
1027
+ // If the worker has been terminated there is nothing left to free (so `await using` and
1028
+ // terminate() can come in either order); any other failure is reported.
1029
+ try {
1030
+ await invoke('release', [id], [], new Error());
1031
+ } catch (error) {
1032
+ if (error.code !== 'worker-terminated') {
1033
+ throw error;
1034
+ }
1035
+ }
1036
+ stopIfAbandoned();
1037
+ }
1038
+ };
1039
+ if (kind === 'image') {
1040
+ Object.assign(handle, {
1041
+ getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
1042
+ quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions)))(),
1043
+ quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions),
1044
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
1045
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions)
1046
+ });
1047
+ }
1048
+ if (kind === 'clustering') {
1049
+ // The handle holds no image: each call maps the image it is given, and returns the type of that image.
1050
+ const mapping = (name, method, mapped) => (image, k, mapOptions) => {
1051
+ if (typeof image === 'number') {
1052
+ return Promise.reject((0, _shared.fail)('invalid-argument', "Invalid image: this handle holds a clustering, not an image (from worker.load); pass the image, then k.", 'image'));
1053
+ }
1054
+ const origin = new Error();
1055
+ return (async () => {
1056
+ if (released || !handle) {
1057
+ throw (0, _shared.fail)('invalid-handle', "Invalid handle: it was released.");
1058
+ }
1059
+ const {
1060
+ options,
1061
+ signal,
1062
+ onProgress
1063
+ } = takeControls(mapOptions);
1064
+ if (signal && signal.aborted) {
1065
+ // As the functions on the worker do: a wrong argument is reported before the abort.
1066
+ try {
1067
+ await invoke(method, [id, own(send(image)), k, options], [], origin, {
1068
+ check: true
1069
+ });
1070
+ } catch (error) {
1071
+ if ((0, _shared.isCodedError)(error) && error.argument !== undefined) {
1072
+ throw error;
1073
+ }
1074
+ }
1075
+ throw abortReason(signal);
1076
+ }
1077
+ const warning = (0, _shared.bareImageWarning)(image);
1078
+ const byteLength = warning ? image.byteLength : 0;
1079
+ let sent = send(image);
1080
+ const ahead = !ready();
1081
+ if (ahead) {
1082
+ sent = take(sent);
1083
+ }
1084
+ const result = await invoke(method, [id, sent, ahead ? own(k) : k, options], pixelBuffers(sent), origin, {
1085
+ signal,
1086
+ onProgress
1087
+ });
1088
+ if (warning) {
1089
+ (0, _shared.warnOnce)(warning, byteLength);
1090
+ }
1091
+ return mapped ? rebuild(image)(result) : result;
1092
+ })();
1093
+ };
1094
+ Object.assign(handle, {
1095
+ quantize: mapping('quantize', 'handleQuantizeImage', true),
1096
+ quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false)
1097
+ });
1098
+ }
1099
+ // `await using handle = await worker.cluster(image)` releases it at the end of the block.
1100
+ if (typeof Symbol.asyncDispose === 'symbol') {
1101
+ handle[Symbol.asyncDispose] = handle.release;
1102
+ }
1103
+ if (reclaim) {
1104
+ reclaim.register(handle, id, handle);
1105
+ }
1106
+ return handle;
1107
+ };
1108
+
961
1109
  // Clusters `image` and keeps it, with its clustering, in the worker.
962
1110
  instance.cluster = (image, clusterOptions) => {
963
1111
  const origin = new Error();
@@ -995,70 +1143,33 @@ const makeWorker = (options, allowScript) => {
995
1143
  if (warning) {
996
1144
  (0, _shared.warnOnce)(warning, byteLength);
997
1145
  }
998
- const output = rebuild(image);
999
- let released = false;
1000
- // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
1001
- // keeps it alive and it is not reclaimed while still in use.
1002
- const use = (method, args, controls) => {
1003
- if (released || !handle) {
1004
- return Promise.reject((0, _shared.fail)('invalid-handle', "Invalid handle: it was released."));
1005
- }
1006
- return invoke(method, [id, ...args], [], new Error(), controls);
1007
- };
1008
- // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
1009
- const withControls = (method, leading, mapOptions) => {
1010
- let taken;
1011
- try {
1012
- taken = takeControls(mapOptions);
1013
- } catch (error) {
1014
- return Promise.reject(error);
1015
- }
1016
- return use(method, [...leading, taken.options], {
1017
- signal: taken.signal,
1018
- onProgress: taken.onProgress
1019
- });
1020
- };
1021
- // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
1022
- // as in the main entry, rather than silently ignored.
1023
- const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
1024
- const handle = {
1025
- getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
1026
- getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
1027
- getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
1028
- getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
1029
- quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
1030
- quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
1031
- quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
1032
- quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
1033
- release: async () => {
1034
- if (released) {
1035
- return;
1036
- }
1037
- released = true;
1038
- liveHandles--;
1039
- if (reclaim) {
1040
- reclaim.unregister(handle);
1041
- }
1042
- // If the worker has been terminated there is nothing left to free (so `await using` and
1043
- // terminate() can come in either order); any other failure is reported.
1044
- try {
1045
- await invoke('release', [id], [], new Error());
1046
- } catch (error) {
1047
- if (error.code !== 'worker-terminated') {
1048
- throw error;
1049
- }
1050
- }
1051
- stopIfAbandoned();
1052
- }
1053
- };
1054
- // `await using handle = await worker.cluster(image)` releases it at the end of the block.
1055
- if (typeof Symbol.asyncDispose === 'symbol') {
1056
- handle[Symbol.asyncDispose] = handle.release;
1146
+ return makeHandle(id, 'image', rebuild(image));
1147
+ })();
1148
+ };
1149
+
1150
+ // Keeps a stored clustering in the worker, for cutting it and mapping images with it without sending it again.
1151
+ instance.load = (clustering, ...extra) => {
1152
+ const origin = new Error();
1153
+ return (async () => {
1154
+ // Checked, and the bytes taken, before anything is awaited (see `own`): a damaged clustering, a palette or an
1155
+ // image is reported here, and nothing is posted.
1156
+ if (extra.length > 0) {
1157
+ throw (0, _shared.fail)('invalid-argument', "Invalid arguments: load takes the clustering only. Options go to the handle's methods.", 'options');
1057
1158
  }
1058
- if (reclaim) {
1059
- reclaim.register(handle, id, handle);
1159
+ (0, _shared.readHeader)(clustering);
1160
+ const id = nextHandle++;
1161
+ const sent = ready() ? clustering : take(clustering);
1162
+ liveHandles++;
1163
+ try {
1164
+ await invoke('load', [id, sent], pixelBuffers(sent), origin);
1165
+ } catch (error) {
1166
+ liveHandles--;
1167
+ if (!terminated) {
1168
+ invoke('release', [id], [], new Error()).catch(() => {});
1169
+ }
1170
+ throw error;
1060
1171
  }
1061
- return handle;
1172
+ return makeHandle(id, 'clustering');
1062
1173
  })();
1063
1174
  };
1064
1175