agglomerative-clustering 4.0.0-beta.3 → 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/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.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;
9
+ exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.quantizeOptions = exports.quantizeIndexOptions = exports.parseOptions = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.mapOptions = exports.mapIndexOptions = 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.counted = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.clusterOptions = exports.checkSize = exports.checkPixelArray = exports.checkPalette = exports.checkNotEmpty = exports.checkK = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.checkChoice = exports.channels = exports.bareLayout = exports.bareImageError = exports.alphaModes = exports.alphaModeCodes = 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.3';
16
+ const version = exports.version = '4.0.0-beta.4';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -119,7 +119,7 @@ const checkImageDataPixels = image => {
119
119
  }
120
120
  const needed = image.width * image.height * 4;
121
121
  if (image.data.length !== needed) {
122
- throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
122
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${counted(image.data.length, 'byte', 'bytes')}, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
123
123
  }
124
124
  return;
125
125
  }
@@ -331,10 +331,12 @@ const imageCopy = image => {
331
331
 
332
332
  // What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
333
333
  // buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
334
+ // What to do with 16-bit pixels (a decoder's Uint16Array for a 16-bit PNG): the library reads 8 bits per channel.
334
335
  exports.imageCopy = imageCopy;
336
+ const sixteenBit = data => Object.prototype.toString.call(data) === '[object Uint16Array]' ? ' 16-bit pixels (a Uint16Array, as decoders give for a 16-bit PNG) have to be shifted down to 8 bits first: Uint8Array.from(data, (v) => v >> 8).' : '';
335
337
  const checkImageBody = image => {
336
338
  if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
337
- throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
339
+ throw fail('invalid-argument', `Invalid image data: must be Uint8Array or Uint8ClampedArray.${sixteenBit(image.data)}`, 'image');
338
340
  }
339
341
  if (isDetached(image.data)) {
340
342
  throw detachedError('data');
@@ -374,7 +376,11 @@ const ditherMethodCodes = {
374
376
  const ditherMethods = exports.ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
375
377
  const ditherSteps = exports.ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
376
378
 
379
+ // A count with its noun in the right number, for messages: 1 byte, 2 bytes.
380
+ const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
381
+
377
382
  // A short description of a value for an error message.
383
+ exports.counted = counted;
378
384
  const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
379
385
 
380
386
  // Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
@@ -665,7 +671,7 @@ exports.bareImageError = bareImageError;
665
671
  const inspect = Symbol.for('nodejs.util.inspect.custom');
666
672
  const view = label => function (depth, options, nodeInspect) {
667
673
  const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
668
- return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
674
+ return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${counted(plain.length, 'byte', 'bytes')}]`}`;
669
675
  };
670
676
  const paletteView = view(palette => `Palette(${palette.colorSpace})`);
671
677
  const clusteringView = view(() => 'Clustering');
@@ -920,13 +926,17 @@ const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes
920
926
  // and a length of 0 or 3 more than a multiple of 9).
921
927
  const notAClustering = clustering => {
922
928
  const length = clustering.length;
929
+ // No bytes at all is not a 1.x clustering that lost its header: there is nothing to read.
930
+ if (length === 0) {
931
+ return fail('invalid-clustering', "Invalid clustering: it is empty (no bytes). A clustering comes from buildClustering, even for an image with no visible pixels.", 'clustering');
932
+ }
923
933
  if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
924
934
  return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
925
935
  }
926
936
  if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
927
- return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
937
+ return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${counted(length, 'byte', 'bytes')}): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
928
938
  }
929
- return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
939
+ return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${counted(length, 'byte', 'bytes')} that ${length === 1 ? "doesn't" : "don't"} start with a clustering header).`, 'clustering');
930
940
  };
931
941
  const readHeader = clustering => {
932
942
  if (isPalette(clustering)) {
@@ -1075,4 +1085,202 @@ const revive = value => {
1075
1085
  }
1076
1086
  return value;
1077
1087
  };
1078
- exports.revive = revive;
1088
+
1089
+ // ----- Arguments both entries check ------------------------------------------------------------------------------------
1090
+ // What the main entry checks about k and the options before it does any work, kept here so the worker entry runs the very same
1091
+ // checks, in the same order, before it posts anything.
1092
+ exports.revive = revive;
1093
+ const alphaModeCodes = exports.alphaModeCodes = {
1094
+ 'ignore': 0,
1095
+ 'weight': 1
1096
+ };
1097
+
1098
+ // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
1099
+ // the WASM side holds (a larger one would overflow its int).
1100
+ const checkK = k => {
1101
+ if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
1102
+ // A string is the usual slip (an input's `value`), so it gets its own fix.
1103
+ const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
1104
+ throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
1105
+ }
1106
+ return Math.min(k, 0x7FFFFFFF);
1107
+ };
1108
+
1109
+ // Validates `options` against the keys a function accepts and fills in defaults:
1110
+ // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
1111
+ // clustering, the default is the space the clustering was made in (code -1)
1112
+ // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
1113
+ // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
1114
+ // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
1115
+ // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
1116
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
1117
+ // (see clusterInSlices and mapInSlices)
1118
+ // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
1119
+ // indexed output also gives them their own entry, which counts towards k
1120
+
1121
+ // The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
1122
+ // object form.
1123
+ exports.checkK = checkK;
1124
+ const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
1125
+ const parseOptions = (options, allowed, image) => {
1126
+ if (options === undefined) {
1127
+ options = {};
1128
+ }
1129
+ if (!isOptionsObject(options)) {
1130
+ throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
1131
+ }
1132
+ options = snapshot(options);
1133
+ for (const key of Object.keys(options)) {
1134
+ if (!allowed.includes(key)) {
1135
+ const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
1136
+ throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
1137
+ }
1138
+ }
1139
+ const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
1140
+ if (!colorSpaces.includes(colorSpace)) {
1141
+ throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
1142
+ }
1143
+ const alpha = options.alpha === undefined ? 'weight' : options.alpha;
1144
+ if (!alphaModes.includes(alpha)) {
1145
+ throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
1146
+ }
1147
+ const precision = options.precision === undefined ? 8 : options.precision;
1148
+ if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
1149
+ throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
1150
+ }
1151
+ const {
1152
+ strength: dither,
1153
+ method: ditherMethod,
1154
+ steps: ditherSteps
1155
+ } = parseDither(options.dither);
1156
+
1157
+ // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
1158
+ // (a wrong row length would dither without an error, as long as it divides the pixel count).
1159
+ if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
1160
+ throw fail('invalid-argument', `Invalid width: options.width (${describe(options.width)}) does not match the image's width (${image.width}).`, 'options.width');
1161
+ }
1162
+ if (options.width !== undefined && image) {
1163
+ checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
1164
+ }
1165
+ const width = options.width !== undefined ? options.width : image ? image.width : undefined;
1166
+ if (dither > 0) {
1167
+ const stride = channels(image.format);
1168
+ if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
1169
+ throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
1170
+ }
1171
+ if (image.data.length / stride % width !== 0) {
1172
+ throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
1173
+ }
1174
+ }
1175
+ const signal = options.signal;
1176
+ if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
1177
+ throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
1178
+ }
1179
+ const onProgress = options.onProgress;
1180
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
1181
+ throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
1182
+ }
1183
+
1184
+ // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
1185
+ const transparentOption = options.transparent === undefined ? false : options.transparent;
1186
+ const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
1187
+ if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
1188
+ throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
1189
+ }
1190
+ checkTransparentFormat(image, options);
1191
+
1192
+ // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
1193
+ if (transparent > 0 && options.alpha !== undefined) {
1194
+ throw fail('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
1195
+ }
1196
+ return {
1197
+ colorSpace: colorSpaceCodes[colorSpace],
1198
+ colorSpaceGiven: options.colorSpace !== undefined,
1199
+ alpha: alphaModeCodes[alpha],
1200
+ precision,
1201
+ dither,
1202
+ ditherMethod,
1203
+ ditherSteps,
1204
+ width: dither > 0 ? width : 0,
1205
+ transparent,
1206
+ transparentGiven: options.transparent !== undefined,
1207
+ signal,
1208
+ onProgress
1209
+ };
1210
+ };
1211
+ exports.parseOptions = parseOptions;
1212
+ const controlOptions = ['signal', 'onProgress'];
1213
+ // `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
1214
+ // an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
1215
+ const checkTransparentFormat = (image, options) => {
1216
+ if (!image || hasAlpha(image.format) || options.transparent === undefined || options.transparent === false) {
1217
+ return;
1218
+ }
1219
+ const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
1220
+ throw fail('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
1221
+ };
1222
+ const clusterOptions = exports.clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
1223
+ const quantizeOptions = exports.quantizeOptions = [...clusterOptions, 'dither', 'width'];
1224
+ const mapOptions = exports.mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
1225
+ const quantizeIndexOptions = exports.quantizeIndexOptions = quantizeOptions;
1226
+ const mapIndexOptions = exports.mapIndexOptions = [...mapOptions, 'transparent'];
1227
+
1228
+ // What a bare typed array passed as an image must be, in the order the main entry checks it: not a clustering or a palette,
1229
+ // then (when it is not detached, which the caller reports) for a Uint8Array not the bytes of an image file and a whole number
1230
+ // of RGBA pixels, and no other kind of array. The bare-RGB and grey check (bareImageError) follows, in the caller.
1231
+ const checkPixelArray = image => {
1232
+ if (isClustering(image) || isPalette(image)) {
1233
+ const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
1234
+ const fix = isClustering(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
1235
+ throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
1236
+ }
1237
+ if (isDetached(image)) {
1238
+ return;
1239
+ }
1240
+ if (isUint8Array(image)) {
1241
+ const encoded = sniffImageFormat(image);
1242
+ if (encoded) {
1243
+ throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
1244
+ }
1245
+ if (image.length % 4 !== 0) {
1246
+ throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
1247
+ }
1248
+ return;
1249
+ }
1250
+ throw fail('invalid-argument', `Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.${sixteenBit(image)}`, 'image');
1251
+ };
1252
+
1253
+ // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
1254
+ // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
1255
+ // alpha from which an RGBA pixel needs a colour.
1256
+ exports.checkPixelArray = checkPixelArray;
1257
+ const checkNotEmpty = (palette, image, cutoff) => {
1258
+ if (palette.length > 0) {
1259
+ return;
1260
+ }
1261
+ const data = image.data;
1262
+ let visible = hasAlpha(image.format) ? false : data.length > 0;
1263
+ for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
1264
+ visible = data[i] >= cutoff;
1265
+ }
1266
+ if (visible) {
1267
+ throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
1268
+ }
1269
+ };
1270
+
1271
+ // What clustering.chooseFrom checks about its palette and k, in order: the palette is flat RGB bytes and not empty, k is a
1272
+ // whole number of colours and no more than the palette has. Returns k.
1273
+ exports.checkNotEmpty = checkNotEmpty;
1274
+ const checkChoice = (palette, k) => {
1275
+ checkPalette(palette);
1276
+ if (palette.length === 0) {
1277
+ throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1278
+ }
1279
+ const count = palette.length / 3;
1280
+ k = checkK(k);
1281
+ if (k > count) {
1282
+ throw fail('invalid-argument', `Invalid k: ${k} is more than the ${counted(count, 'entry', 'entries')} in the palette; use ${count} or fewer.`, 'k');
1283
+ }
1284
+ return k;
1285
+ };
1286
+ exports.checkChoice = checkChoice;
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.3';
7
+ export const version = '4.0.0-beta.4';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -97,7 +97,7 @@ export const checkImageDataPixels = image => {
97
97
  }
98
98
  const needed = image.width * image.height * 4;
99
99
  if (image.data.length !== needed) {
100
- throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
100
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${counted(image.data.length, 'byte', 'bytes')}, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
101
101
  }
102
102
  return;
103
103
  }
@@ -302,9 +302,11 @@ export const imageCopy = image => {
302
302
 
303
303
  // What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
304
304
  // buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
305
+ // What to do with 16-bit pixels (a decoder's Uint16Array for a 16-bit PNG): the library reads 8 bits per channel.
306
+ const sixteenBit = data => Object.prototype.toString.call(data) === '[object Uint16Array]' ? ' 16-bit pixels (a Uint16Array, as decoders give for a 16-bit PNG) have to be shifted down to 8 bits first: Uint8Array.from(data, (v) => v >> 8).' : '';
305
307
  export const checkImageBody = image => {
306
308
  if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
307
- throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
309
+ throw fail('invalid-argument', `Invalid image data: must be Uint8Array or Uint8ClampedArray.${sixteenBit(image.data)}`, 'image');
308
310
  }
309
311
  if (isDetached(image.data)) {
310
312
  throw detachedError('data');
@@ -341,6 +343,9 @@ const ditherMethodCodes = {
341
343
  export const ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
342
344
  export const ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
343
345
 
346
+ // A count with its noun in the right number, for messages: 1 byte, 2 bytes.
347
+ export const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
348
+
344
349
  // A short description of a value for an error message.
345
350
  export const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
346
351
 
@@ -624,7 +629,7 @@ export const bareImageError = image => {
624
629
  const inspect = Symbol.for('nodejs.util.inspect.custom');
625
630
  const view = label => function (depth, options, nodeInspect) {
626
631
  const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
627
- return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
632
+ return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${counted(plain.length, 'byte', 'bytes')}]`}`;
628
633
  };
629
634
  const paletteView = view(palette => `Palette(${palette.colorSpace})`);
630
635
  const clusteringView = view(() => 'Clustering');
@@ -876,13 +881,17 @@ const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes
876
881
  // and a length of 0 or 3 more than a multiple of 9).
877
882
  const notAClustering = clustering => {
878
883
  const length = clustering.length;
884
+ // No bytes at all is not a 1.x clustering that lost its header: there is nothing to read.
885
+ if (length === 0) {
886
+ return fail('invalid-clustering', "Invalid clustering: it is empty (no bytes). A clustering comes from buildClustering, even for an image with no visible pixels.", 'clustering');
887
+ }
879
888
  if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
880
889
  return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
881
890
  }
882
891
  if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
883
- return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
892
+ return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${counted(length, 'byte', 'bytes')}): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
884
893
  }
885
- return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
894
+ return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${counted(length, 'byte', 'bytes')} that ${length === 1 ? "doesn't" : "don't"} start with a clustering header).`, 'clustering');
886
895
  };
887
896
  export const readHeader = clustering => {
888
897
  if (isPalette(clustering)) {
@@ -1027,4 +1036,197 @@ export const revive = value => {
1027
1036
  value[key] = reviveOne(value[key]);
1028
1037
  }
1029
1038
  return value;
1039
+ };
1040
+
1041
+ // ----- Arguments both entries check ------------------------------------------------------------------------------------
1042
+ // What the main entry checks about k and the options before it does any work, kept here so the worker entry runs the very same
1043
+ // checks, in the same order, before it posts anything.
1044
+ export const alphaModeCodes = {
1045
+ 'ignore': 0,
1046
+ 'weight': 1
1047
+ };
1048
+
1049
+ // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
1050
+ // the WASM side holds (a larger one would overflow its int).
1051
+ export const checkK = k => {
1052
+ if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
1053
+ // A string is the usual slip (an input's `value`), so it gets its own fix.
1054
+ const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
1055
+ throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
1056
+ }
1057
+ return Math.min(k, 0x7FFFFFFF);
1058
+ };
1059
+
1060
+ // Validates `options` against the keys a function accepts and fills in defaults:
1061
+ // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
1062
+ // clustering, the default is the space the clustering was made in (code -1)
1063
+ // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
1064
+ // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
1065
+ // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
1066
+ // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
1067
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
1068
+ // (see clusterInSlices and mapInSlices)
1069
+ // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
1070
+ // indexed output also gives them their own entry, which counts towards k
1071
+
1072
+ // The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
1073
+ // object form.
1074
+ const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
1075
+ export const parseOptions = (options, allowed, image) => {
1076
+ if (options === undefined) {
1077
+ options = {};
1078
+ }
1079
+ if (!isOptionsObject(options)) {
1080
+ throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
1081
+ }
1082
+ options = snapshot(options);
1083
+ for (const key of Object.keys(options)) {
1084
+ if (!allowed.includes(key)) {
1085
+ const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
1086
+ throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
1087
+ }
1088
+ }
1089
+ const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
1090
+ if (!colorSpaces.includes(colorSpace)) {
1091
+ throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
1092
+ }
1093
+ const alpha = options.alpha === undefined ? 'weight' : options.alpha;
1094
+ if (!alphaModes.includes(alpha)) {
1095
+ throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
1096
+ }
1097
+ const precision = options.precision === undefined ? 8 : options.precision;
1098
+ if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
1099
+ throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
1100
+ }
1101
+ const {
1102
+ strength: dither,
1103
+ method: ditherMethod,
1104
+ steps: ditherSteps
1105
+ } = parseDither(options.dither);
1106
+
1107
+ // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
1108
+ // (a wrong row length would dither without an error, as long as it divides the pixel count).
1109
+ if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
1110
+ throw fail('invalid-argument', `Invalid width: options.width (${describe(options.width)}) does not match the image's width (${image.width}).`, 'options.width');
1111
+ }
1112
+ if (options.width !== undefined && image) {
1113
+ checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
1114
+ }
1115
+ const width = options.width !== undefined ? options.width : image ? image.width : undefined;
1116
+ if (dither > 0) {
1117
+ const stride = channels(image.format);
1118
+ if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
1119
+ throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
1120
+ }
1121
+ if (image.data.length / stride % width !== 0) {
1122
+ throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
1123
+ }
1124
+ }
1125
+ const signal = options.signal;
1126
+ if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
1127
+ throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
1128
+ }
1129
+ const onProgress = options.onProgress;
1130
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
1131
+ throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
1132
+ }
1133
+
1134
+ // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
1135
+ const transparentOption = options.transparent === undefined ? false : options.transparent;
1136
+ const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
1137
+ if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
1138
+ throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
1139
+ }
1140
+ checkTransparentFormat(image, options);
1141
+
1142
+ // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
1143
+ if (transparent > 0 && options.alpha !== undefined) {
1144
+ throw fail('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
1145
+ }
1146
+ return {
1147
+ colorSpace: colorSpaceCodes[colorSpace],
1148
+ colorSpaceGiven: options.colorSpace !== undefined,
1149
+ alpha: alphaModeCodes[alpha],
1150
+ precision,
1151
+ dither,
1152
+ ditherMethod,
1153
+ ditherSteps,
1154
+ width: dither > 0 ? width : 0,
1155
+ transparent,
1156
+ transparentGiven: options.transparent !== undefined,
1157
+ signal,
1158
+ onProgress
1159
+ };
1160
+ };
1161
+ const controlOptions = ['signal', 'onProgress'];
1162
+ // `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
1163
+ // an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
1164
+ const checkTransparentFormat = (image, options) => {
1165
+ if (!image || hasAlpha(image.format) || options.transparent === undefined || options.transparent === false) {
1166
+ return;
1167
+ }
1168
+ const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
1169
+ throw fail('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
1170
+ };
1171
+ export const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
1172
+ export const quantizeOptions = [...clusterOptions, 'dither', 'width'];
1173
+ export const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
1174
+ export const quantizeIndexOptions = quantizeOptions;
1175
+ export const mapIndexOptions = [...mapOptions, 'transparent'];
1176
+
1177
+ // What a bare typed array passed as an image must be, in the order the main entry checks it: not a clustering or a palette,
1178
+ // then (when it is not detached, which the caller reports) for a Uint8Array not the bytes of an image file and a whole number
1179
+ // of RGBA pixels, and no other kind of array. The bare-RGB and grey check (bareImageError) follows, in the caller.
1180
+ export const checkPixelArray = image => {
1181
+ if (isClustering(image) || isPalette(image)) {
1182
+ const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
1183
+ const fix = isClustering(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
1184
+ throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
1185
+ }
1186
+ if (isDetached(image)) {
1187
+ return;
1188
+ }
1189
+ if (isUint8Array(image)) {
1190
+ const encoded = sniffImageFormat(image);
1191
+ if (encoded) {
1192
+ throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
1193
+ }
1194
+ if (image.length % 4 !== 0) {
1195
+ throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
1196
+ }
1197
+ return;
1198
+ }
1199
+ throw fail('invalid-argument', `Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.${sixteenBit(image)}`, 'image');
1200
+ };
1201
+
1202
+ // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
1203
+ // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
1204
+ // alpha from which an RGBA pixel needs a colour.
1205
+ export const checkNotEmpty = (palette, image, cutoff) => {
1206
+ if (palette.length > 0) {
1207
+ return;
1208
+ }
1209
+ const data = image.data;
1210
+ let visible = hasAlpha(image.format) ? false : data.length > 0;
1211
+ for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
1212
+ visible = data[i] >= cutoff;
1213
+ }
1214
+ if (visible) {
1215
+ throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
1216
+ }
1217
+ };
1218
+
1219
+ // What clustering.chooseFrom checks about its palette and k, in order: the palette is flat RGB bytes and not empty, k is a
1220
+ // whole number of colours and no more than the palette has. Returns k.
1221
+ export const checkChoice = (palette, k) => {
1222
+ checkPalette(palette);
1223
+ if (palette.length === 0) {
1224
+ throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1225
+ }
1226
+ const count = palette.length / 3;
1227
+ k = checkK(k);
1228
+ if (k > count) {
1229
+ throw fail('invalid-argument', `Invalid k: ${k} is more than the ${counted(count, 'entry', 'entries')} in the palette; use ${count} or fewer.`, 'k');
1230
+ }
1231
+ return k;
1030
1232
  };
@@ -188,7 +188,7 @@ const respond = async ({
188
188
  stack: error.stack
189
189
  } : {
190
190
  name: 'Error',
191
- message: String(error),
191
+ message: typeof error === 'function' ? 'a function was thrown' : String(error),
192
192
  code: 'worker-failed'
193
193
  }
194
194
  });