agglomerative-clustering 3.7.2 → 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).
@@ -1242,11 +1243,57 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1242
1243
  return result;
1243
1244
  };
1244
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
+
1245
1291
  // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1246
1292
  setEngine({
1247
1293
  cut: cutPalette,
1248
1294
  cutSwatches,
1249
1295
  info: readInfo,
1250
1296
  quantizeFromClustering,
1251
- quantizeToIndicesFromClustering
1297
+ quantizeToIndicesFromClustering,
1298
+ chooseFrom
1252
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.2';
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.2';
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 {
@@ -268,7 +268,7 @@ const start = async (receive, chosen) => {
268
268
  // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
269
269
  const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
270
270
  worker.on('error', error => receive({
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, 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
272
272
  }));
273
273
  worker.on('exit', code => receive({
274
274
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -960,6 +960,152 @@ const makeWorker = (options, allowScript) => {
960
960
  return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
961
961
  };
962
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
+
963
1109
  // Clusters `image` and keeps it, with its clustering, in the worker.
964
1110
  instance.cluster = (image, clusterOptions) => {
965
1111
  const origin = new Error();
@@ -997,70 +1143,33 @@ const makeWorker = (options, allowScript) => {
997
1143
  if (warning) {
998
1144
  (0, _shared.warnOnce)(warning, byteLength);
999
1145
  }
1000
- const output = rebuild(image);
1001
- let released = false;
1002
- // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
1003
- // keeps it alive and it is not reclaimed while still in use.
1004
- const use = (method, args, controls) => {
1005
- if (released || !handle) {
1006
- return Promise.reject((0, _shared.fail)('invalid-handle', "Invalid handle: it was released."));
1007
- }
1008
- return invoke(method, [id, ...args], [], new Error(), controls);
1009
- };
1010
- // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
1011
- const withControls = (method, leading, mapOptions) => {
1012
- let taken;
1013
- try {
1014
- taken = takeControls(mapOptions);
1015
- } catch (error) {
1016
- return Promise.reject(error);
1017
- }
1018
- return use(method, [...leading, taken.options], {
1019
- signal: taken.signal,
1020
- onProgress: taken.onProgress
1021
- });
1022
- };
1023
- // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
1024
- // as in the main entry, rather than silently ignored.
1025
- 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);
1026
- const handle = {
1027
- getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
1028
- getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
1029
- getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
1030
- getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
1031
- quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
1032
- quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
1033
- quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
1034
- quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
1035
- release: async () => {
1036
- if (released) {
1037
- return;
1038
- }
1039
- released = true;
1040
- liveHandles--;
1041
- if (reclaim) {
1042
- reclaim.unregister(handle);
1043
- }
1044
- // If the worker has been terminated there is nothing left to free (so `await using` and
1045
- // terminate() can come in either order); any other failure is reported.
1046
- try {
1047
- await invoke('release', [id], [], new Error());
1048
- } catch (error) {
1049
- if (error.code !== 'worker-terminated') {
1050
- throw error;
1051
- }
1052
- }
1053
- stopIfAbandoned();
1054
- }
1055
- };
1056
- // `await using handle = await worker.cluster(image)` releases it at the end of the block.
1057
- if (typeof Symbol.asyncDispose === 'symbol') {
1058
- 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');
1059
1158
  }
1060
- if (reclaim) {
1061
- 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;
1062
1171
  }
1063
- return handle;
1172
+ return makeHandle(id, 'clustering');
1064
1173
  })();
1065
1174
  };
1066
1175