agglomerative-clustering 3.0.0-beta.4 → 3.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -226,6 +226,56 @@ for (const frame of frames) {
226
226
 
227
227
  Cutting the clustering keeps `k` counting the transparent entry, so the palette fits a GIF. (A palette passed to `quantizeToIndicesWithPalette` has the transparent entry added to it, so 256 colours become 257 entries: cut 255.) A frame with no transparent pixels has no transparent entry, so its palette can be one entry shorter than another frame's; a GIF with one global palette should reserve a slot for it. With the worker entry, a few `createWorker()`s map frames in parallel; on small frames (320×240) the cost of sending them across outweighs the gain.
228
228
 
229
+ ### Live video and camera frames
230
+
231
+ For a palette that follows a video or a camera (ambient light, a live theme), take each frame small and **skip frames while the worker is busy**:
232
+
233
+ ```js
234
+ import { createWorker } from 'agglomerative-clustering/worker';
235
+
236
+ const worker = createWorker({ transfer: true }); // each frame's pixels are fresh, so move them rather than copy
237
+ const canvas = new OffscreenCanvas(160, 90); // a small copy is plenty for a palette
238
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
239
+ let busy = false;
240
+
241
+ const onFrame = () => {
242
+ if (!busy) {
243
+ busy = true;
244
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
245
+ worker.getPalette(ctx.getImageData(0, 0, canvas.width, canvas.height), 6, { precision: 6 })
246
+ .then(show, console.error)
247
+ .finally(() => {busy = false;});
248
+ }
249
+ video.requestVideoFrameCallback(onFrame);
250
+ };
251
+ video.requestVideoFrameCallback(onFrame);
252
+ ```
253
+
254
+ - **Don't abort the running call when a new frame arrives**, as the slider example does. A slider stops; frames keep coming, so when each palette takes longer than a frame, every call is aborted before it finishes and no palette ever arrives (none in 6 seconds at 640×360 and 30 frames a second, in testing). Each abort also costs the worker a little. Skip frames instead, or keep only the newest one waiting.
255
+ - **Size.** In a worker with `precision: 6` a palette took about 20 ms at 160×90, 50 ms at 320×180, 100 ms at 640×360 and 185 ms at 1280×720 (on a busy machine, so a ceiling); exact precision is 3 to 7 times slower. 160×90 keeps up with 30 frames a second.
256
+ - **Flicker.** Each frame is clustered on its own, so even a still scene with a little noise gives palettes whose colours shift, swap places or split differently from frame to frame. Follow the previous palette and smooth it; in testing this cut the flicker about fourfold, for a lag of two or three frames:
257
+
258
+ ```js
259
+ // Match each colour of the previous (smoothed) palette to its nearest new colour, then move a quarter of the way there.
260
+ const follow = (previous, next, weight = 0.25) => {
261
+ if (!previous || previous.length !== next.length) {return Array.from(next);}
262
+ const free = new Set(Array.from({ length: next.length / 3 }, (_, i) => i));
263
+ const smoothed = [];
264
+ for (let i = 0; i < previous.length; i += 3) {
265
+ let best = 0, bestDistance = Infinity;
266
+ for (const j of free) {
267
+ const d = (previous[i] - next[3 * j]) ** 2 + (previous[i + 1] - next[3 * j + 1]) ** 2 + (previous[i + 2] - next[3 * j + 2]) ** 2;
268
+ if (d < bestDistance) {bestDistance = d; best = j;}
269
+ }
270
+ free.delete(best);
271
+ for (let c = 0; c < 3; c++) {smoothed.push(previous[i + c] + weight * (next[3 * best + c] - previous[i + c]));}
272
+ }
273
+ return smoothed; // fractional values: round them for display
274
+ };
275
+ ```
276
+ - **One palette for a whole clip** (no flicker at all) is the animated-GIF recipe above: cluster a sample of frames once.
277
+ - **In Node**, pipe ffmpeg's raw output (`-f rawvideo -pix_fmt rgba`) and hand each frame to a few `createWorker()`s; memory stayed flat over thousands of frames in testing.
278
+
229
279
  ### Off the main thread
230
280
 
231
281
  Clustering a photo takes about 70 ms, too long to run on a page's main thread while someone drags a slider. The worker entry has the same functions, run in a Web Worker (or a worker thread in Node):
@@ -246,18 +296,18 @@ const handle = await worker.cluster(imageData, { precision: 6 });
246
296
  let controller = null;
247
297
  slider.oninput = async () => {
248
298
  controller?.abort(); // a size the slider has already moved past isn't worth finishing
249
- controller = new AbortController();
299
+ const mine = (controller = new AbortController());
250
300
  try {
251
- ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: controller.signal }), 0, 0);
301
+ ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: mine.signal }), 0, 0);
252
302
  } catch (error) {
253
- if (error.name !== 'AbortError') {throw error;}
303
+ if (!mine.signal.aborted) {throw error;} // an abort is expected; anything else is a real failure
254
304
  }
255
305
  };
256
306
  ```
257
307
 
258
- Calls to one worker run in order, and re-mapping a large image takes a while (0.2 to 0.3 s at 12 megapixels, about 1 s dithered), so without the `signal` a fast drag queues up every size it passed through and the picture keeps changing after the slider stops. Aborting the previous call drops it from the queue. Re-cutting alone (`handle.getPalette(k)`, `handle.getSwatches(k)`) takes well under a millisecond and needs none of this.
308
+ Calls to one worker run in order, and re-mapping a large image takes a while (0.2 to 0.3 s at 12 megapixels, about 1 s dithered), so without the `signal` a fast drag queues up every size it passed through and the picture keeps changing after the slider stops. Aborting the previous call drops it from the queue. Re-cutting alone (`handle.getPalette(k)`, `handle.getSwatches(k)`) takes well under a millisecond and needs none of this. This suits a slider, which stops; for a stream that never does, such as video frames, see [Live video and camera frames](#live-video-and-camera-frames).
259
309
 
260
- It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite and webpack 5, Parcel 2 works with its `packageExports` option on, and for Next.js see [Next.js](#nextjs). Bundlers that don't emit that script (Angular's `application` builder, plain esbuild or Rollup) need it given to them: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). Loaded from a CDN (another origin than the page), it starts the worker through a small `blob:` script, as browsers don't start workers from other origins' scripts. In TypeScript a handle keeps the image type it was made from: a variable that holds one is `ClusteringHandle<ImageData> | null`, not a bare `ClusteringHandle`, whose `quantize` returns the general image type. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
310
+ It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite and webpack 5, Parcel 2 works with its `packageExports` option on (see [below](#angular-esbuild-rollup-and-other-bundlers)), and for Next.js see [Next.js](#nextjs). Bundlers that don't emit that script (Angular's `application` builder, plain esbuild or Rollup) need it given to them: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). Loaded from a CDN (another origin than the page), it starts the worker through a small `blob:` script, as browsers don't start workers from other origins' scripts. In TypeScript a handle keeps the image type it was made from: a variable that holds one is `ClusteringHandle<ImageData> | null`, not a bare `ClusteringHandle`, whose `quantize` returns the general image type. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
261
311
 
262
312
  ### Fixed palettes: e-ink, thread, bricks
263
313
 
@@ -271,9 +321,28 @@ const { indices } = await quantizeToIndicesWithPalette({ data, format: 'rgba', w
271
321
 
272
322
  - **Undithered, every pixel gets its nearest entry** (ties go to the smaller RGB value, and a repeated entry gets its first index). Dithering diffuses the error to the neighbours, and keeps working when the palette can't reach the image's colours: saturated cyan with the seven e-ink inks comes out as an even mix of white, green and blue, not solid blue.
273
323
  - **Colour space is a choice here too, and the answer differs from clustering.** `'oklab'` keeps skin tones from going olive when mapping *without* dithering; with small palettes of widely spaced inks (e-ink, grey levels) `'rgb'` dithers better, and OKLab brightens black and white. Try both on your panel.
274
- - **Choosing N colours from a fixed set** (the 12 threads that best represent a photo out of 400): there is no function for it, but this works. Cluster the image, cut it to a few more than N colours, snap each cut colour to its nearest thread (pass the cut palette as a one-pixel-per-colour `rgb` image to `quantizeToIndicesWithPalette`), and raise the number you cut until N distinct threads appear. It beat "the N most used threads" by up to 6 dB PSNR in testing.
324
+ - **Choosing N colours from a fixed set** (the 12 threads that best represent a photo out of 400) has no function of its own, but a few lines do it: cut the clustering, snap each cut colour to its nearest thread, and cut finer until N distinct threads appear. In testing it beat "the N most used threads" by 3 to 8 dB PSNR for N up to 12; the gain shrinks as N grows (under 1 dB at 24).
325
+
326
+ ```js
327
+ import { getClustering, getPaletteFromClustering, quantizeToIndicesWithPalette } from 'agglomerative-clustering';
328
+
329
+ // The indices (into `threads`, flat RGB) of the n threads that best represent `image`.
330
+ async function chooseThreads(image, threads, n) {
331
+ const clustering = await getClustering(image);
332
+ let chosen = [];
333
+ for (let k = n; k <= 4 * n && chosen.length < n; k++) {
334
+ const cut = await getPaletteFromClustering(clustering, k);
335
+ // The cut palette as an image of one pixel per colour, mapped to the threads.
336
+ const { indices } = await quantizeToIndicesWithPalette({ data: cut, format: 'rgb' }, threads);
337
+ // Split order puts the coarsest colours first, so when a cut gives more than n threads, the first n are kept.
338
+ chosen = [...new Set(indices)].slice(0, n);
339
+ }
340
+ return chosen; // can be fewer than n for an image with few colours
341
+ }
342
+ ```
275
343
  - **Transparent pixels** map to black unless you pass `transparent`, which appends an entry for them (so a 1- or 2-bit panel has no room for it): composite the image onto your background first.
276
- - A palette of more than 1024 colours is mapped about three times slower than one of 1024 or fewer.
344
+ - **Index width:** up to 256 entries give 8-bit indices; more give 16-bit ones (`indexBits` says which), so a 257-colour palette doesn't fit an 8-bit format.
345
+ - **Speed:** a palette of more than 1024 colours is mapped about three times slower than one of 1024 or fewer, and dithered about four to six times slower (at 12 megapixels, about 2 s with 1024 colours against 8 to 13 s with 1025 to 2000).
277
346
 
278
347
  ### Swatches for many images (a build step)
279
348
 
@@ -321,6 +390,23 @@ const rankedIndices = indices.map((index) => rank[index]);
321
390
  const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
322
391
  ```
323
392
 
393
+ ### Coming from color-thief, node-vibrant, image-q or get-image-colors
394
+
395
+ This library takes **decoded pixels**, not files, URLs or image elements: decode first (sharp or pngjs in Node, a canvas or `createImageBitmap` in a browser). Pixels without alpha go in as `{ data, format: 'rgb' }`; passed bare they are read as RGBA, so sharp's `.raw()` without `.ensureAlpha()` gives a palette that is quietly wrong.
396
+
397
+ | You used | Use | Notes |
398
+ |---|---|---|
399
+ | color-thief `getColor(image)` | `getSwatches(image, 5, { precision: 6 })`, then the entry with the largest `shares` | The heaviest cluster's average colour. |
400
+ | color-thief `getPalette(image, n)` | `getPalette(image, n, { precision: 6 })` | Flat bytes; `[[r, g, b], …]` is one line ("Using the output"). |
401
+ | get-image-colors | `getSwatches(image, n)`, and hex strings from the palette | Sort by `shares` for most-used first. |
402
+ | node-vibrant's named swatches (Vibrant, Muted, …) | `getSwatches(image, 16)`, then choose by saturation and lightness yourself | There are no named roles: these colours are averages, more muted than node-vibrant's picks. |
403
+ | image-q `buildPalette` and `applyPalette` | `quantize(image, k, { dither })`, or `getPalette` then `quantizeWithPalette` | Same idea, one call; `quantizeToIndices` for indexed output. |
404
+
405
+ - **Expect different colours.** The palettes are the ones with the least error, not the most vivid or the most frequent, so they won't match what you had (a mean ΔE2000 of 12 to 14 between matched colours, against color-thief, get-image-colors and node-vibrant, in testing).
406
+ - **Speed.** color-thief and node-vibrant sample pixels, so they are quick on photos; the exact default here is several times slower at photo sizes. With `precision: 6` it was level with color-thief at 12 megapixels; downscaling helps both. Against image-q it was 4 to 6 times faster.
407
+ - **Quality.** Undithered, the error was lower than image-q's Wu (at 16 colours, MSE 71 against 84). `dither: true` diffuses the whole error, so per-pixel error is higher than with image-q's Floyd–Steinberg while the image looks closer from a distance; a strength such as `dither: 0.5` sits between.
408
+ - **Missing pieces** are a few lines each: hex strings and ranking by share in [Using the output](#using-the-output), and a dominant colour above.
409
+
324
410
  ## Reference
325
411
 
326
412
  ### Input and output
@@ -454,7 +540,7 @@ const clustering = await getClustering(image, {
454
540
  ```
455
541
 
456
542
  - **Slices.** With either option, clustering runs in slices of about 10 ms (a large image has a few unsliced steps of up to 150 ms in between), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
457
- - **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is not one of this library's errors, and has none of their codes: check `error.name === 'AbortError'`. An already aborted signal does no work.
543
+ - **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is not one of this library's errors, and has none of their codes (a `DOMException`'s `code` is a number). To tell an abort from a failure, check your signal (`signal.aborted`), not the error: a reason you gave (`controller.abort(new Error('superseded'))`) keeps its own name. An already aborted signal does no work.
458
544
  - **Mapping can't be interrupted** (it takes milliseconds: 6 ms at 768×512, 27 ms dithered). The functions that only map check the signal before they start, and don't take `onProgress`.
459
545
  - **Progress** is approximate, never goes backwards, and ends at exactly 1.
460
546
  - **In a worker** the work in the worker stops too, and a call still queued is removed without running. The worker keeps running for later calls.
@@ -472,18 +558,22 @@ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`
472
558
  | `unsupported-version` | A clustering from a newer format, or using a colour space it doesn't know (upgrade the package), or an older one without what you asked for (cluster again, e.g. for `getSwatchesFromClustering`). |
473
559
  | `out-of-memory` | The WebAssembly module couldn't allocate. |
474
560
  | `wasm-load-failed` | The WebAssembly module couldn't be loaded or compiled: a missing or blocked `.wasm` file, a server bundle that moved it, a browser without SIMD, or a `.wasm` from a different version of the library than the script (a stale cache or CDN copy; the message names both versions). The message leads with the engine's reason and says what to check, and `cause` is the engine's own error. |
475
- | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed to start, or a handle was released. |
561
+ | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped, failed, or a handle was released. `worker-terminated` is for calls running or waiting when `terminate()` was called, and every later call on that `createWorker()` worker, so retrying on it can't help (the shared worker starts again on the next call). After `worker-failed` (it couldn't start, crashed or exited), the next call starts a new worker. |
476
562
 
477
563
  ```js
564
+ import { getPaletteFromClustering, isCodedError } from 'agglomerative-clustering';
565
+
478
566
  try {
479
567
  await getPaletteFromClustering(stored, 16);
480
568
  } catch (error) {
481
- const code = error instanceof Error && 'code' in error ? error.code : undefined; // also compiles in strict TypeScript
482
- if (code === 'unsupported-version' || code === 'invalid-clustering') { /* cluster the image again */ }
569
+ // isCodedError narrows the type in TypeScript, and is false for errors that aren't the library's (Node's ENOENT, an abort)
570
+ if (isCodedError(error) && (error.code === 'unsupported-version' || error.code === 'invalid-clustering')) { /* cluster the image again */ }
483
571
  else { throw error; }
484
572
  }
485
573
  ```
486
574
 
575
+ `errorCodes` lists every code, for code that forwards them (a wrapper package re-exporting them, a bridge between processes). `isCodedError` also accepts a plain object with a known `code` and a `message`, which is what an error becomes after Electron's IPC or a `postMessage`.
576
+
487
577
  Messages are for people and may change. The worker entry fails the same way as the main entry, with your call's stack (the worker's is on `cause`). A failure that isn't the library's own, such as a WebAssembly trap, has no `code`.
488
578
 
489
579
  ### Worker entry
@@ -494,10 +584,12 @@ Messages are for people and may change. The worker entry fails the same way as t
494
584
 
495
585
  `createWorker` takes `transfer`, `wasm` (see [Loading the WebAssembly module](#loading-the-webassembly-module)) and `script`: the URL (or in Node, the path) of a copy of the package's `dist/worker-thread.mjs`, for setups whose bundler doesn't emit the package's own. For the shared worker, `init({ script })` does the same, before any other call.
496
586
 
497
- Calls run one at a time, in order. Results are transferred back without copying. Images are copied in, unless you create the worker with `createWorker({ transfer: true })`, which is faster but leaves your buffer empty. Only pixels that are a whole buffer of their own are transferred; a view into part of a larger buffer, such as a `subarray` or a small Node `Buffer`, is copied. The entry is an ES module; `require()` works too on the supported Node versions.
587
+ Calls run one at a time, in order. Results are transferred back without copying. Images are copied in, unless you create the worker with `createWorker({ transfer: true })`, which is faster but leaves your buffer empty. Only pixels that are a whole buffer of their own are transferred; a view into part of a larger buffer, such as a `subarray` or a small Node `Buffer`, is copied.
588
+
589
+ The entry is an ES module, with a CommonJS build for `require()` in Node and in Jest. In a browser bundle, import it rather than `require()` it: bundlers find the worker script only from the ES module, so the CommonJS build there needs `createWorker({ script })`.
498
590
 
499
591
  ### TypeScript
500
- Both entries ship declarations, checked in CI under strict mode with `nodenext` (ES module and CommonJS importers), `bundler`, and a Node-only project without the DOM lib. The worker entry's declarations use `await using` for handles, so they need **TypeScript 5.2 or newer** (or `skipLibCheck: true`); the main entry works on older versions. From a CommonJS file, load the worker entry with `await import('agglomerative-clustering/worker')`, or use TypeScript 5.8+ with `module: nodenext`.
592
+ Both entries ship declarations, checked in CI under strict mode with `nodenext` (ES module and CommonJS importers), `bundler`, and a Node-only project without the DOM lib. The worker entry's declarations use `await using` for handles, so they need **TypeScript 5.2 or newer** (or `skipLibCheck: true`); the main entry works on older versions. Both entries have CommonJS declarations too, so a `.cts` file or a CommonJS project imports either.
501
593
 
502
594
  Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`, and checking `info.formatVersion === 3` makes `mse`, `explained` and `totalWeight` present. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
503
595
 
@@ -587,6 +679,9 @@ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signa
587
679
  ### `init(options?): Promise<void>`
588
680
  Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, for example to warm up before a batch. Concurrent calls share one load, and a failed load can be retried. To say where the module is, see [Loading the WebAssembly module](#loading-the-webassembly-module).
589
681
 
682
+ ### `errorCodes: readonly string[]` and `isCodedError(value): boolean`
683
+ `errorCodes` is a frozen array of every `code` the library's errors have (see [Errors](#errors)). `isCodedError(value)` is true when `value` has a string `message` and one of those codes; in TypeScript it narrows to `CodedError`. Both entries export both.
684
+
590
685
  ### `version: string` and `formatVersion: number`
591
686
  `version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: if a stored clustering's `getClusteringInfo(stored).formatVersion` differs, cluster the image again (2.x clusterings still load, but have no weights). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
592
687
 
@@ -596,7 +691,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
596
691
 
597
692
  Node 20.19+ and 22.12+ (CI tests Node 20, 22 and 24, on Linux and Windows), and browsers with WebAssembly SIMD: Chrome and Edge 91, Firefox 89, Safari 16.4 or newer ([support table](https://caniuse.com/wasm-simd)). CI bundles a test page with Vite and webpack 5 and runs it in Chromium, Firefox and WebKit on Linux and in Safari on macOS. In a browser without SIMD, or where the `.wasm` is blocked or missing, `init` and every other call reject with a `wasm-load-failed` error.
598
693
 
599
- CI also loads `dist/` from another origin, as a page using a CDN does, in the same browsers. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime, SvelteKit and Nuxt, Next.js and Parcel 2 (see below).
694
+ CI also loads `dist/` from another origin, as a page using a CDN does, and the worker entry from a sandboxed iframe, in the same browsers, and runs both entries under Jest. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime, SvelteKit and Nuxt, Next.js and Parcel 2 (see below).
600
695
 
601
696
  ### From a CDN, without a build step
602
697
 
@@ -607,7 +702,7 @@ CI also loads `dist/` from another origin, as a page using a CDN does, in the sa
607
702
  </script>
608
703
  ```
609
704
 
610
- Import `dist/index.mjs` and `dist/worker.mjs` by their paths (jsDelivr and unpkg don't follow the package's `exports` for subpaths such as `/worker`); `https://esm.sh/agglomerative-clustering@next` works too. The `.wasm` is found next to the script, so `init` needs no `wasm` option, and the worker entry starts its worker through a `blob:` script (browsers don't start workers from another origin's script). A Content-Security-Policy needs the CDN in `script-src` and `connect-src` (the `.wasm` is fetched), `'wasm-unsafe-eval'`, and `worker-src blob:` for the worker. Pin an exact version in production, as `@3.0.0` rather than `@next`.
705
+ Import `dist/index.mjs` and `dist/worker.mjs` by their paths (jsDelivr and unpkg don't follow the package's `exports` for subpaths such as `/worker`); `https://esm.sh/agglomerative-clustering@next` works too. The `.wasm` is found next to the script, so `init` needs no `wasm` option, and the worker entry starts its worker through a `blob:` script (browsers don't start workers from another origin's script). A Content-Security-Policy needs the CDN in `script-src` and `connect-src` (the `.wasm` is fetched) and `'wasm-unsafe-eval'` in `script-src`. The worker entry also needs `worker-src blob:` *and* the CDN, since the `blob:` worker imports its script from there: `worker-src blob: https://cdn.jsdelivr.net`. Pin an exact version in production, as `@3.0.0` rather than `@next`.
611
706
 
612
707
  ### Deno, Bun and Cloudflare Workers
613
708
 
@@ -637,7 +732,7 @@ await init({ wasm: await (await fetch(url)).arrayBuffer() }); // the by
637
732
  await init({ wasm: wasmModule }); // a compiled WebAssembly.Module
638
733
  ```
639
734
 
640
- The package exports the file as `agglomerative-clustering/clustering.wasm`, so a bundler that imports `.wasm` files as compiled modules (Wrangler, for Cloudflare Workers) can give you `wasmModule`. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
735
+ The package exports the file as `agglomerative-clustering/clustering.wasm`, so a bundler that imports `.wasm` files as compiled modules (Wrangler, for Cloudflare Workers) can give you `wasmModule`. In Node a path or `file:` URL is read from disk, also when the package is bundled into CommonJS. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
641
736
 
642
737
  ### SvelteKit, Nuxt and other frameworks
643
738
 
@@ -686,9 +781,15 @@ const worker = createWorker({
686
781
  ```json
687
782
  "assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
688
783
  ```
689
- - **esbuild and Rollup** do not recognise `new Worker(new URL(...))`, so copy the same files into the output and give `script`. Rollup users can also build `worker-thread.mjs` as a second entry.
690
- - **Vite, webpack 5 and Parcel** find the script themselves.
784
+ - **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the same files into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
785
+ - **Vite, webpack 5 and Rsbuild** find the script themselves. So does **Parcel 2**, once it reads package `exports` (without this it can't resolve `agglomerative-clustering/worker`):
786
+
787
+ ```json
788
+ "@parcel/resolver-default": { "packageExports": true }
789
+ ```
790
+ in your `package.json`.
691
791
  - **The main entry** can also be told where the `.wasm` is with `init({ wasm })`.
792
+ - **A server bundle** (esbuild or Rollup with a Node target, CommonJS or ES module): leave the package external if you ship `node_modules`. Bundled, it finds its files from the working directory, if at all: pass `init({ wasm: path })` and `createWorker({ script: path })`, with paths to copies of `dist/` that you ship.
692
793
 
693
794
  ### Electron
694
795
 
@@ -697,30 +798,41 @@ Everything works in dev and in an app packaged with `asar` (no `asarUnpack`), in
697
798
  - **Keep the package external in a bundled main process** (electron-vite does by default; with webpack or esbuild mark it external). A bundle that inlines it finds the `.wasm` and worker script only when the app starts from the project directory, which a packaged app doesn't. If you must bundle it, pass `init({ wasm })` for the main entry and `createWorker({ script })` for the worker.
698
799
  - **`nodeIntegrationInWorker: true`** is supported: the worker script talks through `self` there.
699
800
 
700
- Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `error.code` yourself. `nativeImage` gives BGRA pixels: swap the channels to RGBA first.
801
+ Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `{ message, code, argument }` yourself; `isCodedError` accepts that object on the other side. `nativeImage` gives BGRA pixels: swap the channels to RGBA first.
701
802
 
702
803
  ### Browser extensions
703
804
 
704
- The main entry runs in every extension context: a Manifest V3 service worker, an offscreen document, extension pages and content scripts (a page's own Content-Security-Policy does not apply to a content script).
805
+ The main entry runs in every extension context: a Manifest V3 service worker, an offscreen document, extension pages and content scripts (a page's own Content-Security-Policy does not apply to the main entry in a content script). Tested in Chrome and in Firefox's extension pages and background.
705
806
 
706
- - **Manifest CSP.** Compiling WebAssembly in the service worker, an offscreen document or an extension page needs `'wasm-unsafe-eval'` (not `'wasm-eval'`, which Chrome refuses in a manifest): `"content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" }`. Content scripts need nothing.
707
- - **A service worker has no `Worker`**, so use the main entry there, which already keeps the page's thread free. The worker entry works in an offscreen document or an extension page, and in a content script on a page whose CSP allows `worker-src blob:`.
708
- - **Files.** With Vite and CRXJS the `.wasm` and worker script are emitted and made web-accessible for you. Without a bundler, copy `dist/*.mjs`, `clustering.js` and `clustering.wasm` into the extension and list them under `web_accessible_resources` if a content script loads them.
807
+ - **Manifest CSP.** Compiling WebAssembly in the service worker, an offscreen document or an extension page needs `'wasm-unsafe-eval'` (not `'wasm-eval'`, which Chrome refuses in a manifest): `"content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" }`. The main entry in a content script needs nothing.
808
+ - **A service worker has no `Worker`**, so use the main entry there, which already keeps the page's thread free. The worker entry works in an offscreen document or an extension page. In a content script it starts its worker through a `blob:` URL, and that worker follows the *page's* policy, so it works only on pages whose CSP allows `worker-src blob:` and `'wasm-unsafe-eval'` (or has no CSP); on other pages, use the main entry in the content script, or hand the pixels to an offscreen document.
809
+ - **Files.** With Vite and CRXJS the `.wasm` and worker script are emitted and made web-accessible for you. Without a bundler, copy `dist/*.mjs`, `clustering.js` and `clustering.wasm` into the extension and list them under `web_accessible_resources` if a content script loads them (all of them: a `.wasm` left out fails as "could not be fetched", and only the browser's console names the key).
709
810
  - A service worker can fetch cross-origin images with host permissions (a content script gets a tainted canvas), so cluster there. Typed arrays become plain objects through `chrome.runtime.sendMessage`: convert with `Array.from(palette)` and back with `new Uint8Array(...)`.
710
811
 
812
+ ### Plugins and single-file hosts: Figma, VS Code, Obsidian
813
+
814
+ Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wasm` and worker script can't sit next to it. Embed them, and say where everything is: in these hosts the package can't find its own files. (Tested against stand-ins for these hosts: a sandboxed iframe, a Node host process, an Electron renderer. Not inside the apps themselves.)
815
+
816
+ - **The `.wasm` as bytes.** Import it with your bundler's binary loader (esbuild: `--loader:.wasm=binary`, importing `agglomerative-clustering/clustering.wasm`) and pass the bytes: `init({ wasm: bytes })` for the main entry, `createWorker({ wasm: bytes })` for a worker. Set esbuild's `target` (such as `es2022`), or the decoder it emits may use `Uint8Array.fromBase64`, which not every runtime has. The file is about 92 KB, 122 KB as base64, and 54 KB gzipped then base64 (decompress it with `DecompressionStream` before passing it).
817
+ - **The worker script as a `data:` URL.** Bundle `node_modules/agglomerative-clustering/dist/worker-thread.mjs` into one ES module (esbuild `--bundle --format=esm`) and pass it as `createWorker({ script: 'data:text/javascript;base64,…', wasm: bytes })`. In a sandboxed iframe (Figma's UI) a `blob:` worker fails in Chromium; a `data:` one works. The main entry alone is often enough for a plugin's images, and needs only the bytes.
818
+ - **VS Code.** The extension host is Node: bundle your extension with the package external and ship it in `node_modules`, or bundle it and pass a path to a `.wasm` you ship (`init({ wasm: path.join(context.extensionPath, 'dist', 'clustering.wasm') })`); a bundled extension otherwise looks for the package from the working directory, which is not your extension's. A webview's CSP needs `'wasm-unsafe-eval'` in `script-src`, and `worker-src` for the worker entry.
819
+ - **Obsidian** ships `main.js`, `manifest.json` and `styles.css` only, so embed the `.wasm` bytes. Its renderer has Node's globals and a real `Worker`, so both entries work once given the bytes (and, for workers, the `data:` script).
820
+ - **Copying `dist/` files instead**, keep their `.mjs` names: they are ES modules by their extension. Renamed to `.js`, they need a `package.json` with `"type": "module"` next to them.
821
+ - **Get it wrong** and the error says so: a bundled main entry without its `.wasm` fails with `wasm-load-failed` asking for `init({ wasm })`, and a worker without its script with `worker-failed` naming `createWorker({ script })`.
822
+
711
823
  ### Testing code that uses it
712
824
 
713
825
  - **Vitest** needs no configuration, in node, jsdom, happy-dom and browser mode. **Storybook** (Vite builder) works as it is.
714
- - **Jest** works in its default CommonJS mode, in the node and jsdom environments, without transforms or `--experimental-vm-modules` (the package falls back to a CommonJS build of its glue where `require()` of an ES module fails).
715
- - **jsdom and happy-dom** have no `ImageData` (install `canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
716
- - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`: each Jest test file otherwise leaves a worker thread, about 30 MB, in the process.
717
- - **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })`.
826
+ - **Jest** works in its default CommonJS mode, in the node and jsdom environments, with both entries, without transforms or `--experimental-vm-modules` (both have CommonJS builds). Mocha and `node:test` work too.
827
+ - **jsdom and happy-dom** have no `ImageData` (install `canvas`, `@napi-rs/canvas` or `skia-canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
828
+ - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends.
829
+ - **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })` (`isCodedError` accepts them).
718
830
  - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and stay the same within a major version: snapshot them. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
719
831
  - Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
720
832
 
721
833
  ### Writing a package that wraps it
722
834
 
723
- Make `agglomerative-clustering` a **`peerDependency`** and keep it **external** in your build (tsup `external`, Rollup `external`): the app's bundler then finds the worker script and `.wasm` once, with one copy in the output. Bundling it into your package leaves `./worker-thread.mjs` unresolved. Re-export the types you need (`CodedError`, `ErrorCode`, `ClusteringOptions`, …), check `version` against your supported range at run time, and let your users pass `wasm` and `script` through. Importing it on the server (SSR) doesn't run anything: only calls load the module.
835
+ Make `agglomerative-clustering` a **`peerDependency`** and keep it **external** in your build (tsup `external`, Rollup `external`): the app's bundler then finds the worker script and `.wasm` once, with one copy in the output. Bundling it into your package leaves `./worker-thread.mjs` unresolved. Re-export `errorCodes`, `isCodedError` and the types you need (`CodedError`, `ErrorCode`, `ClusteringOptions`, …), check `version` against your supported range at run time, and let your users pass `wasm` and `script` through. Importing it on the server (SSR) doesn't run anything: only calls load the module.
724
836
 
725
837
  ### Performance and limits
726
838
 
@@ -766,8 +878,10 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
766
878
  | `invalid-clustering` for a clustering you stored | Its bytes changed in storage (truncated, re-encoded, mixed up). | Cluster the image again, and check how it is stored: as a binary blob, or base64 that is decoded in full. |
767
879
  | `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
768
880
  | The worker doesn't start under a bundler (`worker-failed`, or a 404 for `worker-thread.mjs`) | The bundler didn't emit the worker script (Angular, esbuild, Rollup). | Copy the package's `dist/` files and pass `createWorker({ script })`: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). |
769
- | Jest: "Must use import to load ES Module" | An older package version; this one loads in Jest's CommonJS mode. | Upgrade to the latest `3.0.0-beta`. |
770
- | `wasm-load-failed` mentioning a Content-Security-Policy | The page or extension forbids compiling WebAssembly. | Add `'wasm-unsafe-eval'` to `script-src`. |
881
+ | Jest: "Must use import to load ES Module" (or "Cannot use import statement" for `/worker`) | An older package version; this one loads in Jest's CommonJS mode, both entries. | Upgrade to the latest `3.0.0-beta`. |
882
+ | `wasm-load-failed` mentioning a Content-Security-Policy | The page or extension forbids compiling WebAssembly. | Add `'wasm-unsafe-eval'` to `script-src`: the page's for the worker entry's worker, also from a content script. |
883
+ | `wasm-load-failed`: "is not WebAssembly" | An error page (a 404, or a server's fallback page) was served in place of `clustering.wasm`. | Open the `.wasm` URL in the browser; copy the file where it is expected, or say where it is with `init({ wasm })`. |
884
+ | `worker-failed` with the worker entry from a CDN, under a CSP | `worker-src` allows `blob:` but not the CDN the worker imports from. | `worker-src blob: <the CDN's origin>`. |
771
885
  | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
772
886
 
773
887
  ## More
Binary file
package/dist/index.cjs CHANGED
@@ -15,7 +15,20 @@ Object.defineProperty(exports, "Palette", {
15
15
  return _shared.Palette;
16
16
  }
17
17
  });
18
- exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
18
+ Object.defineProperty(exports, "errorCodes", {
19
+ enumerable: true,
20
+ get: function () {
21
+ return _shared.errorCodes;
22
+ }
23
+ });
24
+ exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
25
+ Object.defineProperty(exports, "isCodedError", {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _shared.isCodedError;
29
+ }
30
+ });
31
+ exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = void 0;
19
32
  Object.defineProperty(exports, "version", {
20
33
  enumerable: true,
21
34
  get: function () {
@@ -41,8 +54,6 @@ const formatVersion = exports.formatVersion = _shared.latestVersion;
41
54
  // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
42
55
  // from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
43
56
  const tagOf = value => Object.prototype.toString.call(value);
44
- // (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
45
- const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
46
57
  const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
47
58
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
48
59
  const codes = {
@@ -135,18 +146,34 @@ const wasmLoadFailed = (cause, given) => {
135
146
  // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
136
147
  const where = typeof given === 'string' ? ` (${given})` : '';
137
148
  let advice;
138
- if (/Content.Security.Policy|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
149
+ if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
139
150
  // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
140
- advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to its script-src (in a browser extension, to content_security_policy.extension_pages in the manifest).";
151
+ // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
152
+ // does that for a script from another origin, a content script's included) follows the page's.
153
+ advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
141
154
  } else if (!hasSimd()) {
142
155
  advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
156
+ } else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
157
+ // What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
158
+ if (given === true) {
159
+ reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
160
+ advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
161
+ } else {
162
+ reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
163
+ advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
164
+ }
143
165
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
144
166
  reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
145
- advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).";
167
+ const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
168
+ advice = given ? `Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type.${blocked}` : `Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).${blocked}`;
146
169
  } else if (given) {
147
170
  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).`;
148
171
  } else if (isNodeLike) {
149
- advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
172
+ // The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
173
+ if (/Invalid URL/i.test(reason)) {
174
+ reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
175
+ }
176
+ 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.";
150
177
  } else {
151
178
  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 }).";
152
179
  }
@@ -212,6 +239,35 @@ const packagedWasm = async () => {
212
239
  return readFile(file);
213
240
  };
214
241
 
242
+ // In Node, init({ wasm }) given a path or a file: URL reads the file here and hands the glue its bytes. The glue reads files
243
+ // itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
244
+ // (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
245
+ // Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
246
+ const nodeWasmFile = async wasm => {
247
+ if (!isNodeLike) {
248
+ return null;
249
+ }
250
+ const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
251
+ if (text === null) {
252
+ return null;
253
+ }
254
+ const isFileUrl = /^file:/i.test(text);
255
+ // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
256
+ if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
257
+ return null;
258
+ }
259
+ const {
260
+ readFile
261
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
262
+ if (!isFileUrl) {
263
+ return readFile(text);
264
+ }
265
+ const {
266
+ fileURLToPath
267
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
268
+ return readFile(fileURLToPath(text));
269
+ };
270
+
215
271
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
216
272
  let loading = null;
217
273
 
@@ -240,7 +296,8 @@ const acquire = async options => {
240
296
  loading = (async () => {
241
297
  let instance;
242
298
  try {
243
- instance = await instantiate(wasm);
299
+ const file = await nodeWasmFile(wasm);
300
+ instance = await instantiate(file === null ? wasm : file);
244
301
  } catch (error) {
245
302
  // In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
246
303
  // build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
@@ -407,7 +464,7 @@ const load = image => {
407
464
  format: 'rgba'
408
465
  };
409
466
  }
410
- if (isImageData(image)) {
467
+ if ((0, _shared.isImageData)(image)) {
411
468
  if ((0, _shared.isDetached)(image.data)) {
412
469
  throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
413
470
  }
@@ -449,7 +506,7 @@ const load = image => {
449
506
  };
450
507
  };
451
508
  const getWrapper = image => {
452
- if (isImageData(image)) {
509
+ if ((0, _shared.isImageData)(image)) {
453
510
  // In the input's own class and colour space (see imageDataLike).
454
511
  return output => (0, _shared.imageDataLike)(image, new Uint8ClampedArray(output.buffer));
455
512
  }
package/dist/index.d.cts CHANGED
@@ -19,7 +19,7 @@ export type ErrorCode = 'invalid-argument' | 'invalid-clustering' | 'unsupported
19
19
  */
20
20
  export type ErrorArgument = 'image' | 'k' | 'clustering' | 'palette' | 'colorSpace' | 'options' | `options.${string}`;
21
21
 
22
- /** An `Error` thrown by this library. There is no class to test with `instanceof`: check `code`. */
22
+ /** An `Error` thrown by this library. There is no class to test with `instanceof`: use `isCodedError`, or check `code`. */
23
23
  export interface CodedError extends Error {
24
24
  code: ErrorCode;
25
25
  /**
@@ -30,6 +30,17 @@ export interface CodedError extends Error {
30
30
  argument?: ErrorArgument;
31
31
  }
32
32
 
33
+ /** Every `ErrorCode`, in a frozen array: for code that forwards or lists them (a wrapper package, an IPC bridge). */
34
+ export const errorCodes: readonly ErrorCode[];
35
+
36
+ /**
37
+ * Whether `value` is one of this library's errors: something with a string `message` and a `code` from `errorCodes`.
38
+ * Unlike checking `code` alone, it is false for Node's own errors (`'ENOENT'`) and for an abort (the signal's reason).
39
+ * It also accepts a plain object with those fields, which is what an error becomes after Electron's IPC or a
40
+ * `postMessage`; such an object has no `stack`, and is not an `instanceof Error`.
41
+ */
42
+ export function isCodedError(value: unknown): value is CodedError;
43
+
33
44
  /**
34
45
  * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
35
46
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export type ErrorCode = 'invalid-argument' | 'invalid-clustering' | 'unsupported
19
19
  */
20
20
  export type ErrorArgument = 'image' | 'k' | 'clustering' | 'palette' | 'colorSpace' | 'options' | `options.${string}`;
21
21
 
22
- /** An `Error` thrown by this library. There is no class to test with `instanceof`: check `code`. */
22
+ /** An `Error` thrown by this library. There is no class to test with `instanceof`: use `isCodedError`, or check `code`. */
23
23
  export interface CodedError extends Error {
24
24
  code: ErrorCode;
25
25
  /**
@@ -30,6 +30,17 @@ export interface CodedError extends Error {
30
30
  argument?: ErrorArgument;
31
31
  }
32
32
 
33
+ /** Every `ErrorCode`, in a frozen array: for code that forwards or lists them (a wrapper package, an IPC bridge). */
34
+ export const errorCodes: readonly ErrorCode[];
35
+
36
+ /**
37
+ * Whether `value` is one of this library's errors: something with a string `message` and a `code` from `errorCodes`.
38
+ * Unlike checking `code` alone, it is false for Node's own errors (`'ENOENT'`) and for an abort (the signal's reason).
39
+ * It also accepts a plain object with those fields, which is what an error becomes after Electron's IPC or a
40
+ * `postMessage`; such an object has no `stack`, and is not an `instanceof Error`.
41
+ */
42
+ export function isCodedError(value: unknown): value is CodedError;
43
+
33
44
  /**
34
45
  * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
35
46
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.