agglomerative-clustering 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -70,17 +70,17 @@ shares.forEach((share, i) => {
70
70
  **A colour-count slider:** cluster once, then cut and map as often as you like.
71
71
 
72
72
  ```js
73
- import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
73
+ import { getClustering, quantizeWithPalette } from 'agglomerative-clustering';
74
74
 
75
75
  const clustering = await getClustering(imageData); // the expensive step, done once
76
76
 
77
77
  slider.oninput = async () => {
78
- const palette = await getPaletteFromClustering(clustering, Number(slider.value)); // ~0.4 ms for any k
79
- ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
78
+ const palette = await clustering.getPalette(Number(slider.value)); // ~0.4 ms for any k
79
+ ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
80
80
  };
81
81
  ```
82
82
 
83
- Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same functions from `agglomerative-clustering/worker` (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)).
83
+ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
84
84
 
85
85
  ## How it works
86
86
 
@@ -92,14 +92,19 @@ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `
92
92
 
93
93
  The one-shot functions (`getPalette`, `quantize`, …) do every step for you. To try many palette sizes, call `getClustering` once and cut it as often as you like.
94
94
 
95
- | You want | from the image | from a clustering you hold | with a palette you supply |
95
+ | You want | from the image | from a clustering you hold¹ | with a palette you supply |
96
96
  |---|---|---|---|
97
- | a palette (flat RGB) | `getPalette` | `getPaletteFromClustering` | |
98
- | a palette with each colour's share | `getSwatches` | `getSwatchesFromClustering` | |
99
- | the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
100
- | palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
97
+ | a palette (flat RGB) | `getPalette` | `clustering.getPalette(k)` (`getPaletteFromClustering`) | |
98
+ | a palette with each colour's share | `getSwatches` | `clustering.getSwatches(k)` (`getSwatchesFromClustering`) | |
99
+ | the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` (`quantizeFromClustering`) | `quantizeWithPalette` |
100
+ | palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` (`quantizeToIndicesFromClustering`) | `quantizeToIndicesWithPalette` |
101
+ | its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` (`getClusteringInfo`) | |
101
102
 
102
- **`…FromClustering`** takes the colours from a clustering you already hold, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `getClustering` builds a clustering, `getClusteringInfo` reads one (including its error curve, for choosing a palette size), and `init` loads the WebAssembly module (optional). Most code only needs the first column.
103
+ A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `getClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
104
+
105
+ **Methods or functions?** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **In a worker, use a handle** (`createWorker().cluster(image)`, below) or the worker entry's function forms: the methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
106
+
107
+ ¹ Each method has a function form, in brackets, that does the same. The cuts take the clustering first (`getPaletteFromClustering(clustering, k)`); the mapping functions take the image first and the clustering second (`quantizeFromClustering(image, clustering, k)`). See [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
103
108
 
104
109
  Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
105
110
 
Binary file
package/dist/index.cjs CHANGED
@@ -963,9 +963,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
963
963
 
964
964
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
965
965
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
966
+ // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
967
+ // the method form of mapping.
966
968
  const noOptions = (name, extra) => {
967
969
  if (extra.some(value => value !== undefined)) {
968
- throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use quantizeFromClustering.`, 'options');
970
+ const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
971
+ throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use ${alternative}.`, 'options');
969
972
  }
970
973
  };
971
974
 
@@ -1001,15 +1004,18 @@ const getPalette = async (image, k, options) => {
1001
1004
  }
1002
1005
  return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), (0, _shared.colorSpaceName)(o.colorSpace));
1003
1006
  };
1007
+
1008
+ // The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
1004
1009
  exports.getPalette = getPalette;
1005
- const getPaletteFromClustering = async (clustering, k, ...extra) => {
1010
+ const cutPalette = async (name, clustering, k, extra) => {
1006
1011
  const header = (0, _shared.readHeader)(clustering);
1007
1012
  k = check(k);
1008
- noOptions('getPaletteFromClustering', extra);
1013
+ noOptions(name, extra);
1009
1014
  clustering = held(clustering);
1010
1015
  const wasm = Module || (await acquire());
1011
1016
  return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
1012
1017
  };
1018
+ const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
1013
1019
 
1014
1020
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
1015
1021
  exports.getPaletteFromClustering = getPaletteFromClustering;
@@ -1032,10 +1038,10 @@ const needsWeights = header => {
1032
1038
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
1033
1039
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
1034
1040
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1035
- const getSwatchesFromClustering = async (clustering, k, ...extra) => {
1041
+ const cutSwatches = async (name, clustering, k, extra) => {
1036
1042
  const header = (0, _shared.readHeader)(clustering);
1037
1043
  k = check(k);
1038
- noOptions('getSwatchesFromClustering', extra);
1044
+ noOptions(name, extra);
1039
1045
  needsWeights(header);
1040
1046
  clustering = held(clustering);
1041
1047
  const wasm = Module || (await acquire());
@@ -1057,6 +1063,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
1057
1063
  shares
1058
1064
  };
1059
1065
  };
1066
+ const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
1060
1067
 
1061
1068
  // The same for an image: clusters it, then cuts, like getPalette.
1062
1069
  exports.getSwatchesFromClustering = getSwatchesFromClustering;
@@ -1071,9 +1078,9 @@ const getSwatches = async (image, k, options) => {
1071
1078
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
1072
1079
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
1073
1080
  exports.getSwatches = getSwatches;
1074
- const getClusteringInfo = async (clustering, ...extra) => {
1081
+ const readInfo = async (name, clustering, extra) => {
1075
1082
  const header = (0, _shared.readHeader)(clustering);
1076
- noOptions('getClusteringInfo', extra);
1083
+ noOptions(name, extra);
1077
1084
  needsWeights(header);
1078
1085
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
1079
1086
  const info = {
@@ -1114,6 +1121,7 @@ const getClusteringInfo = async (clustering, ...extra) => {
1114
1121
  }
1115
1122
  return info;
1116
1123
  };
1124
+ const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1117
1125
  exports.getClusteringInfo = getClusteringInfo;
1118
1126
  const quantize = async (image, k, options) => {
1119
1127
  const wrap = getWrapper(image);
@@ -1208,4 +1216,13 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1208
1216
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1209
1217
  return result;
1210
1218
  };
1211
- exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1219
+
1220
+ // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1221
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1222
+ (0, _shared.setEngine)({
1223
+ cut: cutPalette,
1224
+ cutSwatches,
1225
+ info: readInfo,
1226
+ quantizeFromClustering,
1227
+ quantizeToIndicesFromClustering
1228
+ });
package/dist/index.d.cts CHANGED
@@ -131,6 +131,12 @@ export class Palette extends Uint8Array {
131
131
  * `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
132
132
  * `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
133
133
  * wants it) and checks they are a clustering.
134
+ *
135
+ * It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
136
+ * so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
137
+ * `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
138
+ * bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
139
+ * `new Clustering(bytes)`.
134
140
  */
135
141
  export class Clustering extends Uint8Array {
136
142
  /**
@@ -141,6 +147,16 @@ export class Clustering extends Uint8Array {
141
147
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
142
148
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
143
149
  readonly [clusteringBrand]: true;
150
+ /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
151
+ getPalette(this: Clustering, k: number): Promise<Palette>;
152
+ /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
+ getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
+ /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
+ getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
+ /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
157
+ quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
+ /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
159
+ quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
144
160
  }
145
161
 
146
162
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
package/dist/index.d.ts CHANGED
@@ -131,6 +131,12 @@ export class Palette extends Uint8Array {
131
131
  * `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
132
132
  * `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
133
133
  * wants it) and checks they are a clustering.
134
+ *
135
+ * It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
136
+ * so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
137
+ * `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
138
+ * bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
139
+ * `new Clustering(bytes)`.
134
140
  */
135
141
  export class Clustering extends Uint8Array {
136
142
  /**
@@ -141,6 +147,16 @@ export class Clustering extends Uint8Array {
141
147
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
142
148
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
143
149
  readonly [clusteringBrand]: true;
150
+ /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
151
+ getPalette(this: Clustering, k: number): Promise<Palette>;
152
+ /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
+ getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
+ /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
+ getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
+ /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
157
+ quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
+ /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
159
+ quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
144
160
  }
145
161
 
146
162
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
2
+ import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
3
3
 
4
4
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
5
5
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -888,9 +888,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
888
888
 
889
889
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
890
890
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
891
+ // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
892
+ // the method form of mapping.
891
893
  const noOptions = (name, extra) => {
892
894
  if (extra.some(value => value !== undefined)) {
893
- throw fail('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use quantizeFromClustering.`, 'options');
895
+ const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
896
+ throw fail('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use ${alternative}.`, 'options');
894
897
  }
895
898
  };
896
899
 
@@ -925,14 +928,17 @@ export const getPalette = async (image, k, options) => {
925
928
  }
926
929
  return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
927
930
  };
928
- export const getPaletteFromClustering = async (clustering, k, ...extra) => {
931
+
932
+ // The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
933
+ const cutPalette = async (name, clustering, k, extra) => {
929
934
  const header = readHeader(clustering);
930
935
  k = check(k);
931
- noOptions('getPaletteFromClustering', extra);
936
+ noOptions(name, extra);
932
937
  clustering = held(clustering);
933
938
  const wasm = Module || (await acquire());
934
939
  return markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
935
940
  };
941
+ export const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
936
942
 
937
943
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
938
944
  const weightsOf = (wasm, clustering, header, k) => {
@@ -954,10 +960,10 @@ const needsWeights = header => {
954
960
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
955
961
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
956
962
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
957
- export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
963
+ const cutSwatches = async (name, clustering, k, extra) => {
958
964
  const header = readHeader(clustering);
959
965
  k = check(k);
960
- noOptions('getSwatchesFromClustering', extra);
966
+ noOptions(name, extra);
961
967
  needsWeights(header);
962
968
  clustering = held(clustering);
963
969
  const wasm = Module || (await acquire());
@@ -979,6 +985,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
979
985
  shares
980
986
  };
981
987
  };
988
+ export const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
982
989
 
983
990
  // The same for an image: clusters it, then cuts, like getPalette.
984
991
  export const getSwatches = async (image, k, options) => {
@@ -991,9 +998,9 @@ export const getSwatches = async (image, k, options) => {
991
998
  // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
992
999
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
993
1000
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
994
- export const getClusteringInfo = async (clustering, ...extra) => {
1001
+ const readInfo = async (name, clustering, extra) => {
995
1002
  const header = readHeader(clustering);
996
- noOptions('getClusteringInfo', extra);
1003
+ noOptions(name, extra);
997
1004
  needsWeights(header);
998
1005
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
999
1006
  const info = {
@@ -1034,6 +1041,7 @@ export const getClusteringInfo = async (clustering, ...extra) => {
1034
1041
  }
1035
1042
  return info;
1036
1043
  };
1044
+ export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1037
1045
  export const quantize = async (image, k, options) => {
1038
1046
  const wrap = getWrapper(image);
1039
1047
  image = load(image);
@@ -1121,4 +1129,13 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1121
1129
  checkAborted(o.signal);
1122
1130
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1123
1131
  return result;
1124
- };
1132
+ };
1133
+
1134
+ // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1135
+ setEngine({
1136
+ cut: cutPalette,
1137
+ cutSwatches,
1138
+ info: readInfo,
1139
+ quantizeFromClustering,
1140
+ quantizeToIndicesFromClustering
1141
+ });
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
9
+ exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = 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 = '3.2.0';
16
+ const version = exports.version = '3.3.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -328,7 +328,100 @@ const markPalette = (bytes, colorSpace) => {
328
328
  });
329
329
  return bytes;
330
330
  };
331
+ // Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
332
+ // non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
333
+ // `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
334
+ // calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
335
+ // entry puts nothing there, so in a worker-only app the methods reject and say what to import. Each copy of this file (the
336
+ // ES module and the CommonJS build) has its own slot, filled by the main entry of the same module system.
331
337
  exports.markPalette = markPalette;
338
+ let engine = null;
339
+ // The first main entry evaluated keeps the slot: it is the one an app loads and gives `init({ wasm })`, so a later copy
340
+ // (a duplicated chunk, a query-string import) doesn't re-point every clustering at a module of its own that isn't set up.
341
+ const setEngine = value => {
342
+ if (engine === null) {
343
+ engine = value;
344
+ }
345
+ };
346
+ // Each method's call shape and its function form, for messages.
347
+ exports.setEngine = setEngine;
348
+ const methodNames = {
349
+ getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
350
+ getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
351
+ getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
352
+ quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
353
+ quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
354
+ };
355
+ // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
356
+ // the worker handle's `k`, then that the main entry is loaded.
357
+ const receive = (name, receiver, image) => {
358
+ const [shape, form] = methodNames[name];
359
+ if (!isUint8Array(receiver)) {
360
+ throw fail('invalid-clustering', `Invalid clustering: ${name} was called without its clustering (this is ${receiver === undefined ? 'undefined' : describe(receiver)}). Call it as clustering.${shape}, or use ${form}.`, 'clustering');
361
+ }
362
+ readHeader(receiver);
363
+ if (image !== undefined) {
364
+ checkImageFirst(name, image.value);
365
+ }
366
+ if (engine === null) {
367
+ throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
368
+ }
369
+ return engine;
370
+ };
371
+ // The worker handle's quantize(k) maps the image it holds; this one takes the image first, so a number there is that mistake.
372
+ const checkImageFirst = (name, image) => {
373
+ if (typeof image === 'number') {
374
+ throw fail('invalid-argument', `Invalid image: got ${image}. clustering.${name} takes the image first: clustering.${name}(image, k). (A worker handle's ${name}(k) maps the image it holds.)`, 'image');
375
+ }
376
+ };
377
+ // Plain functions (they read `this`) that return a promise and never throw: errors are rejections, as from the functions.
378
+ const methods = {
379
+ getPalette(k, ...extra) {
380
+ try {
381
+ return receive('getPalette', this).cut('clustering.getPalette', this, k, extra);
382
+ } catch (error) {
383
+ return Promise.reject(error);
384
+ }
385
+ },
386
+ getSwatches(k, ...extra) {
387
+ try {
388
+ return receive('getSwatches', this).cutSwatches('clustering.getSwatches', this, k, extra);
389
+ } catch (error) {
390
+ return Promise.reject(error);
391
+ }
392
+ },
393
+ getClusteringInfo(...extra) {
394
+ try {
395
+ return receive('getClusteringInfo', this).info('clustering.getClusteringInfo', this, extra);
396
+ } catch (error) {
397
+ return Promise.reject(error);
398
+ }
399
+ },
400
+ quantize(image, k, options) {
401
+ try {
402
+ return receive('quantize', this, {
403
+ value: image
404
+ }).quantizeFromClustering(image, this, k, options);
405
+ } catch (error) {
406
+ return Promise.reject(error);
407
+ }
408
+ },
409
+ quantizeToIndices(image, k, options) {
410
+ try {
411
+ return receive('quantizeToIndices', this, {
412
+ value: image
413
+ }).quantizeToIndicesFromClustering(image, this, k, options);
414
+ } catch (error) {
415
+ return Promise.reject(error);
416
+ }
417
+ }
418
+ };
419
+ // Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
420
+ const methodDescriptors = Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, {
421
+ value,
422
+ writable: true,
423
+ configurable: true
424
+ }]));
332
425
  const markClustering = bytes => {
333
426
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
334
427
  checked.add(bytes);
@@ -338,6 +431,7 @@ const markClustering = bytes => {
338
431
  Object.defineProperty(bytes, inspect, {
339
432
  value: clusteringView
340
433
  });
434
+ Object.defineProperties(bytes, methodDescriptors);
341
435
  return bytes;
342
436
  };
343
437
 
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.2.0';
7
+ export const version = '3.3.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -297,6 +297,98 @@ export const markPalette = (bytes, colorSpace) => {
297
297
  });
298
298
  return bytes;
299
299
  };
300
+ // Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
301
+ // non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
302
+ // `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
303
+ // calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
304
+ // entry puts nothing there, so in a worker-only app the methods reject and say what to import. Each copy of this file (the
305
+ // ES module and the CommonJS build) has its own slot, filled by the main entry of the same module system.
306
+ let engine = null;
307
+ // The first main entry evaluated keeps the slot: it is the one an app loads and gives `init({ wasm })`, so a later copy
308
+ // (a duplicated chunk, a query-string import) doesn't re-point every clustering at a module of its own that isn't set up.
309
+ export const setEngine = value => {
310
+ if (engine === null) {
311
+ engine = value;
312
+ }
313
+ };
314
+ // Each method's call shape and its function form, for messages.
315
+ const methodNames = {
316
+ getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
317
+ getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
318
+ getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
319
+ quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
320
+ quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
321
+ };
322
+ // Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
323
+ // the worker handle's `k`, then that the main entry is loaded.
324
+ const receive = (name, receiver, image) => {
325
+ const [shape, form] = methodNames[name];
326
+ if (!isUint8Array(receiver)) {
327
+ throw fail('invalid-clustering', `Invalid clustering: ${name} was called without its clustering (this is ${receiver === undefined ? 'undefined' : describe(receiver)}). Call it as clustering.${shape}, or use ${form}.`, 'clustering');
328
+ }
329
+ readHeader(receiver);
330
+ if (image !== undefined) {
331
+ checkImageFirst(name, image.value);
332
+ }
333
+ if (engine === null) {
334
+ throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
335
+ }
336
+ return engine;
337
+ };
338
+ // The worker handle's quantize(k) maps the image it holds; this one takes the image first, so a number there is that mistake.
339
+ const checkImageFirst = (name, image) => {
340
+ if (typeof image === 'number') {
341
+ throw fail('invalid-argument', `Invalid image: got ${image}. clustering.${name} takes the image first: clustering.${name}(image, k). (A worker handle's ${name}(k) maps the image it holds.)`, 'image');
342
+ }
343
+ };
344
+ // Plain functions (they read `this`) that return a promise and never throw: errors are rejections, as from the functions.
345
+ const methods = {
346
+ getPalette(k, ...extra) {
347
+ try {
348
+ return receive('getPalette', this).cut('clustering.getPalette', this, k, extra);
349
+ } catch (error) {
350
+ return Promise.reject(error);
351
+ }
352
+ },
353
+ getSwatches(k, ...extra) {
354
+ try {
355
+ return receive('getSwatches', this).cutSwatches('clustering.getSwatches', this, k, extra);
356
+ } catch (error) {
357
+ return Promise.reject(error);
358
+ }
359
+ },
360
+ getClusteringInfo(...extra) {
361
+ try {
362
+ return receive('getClusteringInfo', this).info('clustering.getClusteringInfo', this, extra);
363
+ } catch (error) {
364
+ return Promise.reject(error);
365
+ }
366
+ },
367
+ quantize(image, k, options) {
368
+ try {
369
+ return receive('quantize', this, {
370
+ value: image
371
+ }).quantizeFromClustering(image, this, k, options);
372
+ } catch (error) {
373
+ return Promise.reject(error);
374
+ }
375
+ },
376
+ quantizeToIndices(image, k, options) {
377
+ try {
378
+ return receive('quantizeToIndices', this, {
379
+ value: image
380
+ }).quantizeToIndicesFromClustering(image, this, k, options);
381
+ } catch (error) {
382
+ return Promise.reject(error);
383
+ }
384
+ }
385
+ };
386
+ // Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
387
+ const methodDescriptors = Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, {
388
+ value,
389
+ writable: true,
390
+ configurable: true
391
+ }]));
300
392
  export const markClustering = bytes => {
301
393
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
302
394
  checked.add(bytes);
@@ -306,6 +398,7 @@ export const markClustering = bytes => {
306
398
  Object.defineProperty(bytes, inspect, {
307
399
  value: clusteringView
308
400
  });
401
+ Object.defineProperties(bytes, methodDescriptors);
309
402
  return bytes;
310
403
  };
311
404
 
package/dist/worker.d.cts CHANGED
@@ -11,7 +11,10 @@ import type { Palette, Clustering } from './index.cjs';
11
11
  /** The same class as the main entry's `Palette`: flat RGB bytes that know their colour space. */
12
12
  export { Palette } from './index.cjs';
13
13
 
14
- /** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
14
+ /**
15
+ * The same class as the main entry's `Clustering`. Its methods run on the calling thread and need the main entry imported
16
+ * there; off the thread, use this entry's `…FromClustering` functions or `cluster()`.
17
+ */
15
18
  export { Clustering } from './index.cjs';
16
19
 
17
20
  /** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
package/dist/worker.d.ts CHANGED
@@ -11,7 +11,10 @@ import type { Palette, Clustering } from './index.js';
11
11
  /** The same class as the main entry's `Palette`: flat RGB bytes that know their colour space. */
12
12
  export { Palette } from './index.js';
13
13
 
14
- /** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
14
+ /**
15
+ * The same class as the main entry's `Clustering`. Its methods run on the calling thread and need the main entry imported
16
+ * there; off the thread, use this entry's `…FromClustering` functions or `cluster()`.
17
+ */
15
18
  export { Clustering } from './index.js';
16
19
 
17
20
  /** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
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",