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

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
@@ -163,6 +163,8 @@ const { explained } = await getClusteringInfo(clustering); // null only for a
163
163
  const k = (explained ?? []).findIndex((share) => share >= 0.99) + 1;
164
164
  ```
165
165
 
166
+ How many to ask for: 5 to 8 for a set of swatches to show. To *pick* from them (an accent colour, a theme), ask for more, 12 to 16: a small vivid area, such as a red sign in a street scene, only gets a colour of its own once the bigger areas have been split. Each colour is the average of its cluster, so it is a little less saturated than the image's most vivid pixels, and a white background comes back as a near-white such as `[254, 254, 254]` rather than exactly `#ffffff`. On a smooth single-hue photo no colour has a large share (the shares fall as `k` grows), so judge the heaviest swatch against the others, not by a fixed share. See [Picking colours from swatches](#picking-colours-from-swatches).
167
+
166
168
  ### GIFs and palette PNGs
167
169
 
168
170
  `quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`.
@@ -362,8 +364,9 @@ Palettes are flat RGB bytes, the compact form; each format an encoder or UI want
362
364
  // [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
363
365
  const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
364
366
 
365
- // A CSS colour, and a 0xRRGGBB number
367
+ // A CSS colour, a '#rrggbb' string and a 0xRRGGBB number
366
368
  const css = (i) => `rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`;
369
+ const hexString = (i) => '#' + Array.from(palette.subarray(3 * i, 3 * i + 3), (v) => v.toString(16).padStart(2, '0')).join('');
367
370
  const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
368
371
 
369
372
  // Swatches with their share of the image (the palette is in split order, not sorted by share: sort `swatches` by `share` to put the biggest first)
@@ -390,6 +393,30 @@ const rankedIndices = indices.map((index) => rank[index]);
390
393
  const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
391
394
  ```
392
395
 
396
+ #### Picking colours from swatches
397
+
398
+ The library answers which colours an image has and how much of each; choosing among them (a vivid accent, text that contrasts with a background) is colour arithmetic that a colour library already does well. With [culori](https://culorijs.org/):
399
+
400
+ ```js
401
+ import { getSwatches } from 'agglomerative-clustering';
402
+ import { converter, wcagContrast, formatHex } from 'culori';
403
+
404
+ const oklch = converter('oklch');
405
+ const { palette, shares } = await getSwatches(image, 12);
406
+ const swatches = Array.from(shares, (share, i) => {
407
+ const color = { mode: 'rgb', r: palette[3 * i] / 255, g: palette[3 * i + 1] / 255, b: palette[3 * i + 2] / 255 };
408
+ return { hex: formatHex(color), share, ...oklch(color) }; // l (0-1), c (chroma), h (hue)
409
+ }).sort((a, b) => b.share - a.share); // heaviest first
410
+
411
+ const background = swatches[0];
412
+ // The most colourful swatch that covers at least 2% of the image, as an accent
413
+ const accent = swatches.filter((s) => s.share >= 0.02 && s !== background).sort((a, b) => b.c - a.c)[0];
414
+ // Text: black or white, whichever contrasts more with the background
415
+ const text = wcagContrast(background.hex, '#000') > wcagContrast(background.hex, '#fff') ? '#000' : '#fff';
416
+ ```
417
+
418
+ The colours come back as sRGB bytes whatever `colorSpace` they were clustered in; that option only changes how pixels are grouped. For picks by lightness, chroma or hue, convert them as above (OKLCH is the perceptual form of OKLab). Choose the colour space you cluster in as in [Choosing a colour space](#choosing-a-colour-space): the picks can differ between the two, since each gives different averages.
419
+
393
420
  ### Coming from color-thief, node-vibrant, image-q or get-image-colors
394
421
 
395
422
  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.
@@ -424,6 +451,8 @@ ImageData // from a canvas: always RGBA, widt
424
451
 
425
452
  > **A bare `Uint8Array` is read as RGBA**, like `ImageData`. RGB bytes passed bare are misread, with no error when their length happens to be a multiple of 4. Pass them as `{ data, format: 'rgb', width }`, or add an alpha channel (sharp's `.ensureAlpha()`).
426
453
 
454
+ > **Pixels are 8-bit sRGB with straight alpha**, as `getImageData()` gives them. Convert anything else first: premultiplied pixels (from some native and WebGL APIs) back to straight alpha, 16-bit or floating-point pixels (16-bit PNGs, HDR) to 8 bits (sharp: `.toColourspace('srgb').raw({ depth: 'uchar' })`; pngjs: `inputHasAlpha` and its 8-bit output), and gray or gray-and-alpha pixels to RGBA (sharp's `.toColourspace('srgb').ensureAlpha()`). A gray buffer passed as it is gets misread, with no error when its length is a multiple of 4. Apply a photo's EXIF orientation (sharp's `.rotate()`) and colour profile when decoding; the library doesn't read either. An `ImageData` in another pixel format (Chromium's `pixelFormat: 'rgba-float16'`) is rejected with `invalid-argument`: ask for `getImageData(x, y, w, h, { pixelFormat: 'rgba-unorm8' })`.
455
+
427
456
  > **Image files are not pixels.** A bare `Uint8Array` that starts like a PNG, JPEG, GIF, WebP, BMP, TIFF, AVIF or HEIC file (from `fs.readFile` or `fetch`) is rejected with `invalid-argument` naming the format. Decode it first: a canvas or `createImageBitmap` in a browser, sharp or pngjs in Node. Only bare arrays are checked, so if raw pixels really do begin like a file header, pass `{ data, format: 'rgba' }`. Decoding is [planned](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md).
428
457
 
429
458
  The functions that return an image give back the type they were given: a `Uint8Array`, `ImageData`, or an object with the same `format` (and `width` and `height`). In TypeScript the result type follows the input (`ImageResult<I>`). Palettes come back as a `Palette`, clusterings as a `Clustering`, and the other results are `Swatches`, `IndexedImage` and `ClusteringInfo` objects.
@@ -498,12 +527,12 @@ Give one or the other: `transparent` replaces `alpha`, so naming both is an erro
498
527
  The cutoff decides which side a half-transparent pixel falls on. With the default (128), a soft drop shadow under 50% opacity disappears, and the darker part of it becomes solid; raise the cutoff (`transparent: 200`) to drop more of it, or lower it to keep more.
499
528
 
500
529
  ### Palette and Clustering
501
- The palettes and clusterings this library returns are ordinary `Uint8Array`s with a hidden tag: what they are and, for a palette, the colour space it was made in. Anything that takes bytes takes them, and their `constructor` is `Uint8Array`, so `expect(palette).toEqual(new Uint8Array([...]))` passes in your tests. The tags buy three things:
530
+ The palettes and clusterings this library returns are ordinary `Uint8Array`s with a hidden tag: what they are and, for a palette, the colour space it was made in. Anything that takes bytes takes them, and their `constructor` is `Uint8Array`, so `expect(palette).toEqual(new Uint8Array([...]))` passes in your tests. The tags buy four things:
502
531
 
503
532
  - **A palette maps in the space it was made in.** `quantizeWithPalette(image, palette)` matches an OKLab palette in OKLab without being told; name a `colorSpace` to override it. Plain bytes are matched in RGB.
504
533
  - **A clustering can't be passed as a palette**, or the other way round. TypeScript rejects it, and at run time it throws (`invalid-argument` or `invalid-clustering`), with no guessing about bytes.
505
534
  - **`new Palette(bytes, colorSpace)` and `new Clustering(bytes)` give bytes their type back**, and check them: `new Palette([300, 0, 0])` throws rather than wrapping 300 to 44, and `new Clustering(bytes)` throws `invalid-clustering` unless they are one. The functions still accept a clustering as plain bytes, so stored clusterings keep working in JavaScript; TypeScript wants the constructor.
506
- - **A clustering is checked before it is used.** Clusterings carry a checksum, so stored bytes that came back damaged (truncated, a changed byte, a lossy base64 round trip) are reported as `invalid-clustering` rather than cut into a wrong palette.
535
+ - **A clustering is checked before it is used.** Clusterings carry a checksum, so stored bytes that came back damaged (truncated, a changed byte, a lossy base64 round trip) are reported as `invalid-clustering` rather than cut into a wrong palette. It is checked the first time an array is used, so bytes changed in place after that aren't caught. Clusterings from 2.x have no checksum. It catches accidents, not tampering (anyone can recompute it): a clustering or palette from an untrusted user can't crash the library or make it hang, but it can describe any palette it likes.
507
536
 
508
537
  ```js
509
538
  import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
@@ -539,7 +568,7 @@ const clustering = await getClustering(image, {
539
568
  });
540
569
  ```
541
570
 
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.
571
+ - **Slices.** With either option, clustering runs in slices of about 10 ms (a large photo has a few unsliced steps of up to 150 ms in between; an image with millions of distinct colours, longer: see [Performance and limits](#performance-and-limits)), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
543
572
  - **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.
544
573
  - **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`.
545
574
  - **Progress** is approximate, never goes backwards, and ends at exactly 1.
@@ -556,7 +585,7 @@ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`
556
585
  | `invalid-argument` | A bad image, `k`, option or palette. |
557
586
  | `invalid-clustering` | Bytes that aren't a clustering this version can read, or a stored clustering that came back damaged (its checksum or its records don't fit). |
558
587
  | `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`). |
559
- | `out-of-memory` | The WebAssembly module couldn't allocate. |
588
+ | `out-of-memory` | The WebAssembly module couldn't allocate: an image with very many colours, or pixel data over its 2 GB (the message gives the size). |
560
589
  | `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. |
561
590
  | `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. |
562
591
 
@@ -580,7 +609,9 @@ Messages are for people and may change. The worker entry fails the same way as t
580
609
  `agglomerative-clustering/worker` exports every function above, run in one shared worker started on first use, plus `terminate()`, which stops it (the next call starts a new one), and `createWorker(options?)`, which starts a worker of your own. A worker has every function as a method, plus:
581
610
 
582
611
  - **`cluster(image, options?)`** keeps the image and its clustering in the worker, behind a handle with `getClustering()`, `getPalette(k)`, `getSwatches(k)`, `getClusteringInfo()`, `quantize(k, options?)`, `quantizeToIndices(k, options?)`, `quantizeWithPalette(palette, options?)` and `quantizeToIndicesWithPalette(palette, options?)`. A palette of plain bytes is matched in the handle's colour space, and `quantizeToIndices` uses the cutoff it was clustered with. Free it with `release()`, or declare it with `await using handle = await worker.cluster(image)`; a dropped handle is freed only when the garbage collector gets to it.
583
- - **`terminate()`** stops the worker and rejects the calls still waiting.
612
+ - **`terminate()`** stops the worker and rejects the calls still waiting. `await using worker = createWorker()` calls it at the end of the block.
613
+
614
+ **Terminate the workers you create.** A worker's thread, and the memory its last images needed, stay until `terminate()`: a running worker is never garbage-collected, so a server or page that creates a worker per request and drops it gathers threads. Keep a few workers and reuse them (see [Performance and limits](#performance-and-limits)), or use the shared worker, which the exported functions use. As a safety net, a worker you dropped is stopped some time after the garbage collector has collected it, once no call is running on it and no handle from it is left, but when that happens is up to the engine (it may be never, in a process with little memory pressure).
584
615
 
585
616
  `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.
586
617
 
@@ -691,7 +722,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
691
722
 
692
723
  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.
693
724
 
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).
725
+ 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, the AWS Lambda Node image, pnpm and Yarn Plug'n'Play, SvelteKit, Nuxt, Astro, React Router, Angular, Next.js and Parcel 2 (see below).
695
726
 
696
727
  ### From a CDN, without a build step
697
728
 
@@ -738,6 +769,21 @@ The package exports the file as `agglomerative-clustering/clustering.wasm`, so a
738
769
 
739
770
  SvelteKit (adapter-node) and Nuxt (Nitro's node-server) need no configuration, in development and production builds: the worker entry for pages, the main entry in server routes. Importing either entry during server rendering is safe, and `createWorker()` starts no thread until its first call. On Nitro's Cloudflare preset, turn on `nitro: { experimental: { wasm: true } }` and pass the module from `import wasm from 'agglomerative-clustering/clustering.wasm?module'` to `init`, as for the Edge runtime below.
740
771
 
772
+ ### Serverless functions: AWS Lambda, Vercel, Netlify
773
+
774
+ Both entries run in Node functions (checked in the AWS Lambda Node 20 image, with a read-only code directory, and with the file tracers Vercel and Netlify use). Unbundled, with `node_modules` in the package or a layer, nothing is needed. Bundled:
775
+
776
+ - **An ES module bundle** finds `clustering.wasm` next to itself: copy `node_modules/agglomerative-clustering/dist/clustering.wasm` beside the bundle. **A CommonJS bundle** has lost the package's own location: pass `init({ wasm: path })`, with a path to the copy you ship.
777
+ - **The worker entry** needs `worker-thread.mjs` and the files it imports (`index.mjs`, `shared.mjs`, `clustering.js`, `clustering.wasm`): leave the package external, or ship a copy of `dist/` and pass `createWorker({ script: path })`. Netlify's esbuild bundler moves them apart, so list the package in `external_node_modules`.
778
+ - **Size and cold starts:** the files a function needs are about 180 KB (235 KB with the worker). Loading the module takes 10 to 70 ms, and a first palette of a 1-megapixel image at `precision: 6` came 0.3 to 0.5 s after a cold start; calling `init()` early doesn't make the first palette faster.
779
+ - **Edge functions** (Vercel's edge runtime, Cloudflare) can't compile WebAssembly while they run: import the module as described for [Next.js](#nextjs) and [Cloudflare Workers](#deno-bun-and-cloudflare-workers).
780
+
781
+ ### pnpm, Yarn Plug'n'Play and monorepos
782
+
783
+ pnpm (isolated or hoisted) and Yarn Plug'n'Play need nothing for the main entry. Under Plug'n'Play the package stays in its zip archive, and the worker entry's thread loads its ES modules from there only through Yarn's loader: run with `yarn node` (or `node --require ./.pnp.cjs --loader ./.pnp.loader.mjs`), or `yarn unplug agglomerative-clustering`. Yarn 4 holds back versions published in the last day by default, so to try a release on its first day set `npmMinimalAgeGate: 0` in `.yarnrc.yml`.
784
+
785
+ Two versions in one process (a monorepo whose packages depend on different releases) each load their own module and don't share state; clusterings and palettes pass between them, and `isCodedError` recognises either one's errors.
786
+
741
787
  ### Next.js
742
788
 
743
789
  Checked with Next.js 16, under Turbopack and webpack, in production builds:
@@ -766,7 +812,7 @@ Checked with Next.js 16, under Turbopack and webpack, in production builds:
766
812
 
767
813
  ### Angular, esbuild, Rollup and other bundlers
768
814
 
769
- The main entry works in all of them. The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's `dist/` files out as static assets and say where they are:
815
+ The main entry works in all of them, except that an Angular production build needs `init({ wasm })` (below). The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's `dist/` files out as static assets and say where they are:
770
816
 
771
817
  ```js
772
818
  import { createWorker } from 'agglomerative-clustering/worker';
@@ -776,7 +822,7 @@ const worker = createWorker({
776
822
  });
777
823
  ```
778
824
 
779
- - **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above.
825
+ - **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above. Production builds don't emit `clustering.wasm` for the main entry either, so in the browser call `init({ wasm: '/assets/agglomerative-clustering/clustering.wasm' })` before the first call (the dev server works without it). With SSR, the server bundle finds the package's files from the directory the server starts in: start it from the project directory, or give the server its own `init({ wasm: path })`. zone.js needs nothing.
780
826
 
781
827
  ```json
782
828
  "assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
@@ -825,7 +871,7 @@ Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wa
825
871
  - **Vitest** needs no configuration, in node, jsdom, happy-dom and browser mode. **Storybook** (Vite builder) works as it is.
826
872
  - **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
873
  - **jsdom and happy-dom** have no `ImageData` (install `canvas`, `@napi-rs/canvas` or `skia-canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
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.
874
+ - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends (or until the garbage collector gets to a dropped `createWorker()`, which may not happen in a test run).
829
875
  - **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })` (`isCodedError` accepts them).
830
876
  - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and stay the same within a major version: snapshot them. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
831
877
  - Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
@@ -858,11 +904,14 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
858
904
  ```
859
905
 
860
906
  - **Small images wait behind large ones** in a shared pool. If you serve both, give large uploads a pool of their own.
861
- - **Memory:** one image can need up to 2 GB in a worker, so a pool of four can peak near 8 GB on hostile input; a pixel cap and `precision: 6` keep it to a fraction of that. Memory comes back after a large image (below).
907
+ - **Memory:** one image can need up to 2 GB in a worker, so a pool of four can peak near 8 GB on hostile input; a pixel cap and `precision: 6` keep it to a fraction of that. Memory comes back after a large image, but not at once (below).
908
+ - **Address space:** each WebAssembly instance (the main entry's, and one per worker) reserves about 10 GB of *virtual* memory up front on 64-bit engines, of which it uses only what it needs. A virtual-memory limit (`ulimit -v`) refuses that reservation, which shows as `wasm-load-failed`; limit resident memory instead. A container's memory limit (a cgroup's `memory.max`, Docker's `--memory`) applies to what is used, but when it is reached the kernel kills the process: there is no `out-of-memory` error to catch, so cap the image size below it.
862
909
  - **Stored clusterings:** make them with `precision: 6`. An exact clustering of a noisy 4-megapixel image is 78 MB, against 5.5 MB at `precision: 6`. Read back, wrap the bytes once with `new Clustering(bytes)` and keep that object while you use it: its checksum is checked the first time an object is used (2 to 3 ms for a photo's clustering).
863
910
  - Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
864
911
 
865
- **Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes 2 to 8 s exact (0.2 to 0.9 million distinct colours) and 0.1 to 0.4 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. (Times are from an idle machine; a busy or throttled one, a laptop on battery or a CI runner can be several times slower.) One WebAssembly instance can use up to 2 GB; an image that needs more is rejected with `out-of-memory`, and later calls work normally. WebAssembly memory only grows, so after a call that leaves it above 256 MB the library replaces the instance (the next call loads a fresh one, in milliseconds): a server's memory comes back down after a huge image instead of staying at its peak.
912
+ **Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes 2 to 8 s exact (0.2 to 0.9 million distinct colours) and 0.1 to 0.4 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. (Times are from an idle machine; a busy or throttled one, a laptop on battery or a CI runner can be several times slower.) One WebAssembly instance can use up to 2 GB, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA: 22000 × 22000 works); an image that needs more is rejected with `out-of-memory`, and later calls work normally. WebAssembly memory only grows, so after a call that leaves it above 256 MB the library drops the instance (the next call loads a fresh one, in milliseconds). The engine frees the old instance's memory at its next garbage collection, which in an idle process or worker can be much later: a worker that clustered 12 megapixels of noise held about 1 GB until it had served about a hundred more calls. `terminate()` frees a worker's memory at once.
913
+
914
+ The unsliced steps between slices (see [Cancelling and progress](#cancelling-and-progress)) take up to about 150 ms on a 12-megapixel photo, but grow with the number of distinct colours: on 12 megapixels of noise at full precision one takes over a second, and progress moves unevenly. `precision: 6` keeps them short.
866
915
 
867
916
  ### Troubleshooting
868
917
 
@@ -882,6 +931,10 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
882
931
  | `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
932
  | `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
933
  | `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>`. |
934
+ | `worker-failed` in a serverless function, "Cannot find module … worker-thread.mjs" | The bundler or file tracer left the worker's files out. | Leave the package external, or ship `dist/` and pass `createWorker({ script })`: see [Serverless functions](#serverless-functions-aws-lambda-vercel-netlify). |
935
+ | `worker-failed` under Yarn Plug'n'Play, a path inside a `.zip` | Node can't load the worker's ES modules from the zip without Yarn's loader. | Run with `yarn node`, or `yarn unplug agglomerative-clustering`. |
936
+ | `wasm-load-failed` under `ulimit -v` | Each instance reserves about 10 GB of address space. | Limit resident memory instead (see [Performance and limits](#performance-and-limits)). |
937
+ | Threads and memory grow in a long-running process | `createWorker()` workers that were dropped without `terminate()`. | Reuse a few workers, or terminate each one. |
885
938
  | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
886
939
 
887
940
  ## More
Binary file
package/dist/index.cjs CHANGED
@@ -127,6 +127,11 @@ const hasSimd = () => {
127
127
  // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
128
128
  // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
129
129
  const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
130
+ // A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
131
+ // Deno Deploy): only those have a document, a worker scope or a browser's user agent.
132
+ const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
133
+ // Where the advice for a server runtime ends: a deployment that left the .wasm behind.
134
+ const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
130
135
  // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
131
136
  const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
132
137
  const wasmLoadFailed = (cause, given) => {
@@ -146,7 +151,14 @@ const wasmLoadFailed = (cause, given) => {
146
151
  // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
147
152
  const where = typeof given === 'string' ? ` (${given})` : '';
148
153
  let advice;
149
- if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
154
+ if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
155
+ // Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
156
+ advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
157
+ } else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
158
+ // A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
159
+ // though it only uses what it needs; an address-space limit refuses that reservation.
160
+ advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
161
+ } else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
150
162
  // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
151
163
  // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
152
164
  // does that for a script from another origin, a content script's included) follows the page's.
@@ -162,6 +174,10 @@ const wasmLoadFailed = (cause, given) => {
162
174
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
163
175
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
164
176
  }
177
+ } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
178
+ // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
179
+ reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
180
+ advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
165
181
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
166
182
  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)';
167
183
  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).";
@@ -173,7 +189,13 @@ const wasmLoadFailed = (cause, given) => {
173
189
  if (/Invalid URL/i.test(reason)) {
174
190
  reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
175
191
  }
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.";
192
+ advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
193
+ } else if (!isBrowserLike()) {
194
+ // A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
195
+ if (/Invalid URL/i.test(reason)) {
196
+ reason = "the package can't tell where clustering.wasm is in this runtime";
197
+ }
198
+ advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
177
199
  } else {
178
200
  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 }).";
179
201
  }
@@ -468,6 +490,7 @@ const load = image => {
468
490
  if ((0, _shared.isDetached)(image.data)) {
469
491
  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');
470
492
  }
493
+ (0, _shared.checkImageDataPixels)(image);
471
494
  return {
472
495
  data: held(bytes(image.data)),
473
496
  format: 'rgba',
@@ -699,6 +722,25 @@ const checkNotEmpty = (palette, image, cutoff) => {
699
722
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
700
723
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
701
724
 
725
+ // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
726
+ // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
727
+ // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
728
+ const maxBytes = 2 ** 31;
729
+ const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
730
+ const tooLarge = bytes => (0, _shared.fail)('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
731
+
732
+ // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
733
+ const allocate = (wasm, length) => {
734
+ if (length >= maxBytes) {
735
+ throw tooLarge(length);
736
+ }
737
+ const pointer = wasm._malloc(length);
738
+ if (!pointer) {
739
+ throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
740
+ }
741
+ return pointer;
742
+ };
743
+
702
744
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
703
745
  // freeing everything afterwards.
704
746
  const call = (wasm, buffers, fn) => {
@@ -707,10 +749,7 @@ const call = (wasm, buffers, fn) => {
707
749
  let aborted = false;
708
750
  try {
709
751
  for (const buffer of buffers) {
710
- const pointer = wasm._malloc(buffer.length);
711
- if (!pointer) {
712
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
713
- }
752
+ const pointer = allocate(wasm, buffer.length);
714
753
  pointers.push(pointer);
715
754
  wasm.HEAPU8.set(buffer, pointer);
716
755
  }
@@ -795,10 +834,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
795
834
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
796
835
  const clusterInSlices = async (wasm, image, o, report, share) => {
797
836
  checkAborted(o.signal);
798
- const imagePointer = wasm._malloc(image.data.length);
799
- if (!imagePointer) {
800
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
801
- }
837
+ const imagePointer = allocate(wasm, image.data.length);
802
838
  let job = 0;
803
839
  let aborted = false;
804
840
  try {
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData } from "./shared.mjs";
2
+ import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
3
3
 
4
4
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
5
5
  export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
@@ -84,6 +84,11 @@ const hasSimd = () => {
84
84
  // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
85
85
  // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
86
86
  const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
87
+ // A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
88
+ // Deno Deploy): only those have a document, a worker scope or a browser's user agent.
89
+ const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
90
+ // Where the advice for a server runtime ends: a deployment that left the .wasm behind.
91
+ const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
87
92
  // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
88
93
  const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
89
94
  const wasmLoadFailed = (cause, given) => {
@@ -103,7 +108,14 @@ const wasmLoadFailed = (cause, given) => {
103
108
  // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
104
109
  const where = typeof given === 'string' ? ` (${given})` : '';
105
110
  let advice;
106
- if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
111
+ if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
112
+ // Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
113
+ advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
114
+ } else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
115
+ // A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
116
+ // though it only uses what it needs; an address-space limit refuses that reservation.
117
+ advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
118
+ } else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
107
119
  // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
108
120
  // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
109
121
  // does that for a script from another origin, a content script's included) follows the page's.
@@ -119,6 +131,10 @@ const wasmLoadFailed = (cause, given) => {
119
131
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
120
132
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
121
133
  }
134
+ } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
135
+ // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
136
+ reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
137
+ advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
122
138
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
123
139
  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)';
124
140
  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).";
@@ -130,7 +146,13 @@ const wasmLoadFailed = (cause, given) => {
130
146
  if (/Invalid URL/i.test(reason)) {
131
147
  reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
132
148
  }
133
- 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.";
149
+ advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
150
+ } else if (!isBrowserLike()) {
151
+ // A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
152
+ if (/Invalid URL/i.test(reason)) {
153
+ reason = "the package can't tell where clustering.wasm is in this runtime";
154
+ }
155
+ advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
134
156
  } else {
135
157
  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 }).";
136
158
  }
@@ -424,6 +446,7 @@ const load = image => {
424
446
  if (isDetached(image.data)) {
425
447
  throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
426
448
  }
449
+ checkImageDataPixels(image);
427
450
  return {
428
451
  data: held(bytes(image.data)),
429
452
  format: 'rgba',
@@ -655,6 +678,25 @@ const checkNotEmpty = (palette, image, cutoff) => {
655
678
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
656
679
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
657
680
 
681
+ // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
682
+ // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
683
+ // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
684
+ const maxBytes = 2 ** 31;
685
+ const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
686
+ const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
687
+
688
+ // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
689
+ const allocate = (wasm, length) => {
690
+ if (length >= maxBytes) {
691
+ throw tooLarge(length);
692
+ }
693
+ const pointer = wasm._malloc(length);
694
+ if (!pointer) {
695
+ throw fail('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
696
+ }
697
+ return pointer;
698
+ };
699
+
658
700
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
659
701
  // freeing everything afterwards.
660
702
  const call = (wasm, buffers, fn) => {
@@ -663,10 +705,7 @@ const call = (wasm, buffers, fn) => {
663
705
  let aborted = false;
664
706
  try {
665
707
  for (const buffer of buffers) {
666
- const pointer = wasm._malloc(buffer.length);
667
- if (!pointer) {
668
- throw fail('out-of-memory', "Failed to allocate WASM memory.");
669
- }
708
+ const pointer = allocate(wasm, buffer.length);
670
709
  pointers.push(pointer);
671
710
  wasm.HEAPU8.set(buffer, pointer);
672
711
  }
@@ -751,10 +790,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
751
790
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
752
791
  const clusterInSlices = async (wasm, image, o, report, share) => {
753
792
  checkAborted(o.signal);
754
- const imagePointer = wasm._malloc(image.data.length);
755
- if (!imagePointer) {
756
- throw fail('out-of-memory', "Failed to allocate WASM memory.");
757
- }
793
+ const imagePointer = allocate(wasm, image.data.length);
758
794
  let job = 0;
759
795
  let aborted = false;
760
796
  try {
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
9
+ exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = void 0;
10
10
  // Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
11
11
  // header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
12
12
  // './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
13
13
 
14
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
15
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
16
- const version = exports.version = '3.0.0-beta.5';
16
+ const version = exports.version = '3.0.0-beta.6';
17
17
  const colorSpaces = exports.colorSpaces = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -73,10 +73,21 @@ const isDetached = view => {
73
73
  exports.isDetached = isDetached;
74
74
  const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
75
75
 
76
+ // ImageData can hold other pixel formats than 8-bit RGBA (Chromium's pixelFormat: 'rgba-float16', with a Float16Array of
77
+ // pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
78
+ exports.isImageData = isImageData;
79
+ const checkImageDataPixels = image => {
80
+ if (isUint8ClampedArray(image.data)) {
81
+ return;
82
+ }
83
+ const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
84
+ throw fail('invalid-argument', `Invalid image: this ImageData doesn't hold 8-bit RGBA pixels${format}, and the library reads only those. Ask for 8-bit pixels with getImageData(x, y, width, height, { pixelFormat: 'rgba-unorm8' }), or draw it to a canvas with the default format and take getImageData() from that.`, 'image');
85
+ };
86
+
76
87
  // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
77
88
  // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
78
89
  // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
79
- exports.isImageData = isImageData;
90
+ exports.checkImageDataPixels = checkImageDataPixels;
80
91
  const imageDataLike = (like, pixels) => {
81
92
  const {
82
93
  width,
@@ -348,7 +359,10 @@ const readHeader = clustering => {
348
359
  if (version === 3 && length >= 13) {
349
360
  const headerLength = clustering[2],
350
361
  recordLength = clustering[3];
351
- if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
362
+ // Header lengths are 22 (every release) or 13 (the fixture from before 3.0.0-beta.1, kept readable by the format
363
+ // rules), or longer from a later release that adds fields. 14 to 20 was never written: it is a damaged length, which
364
+ // would also put the checksum field out of reach, so the checksum couldn't catch it.
365
+ if ((headerLength === 13 || headerLength >= checksumAt + 4) && recordLength >= 21 && headerLength <= length) {
352
366
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
353
367
  // doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
354
368
  if (clustering[4] > 1 || clustering[6] > 1) {
@@ -357,8 +371,8 @@ const readHeader = clustering => {
357
371
  const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
358
372
  const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
359
373
  if (padding < 9) {
360
- // Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
361
- // makes one look that short skips this check, but then the records don't line up, which the replay reports.
374
+ // A 13-byte header (from before 3.0.0-beta.1) has no checksum field. A damaged header length of 13 skips this
375
+ // check, but then the records don't line up, which the replay reports.
362
376
  if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
363
377
  const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
364
378
  if (stored !== 0 && stored !== crc32(clustering)) {
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.0.0-beta.5';
7
+ export const version = '3.0.0-beta.6';
8
8
  export const colorSpaces = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -57,6 +57,16 @@ export const isDetached = view => {
57
57
  // jsdom, skia-canvas, whose tag is plain [object Object]).
58
58
  export const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
59
59
 
60
+ // ImageData can hold other pixel formats than 8-bit RGBA (Chromium's pixelFormat: 'rgba-float16', with a Float16Array of
61
+ // pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
62
+ export const checkImageDataPixels = image => {
63
+ if (isUint8ClampedArray(image.data)) {
64
+ return;
65
+ }
66
+ const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
67
+ throw fail('invalid-argument', `Invalid image: this ImageData doesn't hold 8-bit RGBA pixels${format}, and the library reads only those. Ask for 8-bit pixels with getImageData(x, y, width, height, { pixelFormat: 'rgba-unorm8' }), or draw it to a canvas with the default format and take getImageData() from that.`, 'image');
68
+ };
69
+
60
70
  // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
61
71
  // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
62
72
  // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
@@ -323,7 +333,10 @@ export const readHeader = clustering => {
323
333
  if (version === 3 && length >= 13) {
324
334
  const headerLength = clustering[2],
325
335
  recordLength = clustering[3];
326
- if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
336
+ // Header lengths are 22 (every release) or 13 (the fixture from before 3.0.0-beta.1, kept readable by the format
337
+ // rules), or longer from a later release that adds fields. 14 to 20 was never written: it is a damaged length, which
338
+ // would also put the checksum field out of reach, so the checksum couldn't catch it.
339
+ if ((headerLength === 13 || headerLength >= checksumAt + 4) && recordLength >= 21 && headerLength <= length) {
327
340
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
328
341
  // doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
329
342
  if (clustering[4] > 1 || clustering[6] > 1) {
@@ -332,8 +345,8 @@ export const readHeader = clustering => {
332
345
  const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
333
346
  const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
334
347
  if (padding < 9) {
335
- // Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
336
- // makes one look that short skips this check, but then the records don't line up, which the replay reports.
348
+ // A 13-byte header (from before 3.0.0-beta.1) has no checksum field. A damaged header length of 13 skips this
349
+ // check, but then the records don't line up, which the replay reports.
337
350
  if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
338
351
  const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
339
352
  if (stored !== 0 && stored !== crc32(clustering)) {
package/dist/worker.cjs CHANGED
@@ -228,9 +228,11 @@ const start = async (receive, chosen) => {
228
228
  });
229
229
  worker.on('message', receive);
230
230
  // A worker script that can't be found, or that can't find what it imports: a copy of dist/ split up or bundled away.
231
- const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module/.test(String(error.message)));
231
+ const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module|Qualified path resolution failed/.test(String(error.message)));
232
+ // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
233
+ const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
232
234
  worker.on('error', error => receive({
233
- failure: missing(error) ? `${error.message}. 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).` : error.message
235
+ 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
234
236
  }));
235
237
  worker.on('exit', code => receive({
236
238
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -292,6 +294,7 @@ const send = image => {
292
294
  throw (0, _shared.fail)('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
293
295
  }
294
296
  if ((0, _shared.isImageData)(image)) {
297
+ (0, _shared.checkImageDataPixels)(image);
295
298
  const data = image.data;
296
299
  return {
297
300
  data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
@@ -494,6 +497,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
494
497
  const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
495
498
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
496
499
 
500
+ // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
501
+ const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
502
+
497
503
  // `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
498
504
  const makeWorker = (options, allowScript) => {
499
505
  if (options === undefined) {
@@ -526,6 +532,13 @@ const makeWorker = (options, allowScript) => {
526
532
  let generation = 0;
527
533
  let startingGeneration = 0;
528
534
  let terminated = false;
535
+ // A worker created with createWorker() and then dropped without terminate() would keep its thread (and its memory) until
536
+ // the process or page ends: a running worker is never garbage-collected. So once the instance itself has been collected
537
+ // (`abandoned`), no call is in flight (`active`) and no handle is left (`liveHandles`), the thread is stopped. Nothing
538
+ // the worker's own listeners reach refers to `instance`, which is what lets it be collected while the thread runs.
539
+ let active = 0;
540
+ let liveHandles = 0;
541
+ let abandoned = false;
529
542
  let nextId = 1;
530
543
  let nextHandle = 1;
531
544
  const pending = new Map();
@@ -549,6 +562,12 @@ const makeWorker = (options, allowScript) => {
549
562
  // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
550
563
  // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
551
564
  const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
565
+ liveHandles--;
566
+ // The last thing keeping an abandoned worker going: stopping it frees everything, so there is nothing to release.
567
+ if (abandoned && liveHandles === 0) {
568
+ stopIfAbandoned();
569
+ return;
570
+ }
552
571
  if (!terminated) {
553
572
  invoke('release', [id], [], new Error()).catch(() => {});
554
573
  }
@@ -626,7 +645,7 @@ const makeWorker = (options, allowScript) => {
626
645
 
627
646
  // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
628
647
  // from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
629
- const invoke = async (method, args, transferable, origin, controls = {}) => {
648
+ const run = async (method, args, transferable, origin, controls = {}) => {
630
649
  if (terminated) {
631
650
  throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
632
651
  }
@@ -674,6 +693,23 @@ const makeWorker = (options, allowScript) => {
674
693
  }
675
694
  return post(method, args, transferable, origin, controls);
676
695
  };
696
+
697
+ // Every call counts as in flight from the moment it is made (while the worker starts, too) until it settles, so an
698
+ // abandoned worker is never stopped under a call: `createWorker().getPalette(image)` keeps only the promise.
699
+ const invoke = (...args) => {
700
+ active++;
701
+ const settled = () => {
702
+ active--;
703
+ stopIfAbandoned();
704
+ };
705
+ return run(...args).then(value => {
706
+ settled();
707
+ return value;
708
+ }, error => {
709
+ settled();
710
+ throw error;
711
+ });
712
+ };
677
713
  const post = (method, args, transferable, origin, {
678
714
  signal,
679
715
  onProgress
@@ -825,12 +861,16 @@ const makeWorker = (options, allowScript) => {
825
861
  }
826
862
  const id = nextHandle++;
827
863
  const sent = ready() ? send(image) : take(send(image));
864
+ // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
865
+ // existing (see `abandoned`).
866
+ liveHandles++;
828
867
  try {
829
868
  await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
830
869
  signal,
831
870
  onProgress
832
871
  });
833
872
  } catch (error) {
873
+ liveHandles--;
834
874
  // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
835
875
  // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
836
876
  // is harmless, and this message follows the cluster call in the worker's queue.
@@ -879,6 +919,7 @@ const makeWorker = (options, allowScript) => {
879
919
  return;
880
920
  }
881
921
  released = true;
922
+ liveHandles--;
882
923
  if (reclaim) {
883
924
  reclaim.unregister(handle);
884
925
  }
@@ -891,6 +932,7 @@ const makeWorker = (options, allowScript) => {
891
932
  throw error;
892
933
  }
893
934
  }
935
+ stopIfAbandoned();
894
936
  }
895
937
  };
896
938
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -905,7 +947,7 @@ const makeWorker = (options, allowScript) => {
905
947
  };
906
948
 
907
949
  // Stops the worker. Calls still waiting are rejected, and later calls fail.
908
- instance.terminate = async () => {
950
+ const stop = async () => {
909
951
  if (terminated) {
910
952
  return;
911
953
  }
@@ -923,6 +965,23 @@ const makeWorker = (options, allowScript) => {
923
965
  } catch (ignored) {/* it never started */}
924
966
  }
925
967
  };
968
+ // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
969
+ const stopIfAbandoned = () => {
970
+ if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
971
+ stop().catch(() => {});
972
+ }
973
+ };
974
+ instance.terminate = stop;
975
+ // `await using worker = createWorker()` terminates it at the end of the block.
976
+ if (typeof Symbol.asyncDispose === 'symbol') {
977
+ instance[Symbol.asyncDispose] = stop;
978
+ }
979
+ if (allowScript === false && abandonment) {
980
+ abandonment.register(instance, () => {
981
+ abandoned = true;
982
+ stopIfAbandoned();
983
+ });
984
+ }
926
985
  return instance;
927
986
  };
928
987
  const createWorker = options => makeWorker(options, false);
@@ -965,4 +1024,9 @@ exports.quantizeToIndices = quantizeToIndices;
965
1024
  const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
966
1025
  exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
967
1026
  const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
968
- exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1027
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1028
+ // For file tracers (see scripts/patch-cjs.mjs); never called.
1029
+ // eslint-disable-next-line no-unused-vars
1030
+ var __agglomerativeTracedFiles = function () {
1031
+ return [__dirname + "/worker-thread.mjs"];
1032
+ };
package/dist/worker.d.cts CHANGED
@@ -102,9 +102,16 @@ export interface AgglomerativeWorker {
102
102
  cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
103
103
  /** Stops the worker. Calls still waiting are rejected, and later calls fail. */
104
104
  terminate(): Promise<void>;
105
+ /** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
106
+ [Symbol.asyncDispose](): Promise<void>;
105
107
  }
106
108
 
107
- /** Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle. */
109
+ /**
110
+ * Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle.
111
+ * Call `terminate()` when you are done with it (or use `await using`): its thread and memory stay until then. As a
112
+ * safety net, a worker you dropped without terminating is stopped some time after it is garbage-collected, once no call
113
+ * is in flight and no handle from it is left; when that happens is up to the engine.
114
+ */
108
115
  export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
109
116
 
110
117
  /** Stops the shared worker used by the exports below, rejecting calls still waiting. The next call starts a new one. */
package/dist/worker.d.ts CHANGED
@@ -102,9 +102,16 @@ export interface AgglomerativeWorker {
102
102
  cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
103
103
  /** Stops the worker. Calls still waiting are rejected, and later calls fail. */
104
104
  terminate(): Promise<void>;
105
+ /** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
106
+ [Symbol.asyncDispose](): Promise<void>;
105
107
  }
106
108
 
107
- /** Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle. */
109
+ /**
110
+ * Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle.
111
+ * Call `terminate()` when you are done with it (or use `await using`): its thread and memory stay until then. As a
112
+ * safety net, a worker you dropped without terminating is stopped some time after it is garbage-collected, once no call
113
+ * is in flight and no handle from it is left; when that happens is up to the engine.
114
+ */
108
115
  export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
109
116
 
110
117
  /** Stops the shared worker used by the exports below, rejecting calls still waiting. The next call starts a new one. */
package/dist/worker.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
5
5
  // worker, started on first use.
6
6
 
7
- import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData } from "./shared.mjs";
7
+ import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
8
8
 
9
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
10
10
  export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
@@ -191,9 +191,11 @@ const start = async (receive, chosen) => {
191
191
  });
192
192
  worker.on('message', receive);
193
193
  // A worker script that can't be found, or that can't find what it imports: a copy of dist/ split up or bundled away.
194
- const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module/.test(String(error.message)));
194
+ const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module|Qualified path resolution failed/.test(String(error.message)));
195
+ // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
196
+ const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
195
197
  worker.on('error', error => receive({
196
- failure: missing(error) ? `${error.message}. 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).` : error.message
198
+ 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
197
199
  }));
198
200
  worker.on('exit', code => receive({
199
201
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -255,6 +257,7 @@ const send = image => {
255
257
  throw fail('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
256
258
  }
257
259
  if (isImageData(image)) {
260
+ checkImageDataPixels(image);
258
261
  const data = image.data;
259
262
  return {
260
263
  data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
@@ -457,6 +460,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
457
460
  const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
458
461
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
459
462
 
463
+ // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
464
+ const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
465
+
460
466
  // `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
461
467
  const makeWorker = (options, allowScript) => {
462
468
  if (options === undefined) {
@@ -489,6 +495,13 @@ const makeWorker = (options, allowScript) => {
489
495
  let generation = 0;
490
496
  let startingGeneration = 0;
491
497
  let terminated = false;
498
+ // A worker created with createWorker() and then dropped without terminate() would keep its thread (and its memory) until
499
+ // the process or page ends: a running worker is never garbage-collected. So once the instance itself has been collected
500
+ // (`abandoned`), no call is in flight (`active`) and no handle is left (`liveHandles`), the thread is stopped. Nothing
501
+ // the worker's own listeners reach refers to `instance`, which is what lets it be collected while the thread runs.
502
+ let active = 0;
503
+ let liveHandles = 0;
504
+ let abandoned = false;
492
505
  let nextId = 1;
493
506
  let nextHandle = 1;
494
507
  const pending = new Map();
@@ -512,6 +525,12 @@ const makeWorker = (options, allowScript) => {
512
525
  // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
513
526
  // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
514
527
  const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
528
+ liveHandles--;
529
+ // The last thing keeping an abandoned worker going: stopping it frees everything, so there is nothing to release.
530
+ if (abandoned && liveHandles === 0) {
531
+ stopIfAbandoned();
532
+ return;
533
+ }
515
534
  if (!terminated) {
516
535
  invoke('release', [id], [], new Error()).catch(() => {});
517
536
  }
@@ -589,7 +608,7 @@ const makeWorker = (options, allowScript) => {
589
608
 
590
609
  // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
591
610
  // from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
592
- const invoke = async (method, args, transferable, origin, controls = {}) => {
611
+ const run = async (method, args, transferable, origin, controls = {}) => {
593
612
  if (terminated) {
594
613
  throw fail('worker-terminated', "Worker terminated.");
595
614
  }
@@ -637,6 +656,23 @@ const makeWorker = (options, allowScript) => {
637
656
  }
638
657
  return post(method, args, transferable, origin, controls);
639
658
  };
659
+
660
+ // Every call counts as in flight from the moment it is made (while the worker starts, too) until it settles, so an
661
+ // abandoned worker is never stopped under a call: `createWorker().getPalette(image)` keeps only the promise.
662
+ const invoke = (...args) => {
663
+ active++;
664
+ const settled = () => {
665
+ active--;
666
+ stopIfAbandoned();
667
+ };
668
+ return run(...args).then(value => {
669
+ settled();
670
+ return value;
671
+ }, error => {
672
+ settled();
673
+ throw error;
674
+ });
675
+ };
640
676
  const post = (method, args, transferable, origin, {
641
677
  signal,
642
678
  onProgress
@@ -788,12 +824,16 @@ const makeWorker = (options, allowScript) => {
788
824
  }
789
825
  const id = nextHandle++;
790
826
  const sent = ready() ? send(image) : take(send(image));
827
+ // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
828
+ // existing (see `abandoned`).
829
+ liveHandles++;
791
830
  try {
792
831
  await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
793
832
  signal,
794
833
  onProgress
795
834
  });
796
835
  } catch (error) {
836
+ liveHandles--;
797
837
  // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
798
838
  // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
799
839
  // is harmless, and this message follows the cluster call in the worker's queue.
@@ -842,6 +882,7 @@ const makeWorker = (options, allowScript) => {
842
882
  return;
843
883
  }
844
884
  released = true;
885
+ liveHandles--;
845
886
  if (reclaim) {
846
887
  reclaim.unregister(handle);
847
888
  }
@@ -854,6 +895,7 @@ const makeWorker = (options, allowScript) => {
854
895
  throw error;
855
896
  }
856
897
  }
898
+ stopIfAbandoned();
857
899
  }
858
900
  };
859
901
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -868,7 +910,7 @@ const makeWorker = (options, allowScript) => {
868
910
  };
869
911
 
870
912
  // Stops the worker. Calls still waiting are rejected, and later calls fail.
871
- instance.terminate = async () => {
913
+ const stop = async () => {
872
914
  if (terminated) {
873
915
  return;
874
916
  }
@@ -886,6 +928,23 @@ const makeWorker = (options, allowScript) => {
886
928
  } catch (ignored) {/* it never started */}
887
929
  }
888
930
  };
931
+ // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
932
+ const stopIfAbandoned = () => {
933
+ if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
934
+ stop().catch(() => {});
935
+ }
936
+ };
937
+ instance.terminate = stop;
938
+ // `await using worker = createWorker()` terminates it at the end of the block.
939
+ if (typeof Symbol.asyncDispose === 'symbol') {
940
+ instance[Symbol.asyncDispose] = stop;
941
+ }
942
+ if (allowScript === false && abandonment) {
943
+ abandonment.register(instance, () => {
944
+ abandoned = true;
945
+ stopIfAbandoned();
946
+ });
947
+ }
889
948
  return instance;
890
949
  };
891
950
  export const createWorker = options => makeWorker(options, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.0.0-beta.5",
3
+ "version": "3.0.0-beta.6",
4
4
  "description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
5
5
  "license": "MIT",
6
6
  "author": "Rohan Fredriksson",