agglomerative-clustering 4.0.0-beta.2 → 4.0.0-beta.4

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.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, isCodedError, detachedError, isOptionsObject, isUint8Array, isUint8ClampedArray, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce, readHeader, checkImageBody, imageCopy } from "./shared.mjs";
7
+ import { version, fail, isCodedError, detachedError, isOptionsObject, isUint8Array, isUint8ClampedArray, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageError, readHeader, checkImageBody, imageCopy, checkK, checkPalette, checkNotEmpty, checkChoice, checkPixelArray, parseOptions, clusterOptions as clusterKeys, quantizeOptions as quantizeKeys, mapOptions as mapKeys, mapIndexOptions as mapIndexKeys } 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, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -138,7 +138,7 @@ const start = async (receive, chosen) => {
138
138
  // A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
139
139
  // start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
140
140
  const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
141
- const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
141
+ const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }). The worker's files can also be from different versions of agglomerative-clustering: serve all of dist/ from this version.";
142
142
  let worker,
143
143
  source = null;
144
144
  try {
@@ -195,11 +195,12 @@ const start = async (receive, chosen) => {
195
195
  });
196
196
  worker.on('message', receive);
197
197
  // 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.
198
+ const versions = " The worker's files can also be from different versions of agglomerative-clustering: serve all of dist/ from this version.";
198
199
  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)));
199
200
  // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
200
201
  const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
201
202
  worker.on('error', error => receive({
202
- failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
203
+ 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 }).${versions}` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.${versions}` : error.message
203
204
  }));
204
205
  worker.on('exit', code => receive({
205
206
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -258,6 +259,10 @@ const send = image => {
258
259
  // An image object goes through the main entry's own checks here (its fields read once, then shape, data, detached buffer, format,
259
260
  // sizes, unknown keys, premultiplied), so what can't be sent is reported as the main entry reports it, before anything is posted.
260
261
  // A function, a Symbol or a thenable gets the shape error rather than the structured clone's.
262
+ // A bare array has to be what the main entry accepts as one (the checks it makes before its options).
263
+ if (ArrayBuffer.isView(image)) {
264
+ checkPixelArray(image);
265
+ }
261
266
  if (!ArrayBuffer.isView(image) && !isImageData(image)) {
262
267
  const copy = imageCopy(image);
263
268
  if (copy === image) {
@@ -419,81 +424,68 @@ const initOptions = (options, allowScript) => {
419
424
  return checked;
420
425
  };
421
426
 
427
+ // What the options of a call are checked against: the image's data length, format and width (a bare array is RGBA).
428
+ const imageShape = sent => ArrayBuffer.isView(sent) ? {
429
+ data: sent,
430
+ format: 'rgba',
431
+ width: undefined
432
+ } : {
433
+ data: sent.data,
434
+ format: sent.format,
435
+ width: sent.width
436
+ };
437
+
438
+ // Checks a call's options exactly as the main entry does (the same parseOptions, `allowed` being the keys the function takes,
439
+ // `image` the shape of the image it maps, if any), so a wrong option is reported here, in the main entry's order and words,
440
+ // before anything is posted or a buffer is transferred. What it returns is what is sent: the options as one plain copy, and
441
+ // `parsed`, what parseOptions made of them.
422
442
  // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
423
443
  // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
424
- const takeControls = (options, ditherAllowed = true) => {
425
- // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
426
- // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
427
- if (!isOptionsObject(options)) {
444
+ const takeControls = (options, allowed, image) => {
445
+ if (options === undefined) {
428
446
  return {
429
447
  options,
430
448
  signal: undefined,
431
- onProgress: undefined
449
+ onProgress: undefined,
450
+ parsed: parseOptions(options, allowed, image)
432
451
  };
433
452
  }
453
+ // Anything but an ordinary object is rejected by parseOptions, as in the main entry. An ordinary one is copied once first:
454
+ // structured cloning drops inherited properties, and the copy is what gets validated and sent.
455
+ if (!isOptionsObject(options)) {
456
+ parseOptions(options, allowed, image);
457
+ }
434
458
  options = snapshot(options);
435
459
  // The dither setting is an object of its own, which structured cloning would copy without its inherited keys (or not
436
- // at all, for a Proxy or a function): read it here the way the main entry does, and send a plain copy.
437
- // A function that takes no dither option rejects the key whatever its value, as the main entry does: send a value that
438
- // can cross, for the worker's validation to name the option.
439
- if (!ditherAllowed && 'dither' in options) {
440
- options.dither = null;
441
- }
460
+ // at all, for a Proxy or a function): read it here the way the main entry does, once, and validate and send the copy.
442
461
  if (options.dither !== null && (typeof options.dither === 'object' || typeof options.dither === 'function' || typeof options.dither === 'symbol')) {
443
- // One read of each setting (a getter could answer differently twice): the copy is what is checked and sent.
444
- const copy = isOptionsObject(options.dither) ? Object.assign({}, snapshot(options.dither)) : options.dither;
445
- // A wrong setting is the worker's to report, after the image and k, as the main entry orders its checks. Only a
446
- // copy that can't be sent is reported here.
447
- try {
448
- parseDither(copy);
449
- } catch (error) {
450
- if (!sendable(copy)) {
451
- throw error;
452
- }
453
- }
454
- options.dither = copy;
462
+ options.dither = isOptionsObject(options.dither) ? Object.assign({}, snapshot(options.dither)) : options.dither;
455
463
  }
456
- // The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
457
- // A wrong one crosses as `null` instead, which the worker's validation
458
- // rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
459
- // those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
464
+ const parsed = parseOptions(options, allowed, image);
465
+ // Every value left is a primitive, a copy of the dither object or the signal and callback taken out here, so what is
466
+ // posted can be cloned. (The `cannot be sent` error in `unsendable` stays as a safety net for anything that still isn't.)
460
467
  const {
461
468
  signal,
462
469
  onProgress
463
470
  } = options;
464
- const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
465
- const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
466
471
  const {
467
472
  signal: _signal,
468
473
  onProgress: _onProgress,
469
474
  ...rest
470
475
  } = options;
471
- if (badSignal || badProgress) {
472
- return {
473
- options: {
474
- ...rest,
475
- ...(badSignal ? {
476
- signal: null
477
- } : {}),
478
- ...(badProgress ? {
479
- onProgress: null
480
- } : {})
481
- },
482
- signal: undefined,
483
- onProgress: undefined
484
- };
485
- }
486
476
  if (signal === undefined && onProgress === undefined) {
487
477
  return {
488
478
  options,
489
479
  signal,
490
- onProgress
480
+ onProgress,
481
+ parsed
491
482
  };
492
483
  }
493
484
  return {
494
485
  options: rest,
495
486
  signal,
496
- onProgress
487
+ onProgress,
488
+ parsed
497
489
  };
498
490
  };
499
491
 
@@ -512,24 +504,63 @@ const sendable = value => {
512
504
 
513
505
  // Where the options sit among a function's arguments after the image (see takeControls).
514
506
  const optionsPosition = {
515
- getClustering: 0,
516
- getPalette: 1,
517
- getSwatches: 1,
507
+ buildClustering: 0,
508
+ buildPalette: 1,
509
+ buildSwatches: 1,
518
510
  quantize: 1,
519
- quantizeFromClustering: 2,
520
511
  quantizeWithPalette: 1,
521
512
  quantizeToIndices: 1,
522
- quantizeToIndicesFromClustering: 2,
523
513
  quantizeToIndicesWithPalette: 1
524
514
  };
525
515
 
516
+ // The names of the arguments each call posts, for saying which one can't be sent.
517
+ const argumentNames = {
518
+ buildClustering: ['image', 'options'],
519
+ buildPalette: ['image', 'k', 'options'],
520
+ buildSwatches: ['image', 'k', 'options'],
521
+ quantize: ['image', 'k', 'options'],
522
+ quantizeToIndices: ['image', 'k', 'options'],
523
+ quantizeWithPalette: ['image', 'palette', 'options'],
524
+ quantizeToIndicesWithPalette: ['image', 'palette', 'options'],
525
+ init: ['options'],
526
+ cluster: [null, 'image', 'options'],
527
+ load: [null, 'clustering'],
528
+ handleGetPalette: [null, 'k'],
529
+ handleGetSwatches: [null, 'k'],
530
+ handleChooseFrom: [null, 'palette', 'k', 'options'],
531
+ handleQuantize: [null, 'k', 'options'],
532
+ handleQuantizeToIndices: [null, 'k', 'options'],
533
+ handleQuantizeWithPalette: [null, 'palette', 'options'],
534
+ handleQuantizeToIndicesWithPalette: [null, 'palette', 'options'],
535
+ handleQuantizeImage: [null, 'image', 'k', 'options'],
536
+ handleQuantizeToIndicesImage: [null, 'image', 'k', 'options']
537
+ };
538
+
539
+ // The error for a call whose message can't be cloned: the first argument that fails alone names itself.
540
+ const unsendable = (method, args, error) => {
541
+ const names = argumentNames[method] || [];
542
+ const index = args.findIndex((value, at) => names[at] && !sendable(value));
543
+ const cause = {
544
+ cause: error
545
+ };
546
+ return index < 0 ? Object.assign(fail('invalid-argument', `Invalid argument: it cannot be sent to the worker.`), cause) : Object.assign(fail('invalid-argument', `Invalid ${names[index]}: it cannot be sent to the worker.`, names[index]), cause);
547
+ };
548
+
526
549
  // Like fetch: an aborted call rejects with the signal's reason, an AbortError unless the caller gave another.
527
550
  const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
528
- const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
529
- const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
530
- // The functions that only cluster, and so take no dither option.
531
- const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
532
- const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
551
+
552
+ // The option keys each function takes (the main entry's lists).
553
+ const keysOf = {
554
+ buildClustering: clusterKeys,
555
+ buildPalette: clusterKeys,
556
+ buildSwatches: clusterKeys,
557
+ quantize: quantizeKeys,
558
+ quantizeToIndices: quantizeKeys,
559
+ quantizeWithPalette: mapKeys,
560
+ quantizeToIndicesWithPalette: mapIndexKeys
561
+ };
562
+ const imageFunctions = ['buildClustering', 'buildPalette', 'buildSwatches', 'quantize', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesWithPalette'];
563
+ const mappedImageFunctions = ['quantize', 'quantizeWithPalette'];
533
564
 
534
565
  // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
535
566
  const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
@@ -560,6 +591,9 @@ const makeWorker = (options, allowScript) => {
560
591
  wasm: initialWasm
561
592
  };
562
593
  let initialising = null;
594
+ // Whether the worker script has said it is this version (the first message to every worker), and that exchange.
595
+ let shaken = false;
596
+ let shaking = null;
563
597
  let connection = null;
564
598
  let starting = null;
565
599
  // Counts the workers this instance has started, so a late message or error from one it already dropped is ignored.
@@ -577,7 +611,7 @@ const makeWorker = (options, allowScript) => {
577
611
  let nextHandle = 1;
578
612
  const pending = new Map();
579
613
  // Whether a call made now is posted before it returns (see `own`).
580
- const ready = () => connection !== null && !initial;
614
+ const ready = () => connection !== null && shaken && !initial;
581
615
  // The image of a call made before the worker is ready: with `transfer: true` its buffer is moved out of the caller's
582
616
  // hands at once (a structured clone that transfers it, so the caller's array empties now, as it would on posting),
583
617
  // otherwise copied.
@@ -616,6 +650,8 @@ const makeWorker = (options, allowScript) => {
616
650
  connection = null;
617
651
  starting = null;
618
652
  initialising = null;
653
+ shaken = false;
654
+ shaking = null;
619
655
  if (initialWasm !== undefined) {
620
656
  initial = {
621
657
  wasm: initialWasm
@@ -716,6 +752,41 @@ const makeWorker = (options, allowScript) => {
716
752
  }
717
753
  connection = connection || started;
718
754
  }
755
+ if (!shaken) {
756
+ // The first message to a worker: its script must be this version's (an older thread answers `handshake` as an
757
+ // unknown method; a 3.4-3.8 one would otherwise run calls but never see their signals or progress callbacks).
758
+ // Nothing else is posted before it answers, so a mismatch is reported to every call waiting on the worker.
759
+ if (!shaking) {
760
+ const mine = generation;
761
+ shaking = post('handshake', [], [], origin).then(theirs => {
762
+ if (theirs === version) {
763
+ shaken = true;
764
+ return;
765
+ }
766
+ throw theirs;
767
+ }, error => {
768
+ // A coded error from the call itself (terminated, failed) is passed on; only a reply that is an error
769
+ // from the thread (an unknown method) means an older script.
770
+ if (error && error.code !== undefined && error.code !== 'invalid-argument') {
771
+ throw error;
772
+ }
773
+ throw undefined;
774
+ }).catch(theirs => {
775
+ if (theirs instanceof Error) {
776
+ throw theirs;
777
+ }
778
+ if (terminated) {
779
+ throw fail('worker-terminated', "Worker terminated.");
780
+ }
781
+ const reason = `The worker script is from another version of agglomerative-clustering (${typeof theirs === 'string' ? theirs : 'an older one'}; this is ${version}). Use the worker-thread.mjs from this version.`;
782
+ if (mine === generation) {
783
+ lose(reason);
784
+ }
785
+ throw fail('worker-failed', reason);
786
+ });
787
+ }
788
+ await shaking;
789
+ }
719
790
  if (initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined)) {
720
791
  initialising = initialising || post('init', [initial], [], origin).then(() => {
721
792
  initial = null;
@@ -818,10 +889,8 @@ const makeWorker = (options, allowScript) => {
818
889
  connection.unref();
819
890
  }
820
891
  // A value that can't be structured-cloned (a function, symbol or promise) is an invalid argument, as it
821
- // would be if the main entry were called with it.
822
- reject(error && error.name === 'DataCloneError' ? Object.assign(fail('invalid-argument', `Invalid argument: it cannot be sent to the worker (${error.message})`), {
823
- cause: error
824
- }) : error);
892
+ // would be if the main entry were called with it; the first argument that fails alone is named.
893
+ reject(error && error.name === 'DataCloneError' ? unsendable(method, args.map(mark), error) : error);
825
894
  }
826
895
  });
827
896
  };
@@ -831,12 +900,34 @@ const makeWorker = (options, allowScript) => {
831
900
  instance[name] = (image, ...rest) => {
832
901
  const origin = new Error();
833
902
  return (async () => {
903
+ // A bare RGB or grey array is refused first, as in the main entry (before the options are read, an abort is
904
+ // honoured, or anything is posted or a transfer can empty the array).
905
+ const bare = bareImageError(image);
906
+ if (bare) {
907
+ throw bare;
908
+ }
909
+ // then the rest of the image's checks (its fields are read once here), before the options, as in the main entry
910
+ const checked = send(image);
834
911
  const position = optionsPosition[name];
912
+ // then the argument before the options (k, or a palette), and the options, as the main entry orders them
913
+ const shape = imageShape(checked);
914
+ const byPalette = name.endsWith('WithPalette');
915
+ if (position === 1) {
916
+ if (byPalette) {
917
+ checkPalette(rest[0]);
918
+ } else {
919
+ checkK(rest[0]);
920
+ }
921
+ }
835
922
  const {
836
923
  options,
837
924
  signal,
838
- onProgress
839
- } = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
925
+ onProgress,
926
+ parsed
927
+ } = takeControls(rest[position], keysOf[name], shape);
928
+ if (byPalette) {
929
+ checkNotEmpty(rest[0], shape, name === 'quantizeToIndicesWithPalette' && parsed.transparent > 0 ? parsed.transparent : 1);
930
+ }
840
931
  let args = rest.slice();
841
932
  if (position < args.length) {
842
933
  args[position] = options;
@@ -845,7 +936,7 @@ const makeWorker = (options, allowScript) => {
845
936
  // The main entry reports a wrong argument before an abort, so the worker checks the arguments (a
846
937
  // copy, never transferred: an aborted call leaves the image with the caller) without doing the work.
847
938
  try {
848
- await invoke(name, [own(send(image)), ...args.map(own)], [], origin, {
939
+ await invoke(name, [own(checked), ...args.map(own)], [], origin, {
849
940
  check: true
850
941
  });
851
942
  } catch (error) {
@@ -855,12 +946,7 @@ const makeWorker = (options, allowScript) => {
855
946
  }
856
947
  throw abortReason(signal);
857
948
  }
858
- // The bare-image warning is decided here, on the caller's side and before a transfer can empty the
859
- // array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
860
- // silenced (PRINCIPLES "Warnings").
861
- const warning = bareImageWarning(image);
862
- const byteLength = warning ? image.byteLength : 0;
863
- let sent = send(image);
949
+ let sent = checked;
864
950
  if (!ready()) {
865
951
  sent = take(sent);
866
952
  args = args.map(own);
@@ -869,21 +955,10 @@ const makeWorker = (options, allowScript) => {
869
955
  signal,
870
956
  onProgress
871
957
  });
872
- if (warning) {
873
- warnOnce(warning, byteLength);
874
- }
875
958
  return mapped ? rebuild(image)(result) : result;
876
959
  })();
877
960
  };
878
961
  }
879
- for (const name of otherFunctions) {
880
- instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
881
- }
882
- // 3.4.0's names for the functions that cluster an image. The old names are the same functions, and they still name the
883
- // call on the wire, so a worker script copied from an older version still understands it.
884
- instance.buildClustering = instance.getClustering;
885
- instance.buildPalette = instance.getPalette;
886
- instance.buildSwatches = instance.getSwatches;
887
962
  instance.init = initArgs => {
888
963
  const origin = new Error();
889
964
  let checked;
@@ -912,7 +987,7 @@ const makeWorker = (options, allowScript) => {
912
987
  const looksLikeImage = value => value !== null && typeof value === 'object' && (isUint8Array(value) || isUint8ClampedArray(value) || isImageData(value) || 'data' in value);
913
988
  // Builds the handle object for what the worker keeps under `id`: `kind` is 'image' (from `cluster`: an image and its
914
989
  // clustering) or 'clustering' (from `load`: a clustering alone). `output` turns a mapped result back into the type of the image given.
915
- const makeHandle = (id, kind, output) => {
990
+ const makeHandle = (id, kind, output, shape) => {
916
991
  let released = false;
917
992
  // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
918
993
  // keeps it alive and it is not reclaimed while still in use.
@@ -923,13 +998,36 @@ const makeWorker = (options, allowScript) => {
923
998
  return invoke(method, [id, ...args], [], new Error(), controls);
924
999
  };
925
1000
  // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
926
- const withControls = (method, leading, mapOptions) => {
1001
+ // `lead` is what comes first: k or a palette, checked before the options, as in the main entry. `keys` are the options the
1002
+ // method takes, and `shape` the image of this handle (see imageShape).
1003
+ const withControls = (method, leading, mapOptions, keys, lead) => {
927
1004
  let taken;
928
1005
  try {
929
- taken = takeControls(mapOptions);
1006
+ if (lead === 'palette') {
1007
+ checkPalette(leading[0]);
1008
+ } else {
1009
+ checkK(leading[0]);
1010
+ }
1011
+ taken = takeControls(mapOptions, keys, shape);
930
1012
  } catch (error) {
931
1013
  return Promise.reject(error);
932
1014
  }
1015
+ // A palette with no colours is wrong only if the image has pixels to map to it, which the thread knows (this side keeps
1016
+ // the image's size only). So with a signal already aborted, the thread checks the call, as the functions do, and the abort
1017
+ // is reported when that finds nothing wrong.
1018
+ if (lead === 'palette' && leading[0].length === 0 && taken.signal && taken.signal.aborted) {
1019
+ const aborted = taken.signal;
1020
+ return use(method, [...leading, taken.options], {
1021
+ check: true
1022
+ }).then(() => {
1023
+ throw abortReason(aborted);
1024
+ }, error => {
1025
+ if (isCodedError(error) && error.argument !== undefined) {
1026
+ throw error;
1027
+ }
1028
+ throw abortReason(aborted);
1029
+ });
1030
+ }
933
1031
  return use(method, [...leading, taken.options], {
934
1032
  signal: taken.signal,
935
1033
  onProgress: taken.onProgress
@@ -937,29 +1035,34 @@ const makeWorker = (options, allowScript) => {
937
1035
  };
938
1036
  // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
939
1037
  // as in the main entry, rather than silently ignored.
940
- const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
1038
+ const plain = (method, name, args, extra) => {
1039
+ // k first, then the options that aren't taken, as the main entry's cuts check them
1040
+ try {
1041
+ if (args.length > 0) {
1042
+ checkK(args[0]);
1043
+ }
1044
+ } catch (error) {
1045
+ return Promise.reject(error);
1046
+ }
1047
+ return extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
1048
+ };
941
1049
  // An image where k belongs is a mix-up between the two kinds of handle: say so, rather than "k must be an integer".
942
1050
  const imageAsK = (name, k) => looksLikeImage(k) ? Promise.reject(fail('invalid-argument', `Invalid k: this handle holds an image (from worker.cluster) and maps it with ${name}(k); pass k, not an image. To map other images with a stored clustering, use worker.load(clustering).`, 'k')) : null;
943
1051
  const handle = {
944
1052
  getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
945
1053
  getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
946
1054
  getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
947
- // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given crosses as null for
948
- // the thread to reject with the main entry's own error.
949
- // That relies on the thread injecting a progress poster only for calls that have one (see `optionsIndex` in
950
- // worker-thread.js): the null is then the only onProgress it sees, so its own option check rejects it.
1055
+ // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given is rejected here, by
1056
+ // the same check.
951
1057
  chooseFrom: (palette, k, chooseOptions) => {
952
1058
  let taken;
953
1059
  try {
954
- taken = takeControls(chooseOptions, false);
1060
+ checkChoice(palette, k);
1061
+ taken = takeControls(chooseOptions, ['colorSpace', 'signal']);
955
1062
  } catch (error) {
956
1063
  return Promise.reject(error);
957
1064
  }
958
- const sent = taken.onProgress !== undefined ? {
959
- ...taken.options,
960
- onProgress: null
961
- } : taken.options;
962
- return use('handleChooseFrom', [palette, k, sent], {
1065
+ return use('handleChooseFrom', [palette, k, taken.options], {
963
1066
  signal: taken.signal
964
1067
  });
965
1068
  },
@@ -987,15 +1090,15 @@ const makeWorker = (options, allowScript) => {
987
1090
  if (kind === 'image') {
988
1091
  Object.assign(handle, {
989
1092
  getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
990
- quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions)))(),
991
- quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions),
992
- quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
993
- quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions)
1093
+ quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions, mapKeys, 'k')))(),
1094
+ quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions, mapIndexKeys, 'k'),
1095
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions, mapKeys, 'palette')),
1096
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions, mapIndexKeys, 'palette')
994
1097
  });
995
1098
  }
996
1099
  if (kind === 'clustering') {
997
1100
  // The handle holds no image: each call maps the image it is given, and returns the type of that image.
998
- const mapping = (name, method, mapped) => (image, k, mapOptions) => {
1101
+ const mapping = (name, method, mapped, keys) => (image, k, mapOptions) => {
999
1102
  if (typeof image === 'number') {
1000
1103
  return Promise.reject(fail('invalid-argument', "Invalid image: this handle holds a clustering, not an image (from worker.load); pass the image, then k.", 'image'));
1001
1104
  }
@@ -1004,15 +1107,21 @@ const makeWorker = (options, allowScript) => {
1004
1107
  if (released || !handle) {
1005
1108
  throw fail('invalid-handle', "Invalid handle: it was released.");
1006
1109
  }
1110
+ const bare = bareImageError(image);
1111
+ if (bare) {
1112
+ throw bare;
1113
+ }
1114
+ const checked = send(image);
1115
+ checkK(k);
1007
1116
  const {
1008
1117
  options,
1009
1118
  signal,
1010
1119
  onProgress
1011
- } = takeControls(mapOptions);
1120
+ } = takeControls(mapOptions, keys, imageShape(checked));
1012
1121
  if (signal && signal.aborted) {
1013
1122
  // As the functions on the worker do: a wrong argument is reported before the abort.
1014
1123
  try {
1015
- await invoke(method, [id, own(send(image)), k, options], [], origin, {
1124
+ await invoke(method, [id, own(checked), k, options], [], origin, {
1016
1125
  check: true
1017
1126
  });
1018
1127
  } catch (error) {
@@ -1022,9 +1131,7 @@ const makeWorker = (options, allowScript) => {
1022
1131
  }
1023
1132
  throw abortReason(signal);
1024
1133
  }
1025
- const warning = bareImageWarning(image);
1026
- const byteLength = warning ? image.byteLength : 0;
1027
- let sent = send(image);
1134
+ let sent = checked;
1028
1135
  const ahead = !ready();
1029
1136
  if (ahead) {
1030
1137
  sent = take(sent);
@@ -1033,15 +1140,12 @@ const makeWorker = (options, allowScript) => {
1033
1140
  signal,
1034
1141
  onProgress
1035
1142
  });
1036
- if (warning) {
1037
- warnOnce(warning, byteLength);
1038
- }
1039
1143
  return mapped ? rebuild(image)(result) : result;
1040
1144
  })();
1041
1145
  };
1042
1146
  Object.assign(handle, {
1043
- quantize: mapping('quantize', 'handleQuantizeImage', true),
1044
- quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false)
1147
+ quantize: mapping('quantize', 'handleQuantizeImage', true, mapKeys),
1148
+ quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false, mapIndexKeys)
1045
1149
  });
1046
1150
  }
1047
1151
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -1055,21 +1159,26 @@ const makeWorker = (options, allowScript) => {
1055
1159
  };
1056
1160
 
1057
1161
  // Clusters `image` and keeps it, with its clustering, in the worker.
1058
- instance.cluster = (image, clusterOptions) => {
1162
+ instance.cluster = (image, givenOptions) => {
1059
1163
  const origin = new Error();
1060
1164
  return (async () => {
1165
+ // The image is checked before the options and the abort, as the main entry does.
1166
+ const bare = bareImageError(image);
1167
+ if (bare) {
1168
+ throw bare;
1169
+ }
1170
+ const checked = send(image);
1171
+ const shape = imageShape(checked);
1061
1172
  const {
1062
1173
  options,
1063
1174
  signal,
1064
1175
  onProgress
1065
- } = takeControls(clusterOptions, false);
1176
+ } = takeControls(givenOptions, clusterKeys, shape);
1066
1177
  if (signal && signal.aborted) {
1067
1178
  throw abortReason(signal);
1068
1179
  }
1069
1180
  const id = nextHandle++;
1070
- const warning = bareImageWarning(image);
1071
- const byteLength = warning ? image.byteLength : 0;
1072
- const sent = ready() ? send(image) : take(send(image));
1181
+ const sent = ready() ? checked : take(checked);
1073
1182
  // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
1074
1183
  // existing (see `abandoned`).
1075
1184
  liveHandles++;
@@ -1088,10 +1197,13 @@ const makeWorker = (options, allowScript) => {
1088
1197
  }
1089
1198
  throw error;
1090
1199
  }
1091
- if (warning) {
1092
- warnOnce(warning, byteLength);
1093
- }
1094
- return makeHandle(id, 'image', rebuild(image));
1200
+ // The handle keeps the image's size, not its bytes (a transferred buffer is empty by now).
1201
+ return makeHandle(id, 'image', rebuild(image), {
1202
+ ...shape,
1203
+ data: {
1204
+ length: shape.data.length
1205
+ }
1206
+ });
1095
1207
  })();
1096
1208
  };
1097
1209
 
@@ -1173,17 +1285,9 @@ export const terminate = async () => {
1173
1285
  };
1174
1286
  export const init = (...args) => sharedWorker().init(...args);
1175
1287
  export const buildClustering = (...args) => sharedWorker().buildClustering(...args);
1176
- export const getClustering = buildClustering;
1177
1288
  export const buildPalette = (...args) => sharedWorker().buildPalette(...args);
1178
- export const getPalette = buildPalette;
1179
- export const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
1180
1289
  export const buildSwatches = (...args) => sharedWorker().buildSwatches(...args);
1181
- export const getSwatches = buildSwatches;
1182
- export const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
1183
- export const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
1184
1290
  export const quantize = (...args) => sharedWorker().quantize(...args);
1185
- export const quantizeFromClustering = (...args) => sharedWorker().quantizeFromClustering(...args);
1186
1291
  export const quantizeWithPalette = (...args) => sharedWorker().quantizeWithPalette(...args);
1187
1292
  export const quantizeToIndices = (...args) => sharedWorker().quantizeToIndices(...args);
1188
- export const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
1189
1293
  export const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "4.0.0-beta.2",
3
+ "version": "4.0.0-beta.4",
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",
@@ -74,7 +74,7 @@
74
74
  }
75
75
  },
76
76
  "engines": {
77
- "node": "^20.19.0 || >=22.12.0"
77
+ "node": ">=22.12.0"
78
78
  },
79
79
  "files": [
80
80
  "dist/",