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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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}).`
@@ -291,7 +293,12 @@ const send = image => {
291
293
  if (pixels && (0, _shared.isDetached)(pixels)) {
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
  }
296
+ // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
297
+ if (pixels && pixels.byteLength >= _shared.maxBytes) {
298
+ throw (0, _shared.tooLarge)(pixels.byteLength);
299
+ }
294
300
  if ((0, _shared.isImageData)(image)) {
301
+ (0, _shared.checkImageDataPixels)(image);
295
302
  const data = image.data;
296
303
  return {
297
304
  data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
@@ -494,6 +501,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
494
501
  const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
495
502
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
496
503
 
504
+ // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
505
+ const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
506
+
497
507
  // `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
498
508
  const makeWorker = (options, allowScript) => {
499
509
  if (options === undefined) {
@@ -526,6 +536,13 @@ const makeWorker = (options, allowScript) => {
526
536
  let generation = 0;
527
537
  let startingGeneration = 0;
528
538
  let terminated = false;
539
+ // A worker created with createWorker() and then dropped without terminate() would keep its thread (and its memory) until
540
+ // the process or page ends: a running worker is never garbage-collected. So once the instance itself has been collected
541
+ // (`abandoned`), no call is in flight (`active`) and no handle is left (`liveHandles`), the thread is stopped. Nothing
542
+ // the worker's own listeners reach refers to `instance`, which is what lets it be collected while the thread runs.
543
+ let active = 0;
544
+ let liveHandles = 0;
545
+ let abandoned = false;
529
546
  let nextId = 1;
530
547
  let nextHandle = 1;
531
548
  const pending = new Map();
@@ -549,6 +566,12 @@ const makeWorker = (options, allowScript) => {
549
566
  // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
550
567
  // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
551
568
  const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
569
+ liveHandles--;
570
+ // The last thing keeping an abandoned worker going: stopping it frees everything, so there is nothing to release.
571
+ if (abandoned && liveHandles === 0) {
572
+ stopIfAbandoned();
573
+ return;
574
+ }
552
575
  if (!terminated) {
553
576
  invoke('release', [id], [], new Error()).catch(() => {});
554
577
  }
@@ -626,7 +649,7 @@ const makeWorker = (options, allowScript) => {
626
649
 
627
650
  // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
628
651
  // 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 = {}) => {
652
+ const run = async (method, args, transferable, origin, controls = {}) => {
630
653
  if (terminated) {
631
654
  throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
632
655
  }
@@ -653,8 +676,8 @@ const makeWorker = (options, allowScript) => {
653
676
  }
654
677
  const waitingFor = startingGeneration;
655
678
  const started = await starting;
679
+ // terminate() stops the worker that was starting itself, once (not once per call that waited for it).
656
680
  if (terminated) {
657
- started.terminate();
658
681
  throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
659
682
  }
660
683
  // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
@@ -674,6 +697,23 @@ const makeWorker = (options, allowScript) => {
674
697
  }
675
698
  return post(method, args, transferable, origin, controls);
676
699
  };
700
+
701
+ // Every call counts as in flight from the moment it is made (while the worker starts, too) until it settles, so an
702
+ // abandoned worker is never stopped under a call: `createWorker().getPalette(image)` keeps only the promise.
703
+ const invoke = (...args) => {
704
+ active++;
705
+ const settled = () => {
706
+ active--;
707
+ stopIfAbandoned();
708
+ };
709
+ return run(...args).then(value => {
710
+ settled();
711
+ return value;
712
+ }, error => {
713
+ settled();
714
+ throw error;
715
+ });
716
+ };
677
717
  const post = (method, args, transferable, origin, {
678
718
  signal,
679
719
  onProgress
@@ -825,12 +865,16 @@ const makeWorker = (options, allowScript) => {
825
865
  }
826
866
  const id = nextHandle++;
827
867
  const sent = ready() ? send(image) : take(send(image));
868
+ // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
869
+ // existing (see `abandoned`).
870
+ liveHandles++;
828
871
  try {
829
872
  await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
830
873
  signal,
831
874
  onProgress
832
875
  });
833
876
  } catch (error) {
877
+ liveHandles--;
834
878
  // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
835
879
  // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
836
880
  // is harmless, and this message follows the cluster call in the worker's queue.
@@ -879,6 +923,7 @@ const makeWorker = (options, allowScript) => {
879
923
  return;
880
924
  }
881
925
  released = true;
926
+ liveHandles--;
882
927
  if (reclaim) {
883
928
  reclaim.unregister(handle);
884
929
  }
@@ -891,6 +936,7 @@ const makeWorker = (options, allowScript) => {
891
936
  throw error;
892
937
  }
893
938
  }
939
+ stopIfAbandoned();
894
940
  }
895
941
  };
896
942
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -904,11 +950,10 @@ const makeWorker = (options, allowScript) => {
904
950
  })();
905
951
  };
906
952
 
907
- // Stops the worker. Calls still waiting are rejected, and later calls fail.
908
- instance.terminate = async () => {
909
- if (terminated) {
910
- return;
911
- }
953
+ // Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
954
+ // so a second terminate() made while the first is running also waits until the thread has gone.
955
+ let stopping = null;
956
+ const stop = () => stopping = stopping || (async () => {
912
957
  terminated = true;
913
958
  for (const call of pending.values()) {
914
959
  call.cleanup();
@@ -922,7 +967,24 @@ const makeWorker = (options, allowScript) => {
922
967
  (await starting).terminate();
923
968
  } catch (ignored) {/* it never started */}
924
969
  }
970
+ })();
971
+ // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
972
+ const stopIfAbandoned = () => {
973
+ if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
974
+ stop().catch(() => {});
975
+ }
925
976
  };
977
+ instance.terminate = stop;
978
+ // `await using worker = createWorker()` terminates it at the end of the block.
979
+ if (typeof Symbol.asyncDispose === 'symbol') {
980
+ instance[Symbol.asyncDispose] = stop;
981
+ }
982
+ if (allowScript === false && abandonment) {
983
+ abandonment.register(instance, () => {
984
+ abandoned = true;
985
+ stopIfAbandoned();
986
+ });
987
+ }
926
988
  return instance;
927
989
  };
928
990
  const createWorker = options => makeWorker(options, false);
@@ -965,4 +1027,9 @@ exports.quantizeToIndices = quantizeToIndices;
965
1027
  const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
966
1028
  exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
967
1029
  const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
968
- exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1030
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1031
+ // For file tracers (see scripts/patch-cjs.mjs); never called.
1032
+ // eslint-disable-next-line no-unused-vars
1033
+ var __agglomerativeTracedFiles = function () {
1034
+ return [__dirname + "/worker-thread.mjs"];
1035
+ };
package/dist/worker.d.cts CHANGED
@@ -24,11 +24,11 @@ export { isCodedError } from './index.cjs';
24
24
  export const version: string;
25
25
 
26
26
  /** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
27
- export const formatVersion: 3;
27
+ export const formatVersion: number;
28
28
 
29
29
  export type {
30
30
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
31
- ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
31
+ ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
32
32
  } from './index.cjs';
33
33
 
34
34
  /** Options for `createWorker`. */
@@ -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
@@ -24,11 +24,11 @@ export { isCodedError } from './index.js';
24
24
  export const version: string;
25
25
 
26
26
  /** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
27
- export const formatVersion: 3;
27
+ export const formatVersion: number;
28
28
 
29
29
  export type {
30
30
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
31
- ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
31
+ ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
32
32
  } from './index.js';
33
33
 
34
34
  /** Options for `createWorker`. */
@@ -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, maxBytes, tooLarge } from "./shared.mjs";
8
8
 
9
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
10
10
  export { version, Palette, Clustering, errorCodes, isCodedError } 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}).`
@@ -254,7 +256,12 @@ const send = image => {
254
256
  if (pixels && isDetached(pixels)) {
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
  }
259
+ // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
260
+ if (pixels && pixels.byteLength >= maxBytes) {
261
+ throw tooLarge(pixels.byteLength);
262
+ }
257
263
  if (isImageData(image)) {
264
+ checkImageDataPixels(image);
258
265
  const data = image.data;
259
266
  return {
260
267
  data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
@@ -457,6 +464,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
457
464
  const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
458
465
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
459
466
 
467
+ // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
468
+ const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
469
+
460
470
  // `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
461
471
  const makeWorker = (options, allowScript) => {
462
472
  if (options === undefined) {
@@ -489,6 +499,13 @@ const makeWorker = (options, allowScript) => {
489
499
  let generation = 0;
490
500
  let startingGeneration = 0;
491
501
  let terminated = false;
502
+ // A worker created with createWorker() and then dropped without terminate() would keep its thread (and its memory) until
503
+ // the process or page ends: a running worker is never garbage-collected. So once the instance itself has been collected
504
+ // (`abandoned`), no call is in flight (`active`) and no handle is left (`liveHandles`), the thread is stopped. Nothing
505
+ // the worker's own listeners reach refers to `instance`, which is what lets it be collected while the thread runs.
506
+ let active = 0;
507
+ let liveHandles = 0;
508
+ let abandoned = false;
492
509
  let nextId = 1;
493
510
  let nextHandle = 1;
494
511
  const pending = new Map();
@@ -512,6 +529,12 @@ const makeWorker = (options, allowScript) => {
512
529
  // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
513
530
  // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
514
531
  const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
532
+ liveHandles--;
533
+ // The last thing keeping an abandoned worker going: stopping it frees everything, so there is nothing to release.
534
+ if (abandoned && liveHandles === 0) {
535
+ stopIfAbandoned();
536
+ return;
537
+ }
515
538
  if (!terminated) {
516
539
  invoke('release', [id], [], new Error()).catch(() => {});
517
540
  }
@@ -589,7 +612,7 @@ const makeWorker = (options, allowScript) => {
589
612
 
590
613
  // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
591
614
  // 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 = {}) => {
615
+ const run = async (method, args, transferable, origin, controls = {}) => {
593
616
  if (terminated) {
594
617
  throw fail('worker-terminated', "Worker terminated.");
595
618
  }
@@ -616,8 +639,8 @@ const makeWorker = (options, allowScript) => {
616
639
  }
617
640
  const waitingFor = startingGeneration;
618
641
  const started = await starting;
642
+ // terminate() stops the worker that was starting itself, once (not once per call that waited for it).
619
643
  if (terminated) {
620
- started.terminate();
621
644
  throw fail('worker-terminated', "Worker terminated.");
622
645
  }
623
646
  // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
@@ -637,6 +660,23 @@ const makeWorker = (options, allowScript) => {
637
660
  }
638
661
  return post(method, args, transferable, origin, controls);
639
662
  };
663
+
664
+ // Every call counts as in flight from the moment it is made (while the worker starts, too) until it settles, so an
665
+ // abandoned worker is never stopped under a call: `createWorker().getPalette(image)` keeps only the promise.
666
+ const invoke = (...args) => {
667
+ active++;
668
+ const settled = () => {
669
+ active--;
670
+ stopIfAbandoned();
671
+ };
672
+ return run(...args).then(value => {
673
+ settled();
674
+ return value;
675
+ }, error => {
676
+ settled();
677
+ throw error;
678
+ });
679
+ };
640
680
  const post = (method, args, transferable, origin, {
641
681
  signal,
642
682
  onProgress
@@ -788,12 +828,16 @@ const makeWorker = (options, allowScript) => {
788
828
  }
789
829
  const id = nextHandle++;
790
830
  const sent = ready() ? send(image) : take(send(image));
831
+ // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
832
+ // existing (see `abandoned`).
833
+ liveHandles++;
791
834
  try {
792
835
  await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
793
836
  signal,
794
837
  onProgress
795
838
  });
796
839
  } catch (error) {
840
+ liveHandles--;
797
841
  // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
798
842
  // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
799
843
  // is harmless, and this message follows the cluster call in the worker's queue.
@@ -842,6 +886,7 @@ const makeWorker = (options, allowScript) => {
842
886
  return;
843
887
  }
844
888
  released = true;
889
+ liveHandles--;
845
890
  if (reclaim) {
846
891
  reclaim.unregister(handle);
847
892
  }
@@ -854,6 +899,7 @@ const makeWorker = (options, allowScript) => {
854
899
  throw error;
855
900
  }
856
901
  }
902
+ stopIfAbandoned();
857
903
  }
858
904
  };
859
905
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -867,11 +913,10 @@ const makeWorker = (options, allowScript) => {
867
913
  })();
868
914
  };
869
915
 
870
- // Stops the worker. Calls still waiting are rejected, and later calls fail.
871
- instance.terminate = async () => {
872
- if (terminated) {
873
- return;
874
- }
916
+ // Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
917
+ // so a second terminate() made while the first is running also waits until the thread has gone.
918
+ let stopping = null;
919
+ const stop = () => stopping = stopping || (async () => {
875
920
  terminated = true;
876
921
  for (const call of pending.values()) {
877
922
  call.cleanup();
@@ -885,7 +930,24 @@ const makeWorker = (options, allowScript) => {
885
930
  (await starting).terminate();
886
931
  } catch (ignored) {/* it never started */}
887
932
  }
933
+ })();
934
+ // An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
935
+ const stopIfAbandoned = () => {
936
+ if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
937
+ stop().catch(() => {});
938
+ }
888
939
  };
940
+ instance.terminate = stop;
941
+ // `await using worker = createWorker()` terminates it at the end of the block.
942
+ if (typeof Symbol.asyncDispose === 'symbol') {
943
+ instance[Symbol.asyncDispose] = stop;
944
+ }
945
+ if (allowScript === false && abandonment) {
946
+ abandonment.register(instance, () => {
947
+ abandoned = true;
948
+ stopIfAbandoned();
949
+ });
950
+ }
889
951
  return instance;
890
952
  };
891
953
  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.7",
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",