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

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/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.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.imageCopy = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.formatHint = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkSize = exports.checkPalette = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = void 0;
9
+ exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.imageCopy = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.formatHint = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkSize = exports.checkPalette = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.channels = exports.bareLayout = exports.bareImageError = exports.alphaModes = 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 = '4.0.0-beta.2';
16
+ const version = exports.version = '4.0.0-beta.3';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -533,7 +533,7 @@ const sniffImageFormat = bytes => {
533
533
  // The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
534
534
  // with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
535
535
  // as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
536
- // PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
536
+ // PRINCIPLES), only reported, as an error (a warning in 3.x).
537
537
  //
538
538
  // The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
539
539
  // bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
@@ -542,8 +542,8 @@ const sniffImageFormat = bytes => {
542
542
  // but where it changes its bytes come in equal triples at a step of 3 and not of 4.
543
543
  // - Grey and alpha (2 bytes a pixel): smooth at a step of 2 and rough at a step of 1, since grey and alpha bytes alternate.
544
544
  // - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
545
- // RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; it then keeps the
546
- // rgb-as-rgba code, whose text covers grey too.
545
+ // RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
546
+ // covers grey too.
547
547
  // Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
548
548
  // samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
549
549
  // array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
@@ -640,80 +640,28 @@ const bareLayout = d => {
640
640
  exports.bareLayout = bareLayout;
641
641
  const looksLikeRgb = d => bareLayout(d) === 'rgb';
642
642
 
643
- // Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
643
+ // The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
644
+ // clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
645
+ // errors for its image and both entries share this one order.
644
646
  exports.looksLikeRgb = looksLikeRgb;
645
- const warned = new Set();
646
- const bareCodes = {
647
- rgb: 'rgb-as-rgba',
648
- grey: 'gray-as-rgba',
649
- 'grey-alpha': 'gray-as-rgba'
647
+ const bareText = {
648
+ rgb: n => `Invalid image: these ${n} bytes look like RGB (3 per pixel) or grey, not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA: format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
649
+ grey: n => `Invalid image: these ${n} bytes look like grey (1 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices. Expand 8-bit grey to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
650
+ 'grey-alpha': n => `Invalid image: these ${n} bytes look like grey and alpha (2 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG with alpha. Expand it to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`
650
651
  };
651
-
652
- // The warning a bare image calls for, as {code, layout}, or null. It skips everything the main entry rejects (palettes
653
- // and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
654
- // about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
655
- // code because its own was already used: it is classified first, and only then is its code checked.
656
- const bareImageWarning = image => {
657
- if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
652
+ const bareImageError = image => {
653
+ if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
658
654
  return null;
659
655
  }
660
656
  if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
661
657
  return null;
662
658
  }
663
659
  const layout = bareLayout(image);
664
- return layout === null || warned.has(bareCodes[layout]) ? null : {
665
- code: bareCodes[layout],
666
- layout
667
- };
668
- };
669
-
670
- // The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
671
- // process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
672
- // emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
673
- // navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
674
- // keeps Parcel from adding one.
675
- exports.bareImageWarning = bareImageWarning;
676
- const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
677
- const warningText = {
678
- 'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel), or grey, passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA; format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`,
679
- 'gray-as-rgba': (byteLength, layout) => (layout === 'grey-alpha' ? `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey and alpha bytes (2 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG with alpha.` : `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey bytes (1 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices.`) + ` Expand ${layout === 'grey-alpha' ? 'it' : '8-bit grey'} to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()). There is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
680
- };
681
- // `warning` is what bareImageWarning returned: {code, layout}.
682
- const warnOnce = ({
683
- code,
684
- layout
685
- }, byteLength) => {
686
- if (warned.has(code)) {
687
- return;
688
- }
689
- warned.add(code);
690
- const message = warningText[code](byteLength, layout);
691
- const runtime = globalThis.process;
692
- if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
693
- runtime.emitWarning(message, {
694
- type: 'AgglomerativeClusteringWarning',
695
- code
696
- });
697
- } else if (typeof console !== 'undefined') {
698
- console.warn(`agglomerative-clustering [${code}]: ${message}`);
699
- }
700
- };
701
- // The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
702
- // also skips the sampling.
703
- exports.warnOnce = warnOnce;
704
- const silenceWarnings = () => {
705
- for (const code of Object.keys(warningText)) {
706
- warned.add(code);
707
- }
708
- };
709
- // For tests.
710
- exports.silenceWarnings = silenceWarnings;
711
- const resetWarnings = () => {
712
- warned.clear();
660
+ return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
713
661
  };
714
662
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
715
663
  // `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
716
- exports.resetWarnings = resetWarnings;
664
+ exports.bareImageError = bareImageError;
717
665
  const inspect = Symbol.for('nodejs.util.inspect.custom');
718
666
  const view = label => function (depth, options, nodeInspect) {
719
667
  const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
@@ -733,7 +681,7 @@ const markPalette = (bytes, colorSpace) => {
733
681
  });
734
682
  return bytes;
735
683
  };
736
- // Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
684
+ // Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
737
685
  // non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
738
686
  // `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
739
687
  // calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
@@ -748,14 +696,14 @@ const setEngine = value => {
748
696
  engine = value;
749
697
  }
750
698
  };
751
- // Each method's call shape and its function form, for messages.
699
+ // Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
752
700
  exports.setEngine = setEngine;
753
701
  const methodNames = {
754
- getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
755
- getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
756
- getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
757
- quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
758
- quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)'],
702
+ getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
703
+ getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
704
+ getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
705
+ quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
706
+ quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
759
707
  chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
760
708
  };
761
709
  // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
@@ -879,6 +827,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
879
827
  // those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
880
828
  function Clustering(...args) {
881
829
  const [source] = args;
830
+ // A palette gets the same hint as from every other function, before its bytes are copied.
831
+ if (isPalette(source)) {
832
+ readHeader(source);
833
+ }
882
834
  // Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
883
835
  // would coerce. A plain array must hold byte values, as for a palette.
884
836
  const isBuffer = isArrayBufferLike(source);
@@ -978,7 +930,7 @@ const notAClustering = clustering => {
978
930
  };
979
931
  const readHeader = clustering => {
980
932
  if (isPalette(clustering)) {
981
- throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
933
+ throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette or clustering.getPalette(k); a clustering comes from buildClustering.", 'clustering');
982
934
  }
983
935
  if (!isUint8Array(clustering)) {
984
936
  throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
@@ -1040,12 +992,12 @@ const readHeader = clustering => {
1040
992
  throw notAClustering(clustering);
1041
993
  };
1042
994
 
1043
- // Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
995
+ // Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
1044
996
  // image, and quantize maps such an image the same way.
1045
997
  exports.readHeader = readHeader;
1046
998
  const checkPalette = palette => {
1047
999
  if (isClustering(palette)) {
1048
- throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
1000
+ throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with clustering.getPalette(k), or map with clustering.quantize(image, k).", 'palette');
1049
1001
  }
1050
1002
  if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
1051
1003
  throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
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 = '4.0.0-beta.2';
7
+ export const version = '4.0.0-beta.3';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -496,7 +496,7 @@ export const sniffImageFormat = bytes => {
496
496
  // The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
497
497
  // with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
498
498
  // as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
499
- // PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
499
+ // PRINCIPLES), only reported, as an error (a warning in 3.x).
500
500
  //
501
501
  // The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
502
502
  // bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
@@ -505,8 +505,8 @@ export const sniffImageFormat = bytes => {
505
505
  // but where it changes its bytes come in equal triples at a step of 3 and not of 4.
506
506
  // - Grey and alpha (2 bytes a pixel): smooth at a step of 2 and rough at a step of 1, since grey and alpha bytes alternate.
507
507
  // - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
508
- // RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; it then keeps the
509
- // rgb-as-rgba code, whose text covers grey too.
508
+ // RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
509
+ // covers grey too.
510
510
  // Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
511
511
  // samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
512
512
  // array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
@@ -601,72 +601,23 @@ export const bareLayout = d => {
601
601
  };
602
602
  export const looksLikeRgb = d => bareLayout(d) === 'rgb';
603
603
 
604
- // Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
605
- const warned = new Set();
606
- const bareCodes = {
607
- rgb: 'rgb-as-rgba',
608
- grey: 'gray-as-rgba',
609
- 'grey-alpha': 'gray-as-rgba'
604
+ // The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
605
+ // clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
606
+ // errors for its image and both entries share this one order.
607
+ const bareText = {
608
+ rgb: n => `Invalid image: these ${n} bytes look like RGB (3 per pixel) or grey, not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA: format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
609
+ grey: n => `Invalid image: these ${n} bytes look like grey (1 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices. Expand 8-bit grey to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
610
+ 'grey-alpha': n => `Invalid image: these ${n} bytes look like grey and alpha (2 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG with alpha. Expand it to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`
610
611
  };
611
-
612
- // The warning a bare image calls for, as {code, layout}, or null. It skips everything the main entry rejects (palettes
613
- // and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
614
- // about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
615
- // code because its own was already used: it is classified first, and only then is its code checked.
616
- export const bareImageWarning = image => {
617
- if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
612
+ export const bareImageError = image => {
613
+ if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
618
614
  return null;
619
615
  }
620
616
  if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
621
617
  return null;
622
618
  }
623
619
  const layout = bareLayout(image);
624
- return layout === null || warned.has(bareCodes[layout]) ? null : {
625
- code: bareCodes[layout],
626
- layout
627
- };
628
- };
629
-
630
- // The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
631
- // process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
632
- // emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
633
- // navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
634
- // keeps Parcel from adding one.
635
- const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
636
- const warningText = {
637
- 'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel), or grey, passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA; format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`,
638
- 'gray-as-rgba': (byteLength, layout) => (layout === 'grey-alpha' ? `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey and alpha bytes (2 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG with alpha.` : `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey bytes (1 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices.`) + ` Expand ${layout === 'grey-alpha' ? 'it' : '8-bit grey'} to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()). There is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
639
- };
640
- // `warning` is what bareImageWarning returned: {code, layout}.
641
- export const warnOnce = ({
642
- code,
643
- layout
644
- }, byteLength) => {
645
- if (warned.has(code)) {
646
- return;
647
- }
648
- warned.add(code);
649
- const message = warningText[code](byteLength, layout);
650
- const runtime = globalThis.process;
651
- if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
652
- runtime.emitWarning(message, {
653
- type: 'AgglomerativeClusteringWarning',
654
- code
655
- });
656
- } else if (typeof console !== 'undefined') {
657
- console.warn(`agglomerative-clustering [${code}]: ${message}`);
658
- }
659
- };
660
- // The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
661
- // also skips the sampling.
662
- export const silenceWarnings = () => {
663
- for (const code of Object.keys(warningText)) {
664
- warned.add(code);
665
- }
666
- };
667
- // For tests.
668
- export const resetWarnings = () => {
669
- warned.clear();
620
+ return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
670
621
  };
671
622
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
672
623
  // `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
@@ -689,7 +640,7 @@ export const markPalette = (bytes, colorSpace) => {
689
640
  });
690
641
  return bytes;
691
642
  };
692
- // Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
643
+ // Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
693
644
  // non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
694
645
  // `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
695
646
  // calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
@@ -703,13 +654,13 @@ export const setEngine = value => {
703
654
  engine = value;
704
655
  }
705
656
  };
706
- // Each method's call shape and its function form, for messages.
657
+ // Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
707
658
  const methodNames = {
708
- getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
709
- getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
710
- getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
711
- quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
712
- quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)'],
659
+ getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
660
+ getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
661
+ getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
662
+ quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
663
+ quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
713
664
  chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
714
665
  };
715
666
  // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
@@ -832,6 +783,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
832
783
  // those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
833
784
  export function Clustering(...args) {
834
785
  const [source] = args;
786
+ // A palette gets the same hint as from every other function, before its bytes are copied.
787
+ if (isPalette(source)) {
788
+ readHeader(source);
789
+ }
835
790
  // Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
836
791
  // would coerce. A plain array must hold byte values, as for a palette.
837
792
  const isBuffer = isArrayBufferLike(source);
@@ -931,7 +886,7 @@ const notAClustering = clustering => {
931
886
  };
932
887
  export const readHeader = clustering => {
933
888
  if (isPalette(clustering)) {
934
- throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
889
+ throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette or clustering.getPalette(k); a clustering comes from buildClustering.", 'clustering');
935
890
  }
936
891
  if (!isUint8Array(clustering)) {
937
892
  throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
@@ -993,11 +948,11 @@ export const readHeader = clustering => {
993
948
  throw notAClustering(clustering);
994
949
  };
995
950
 
996
- // Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
951
+ // Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
997
952
  // image, and quantize maps such an image the same way.
998
953
  export const checkPalette = palette => {
999
954
  if (isClustering(palette)) {
1000
- throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
955
+ throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with clustering.getPalette(k), or map with clustering.quantize(image, k).", 'palette');
1001
956
  }
1002
957
  if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
1003
958
  throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
@@ -1,10 +1,7 @@
1
1
  // Runs inside the worker started by worker.js: receives calls, runs them with the main entry, and posts results
2
2
  // back, transferring every result buffer. Imports `./index.mjs`, which exists only in dist/ (like clustering.js).
3
3
  import * as ac from './index.mjs';
4
- import { MARK, mark, revive, isPalette, silenceWarnings } from "./shared.mjs";
5
-
6
- // The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
7
- silenceWarnings();
4
+ import { version, MARK, mark, revive, isPalette } from "./shared.mjs";
8
5
 
9
6
  // Images kept in the worker by `cluster`, with their clusterings, and clusterings alone from `load`, by handle id.
10
7
  const handles = new Map();
@@ -31,7 +28,7 @@ const inClusteringSpace = async (id, options, palette) => {
31
28
  }
32
29
  const {
33
30
  colorSpace
34
- } = await ac.getClusteringInfo(handle(id).clustering);
31
+ } = await handle(id).clustering.getClusteringInfo();
35
32
  return {
36
33
  ...options,
37
34
  colorSpace: options && options.colorSpace !== undefined ? options.colorSpace : colorSpace
@@ -44,10 +41,12 @@ const inClusteringSpace = async (id, options, palette) => {
44
41
  const functions = Object.fromEntries(Object.entries(ac).filter(([name, value]) => typeof value === 'function' && !/^[A-Z]/.test(name)));
45
42
  const methods = {
46
43
  ...functions,
44
+ // The first message every worker entry sends: which version this script is.
45
+ handshake: async () => version,
47
46
  cluster: async (id, image, options) => {
48
47
  handles.set(id, {
49
48
  image,
50
- clustering: await ac.getClustering(image, options)
49
+ clustering: await ac.buildClustering(image, options)
51
50
  });
52
51
  },
53
52
  load: async (id, clustering) => {
@@ -59,14 +58,14 @@ const methods = {
59
58
  handles.delete(id);
60
59
  },
61
60
  handleGetClustering: async id => new ac.Clustering(handle(id).clustering),
62
- handleGetPalette: async (id, k) => ac.getPaletteFromClustering(handle(id).clustering, k),
63
- handleGetSwatches: async (id, k) => ac.getSwatchesFromClustering(handle(id).clustering, k),
64
- handleGetClusteringInfo: async id => ac.getClusteringInfo(handle(id).clustering),
61
+ handleGetPalette: async (id, k) => handle(id).clustering.getPalette(k),
62
+ handleGetSwatches: async (id, k) => handle(id).clustering.getSwatches(k),
63
+ handleGetClusteringInfo: async id => handle(id).clustering.getClusteringInfo(),
65
64
  handleChooseFrom: async (id, palette, k, options) => handle(id).clustering.chooseFrom(palette, k, options),
66
- handleQuantize: async (id, k, options) => ac.quantizeFromClustering(handle(id).image, handle(id).clustering, k, options),
67
- handleQuantizeToIndices: async (id, k, options) => ac.quantizeToIndicesFromClustering(handle(id).image, handle(id).clustering, k, options),
68
- handleQuantizeImage: async (id, image, k, options) => ac.quantizeFromClustering(image, handle(id).clustering, k, options),
69
- handleQuantizeToIndicesImage: async (id, image, k, options) => ac.quantizeToIndicesFromClustering(image, handle(id).clustering, k, options),
65
+ handleQuantize: async (id, k, options) => handle(id).clustering.quantize(handle(id).image, k, options),
66
+ handleQuantizeToIndices: async (id, k, options) => handle(id).clustering.quantizeToIndices(handle(id).image, k, options),
67
+ handleQuantizeImage: async (id, image, k, options) => handle(id).clustering.quantize(image, k, options),
68
+ handleQuantizeToIndicesImage: async (id, image, k, options) => handle(id).clustering.quantizeToIndices(image, k, options),
70
69
  handleQuantizeWithPalette: async (id, palette, options) => ac.quantizeWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette)),
71
70
  handleQuantizeToIndicesWithPalette: async (id, palette, options) => ac.quantizeToIndicesWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette))
72
71
  };
@@ -87,14 +86,12 @@ const buffers = value => {
87
86
 
88
87
  // Where the options sit among each method's arguments, to give them the call's signal and progress callback.
89
88
  const optionsIndex = {
90
- getClustering: 1,
91
- getPalette: 2,
92
- getSwatches: 2,
89
+ buildClustering: 1,
90
+ buildPalette: 2,
91
+ buildSwatches: 2,
93
92
  quantize: 2,
94
- quantizeFromClustering: 3,
95
93
  quantizeWithPalette: 2,
96
94
  quantizeToIndices: 2,
97
- quantizeToIndicesFromClustering: 3,
98
95
  quantizeToIndicesWithPalette: 2,
99
96
  cluster: 2,
100
97
  handleQuantize: 2,