agglomerative-clustering 3.0.0-beta.2 → 3.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,35 +6,19 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isClustering = exports.isArrayBufferLike = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
10
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
11
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
12
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
13
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
14
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
15
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
16
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
17
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
18
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
19
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
20
- function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
21
- function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
22
- function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
23
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
9
+ exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isDetached = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
24
10
  // Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
25
11
  // header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
26
12
  // './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
27
13
 
28
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
29
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
30
- var version = exports.version = '3.0.0-beta.2';
31
- var colorSpaces = exports.colorSpaces = {
16
+ const version = exports.version = '3.0.0-beta.4';
17
+ const colorSpaces = exports.colorSpaces = {
32
18
  'rgb': 0,
33
19
  'oklab': 1
34
20
  };
35
- var colorSpaceName = exports.colorSpaceName = function colorSpaceName(code) {
36
- return code === 1 ? 'oklab' : 'rgb';
37
- };
21
+ const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
38
22
 
39
23
  // Every error this library throws is an Error with a `code` saying what went wrong, so callers needn't match on message
40
24
  // text: 'invalid-argument' (image, k, options, palette), 'invalid-clustering', 'unsupported-version' (a clustering from a
@@ -42,44 +26,107 @@ var colorSpaceName = exports.colorSpaceName = function colorSpaceName(code) {
42
26
  // 'worker-terminated', 'worker-failed' and 'invalid-handle'. When the error is about one argument, `argument` names it
43
27
  // for programs (the message is for people): 'image', 'k', 'clustering', 'palette', 'options', or 'options.<key>' for
44
28
  // one option.
45
- var fail = exports.fail = function fail(code, message, argument) {
46
- return Object.assign(new Error(message), argument === undefined ? {
47
- code: code
48
- } : {
49
- code: code,
50
- argument: argument
51
- });
52
- };
29
+ exports.colorSpaceName = colorSpaceName;
30
+ const fail = (code, message, argument) => Object.assign(new Error(message), argument === undefined ? {
31
+ code
32
+ } : {
33
+ code,
34
+ argument
35
+ });
53
36
 
54
37
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
55
38
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
56
- var tag = function tag(value) {
57
- return Object.prototype.toString.call(value);
58
- };
59
- var isUint8Array = exports.isUint8Array = function isUint8Array(value) {
60
- return ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
39
+ exports.fail = fail;
40
+ const tag = value => Object.prototype.toString.call(value);
41
+ const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
42
+ exports.isUint8Array = isUint8Array;
43
+ const isUint8ClampedArray = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8ClampedArray]';
44
+ exports.isUint8ClampedArray = isUint8ClampedArray;
45
+ const isArrayBufferLike = value => tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
46
+
47
+ // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
48
+ exports.isArrayBufferLike = isArrayBufferLike;
49
+ const isDetached = view => {
50
+ const buffer = view.buffer;
51
+ if (typeof buffer.detached === 'boolean') {
52
+ return buffer.detached;
53
+ }
54
+ try {
55
+ new Uint8Array(buffer, 0, 0);
56
+ return false;
57
+ } catch (error) {
58
+ return true;
59
+ }
61
60
  };
62
- var isUint8ClampedArray = exports.isUint8ClampedArray = function isUint8ClampedArray(value) {
63
- return ArrayBuffer.isView(value) && tag(value) === '[object Uint8ClampedArray]';
61
+
62
+ // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
63
+ // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
64
+ // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
65
+ exports.isDetached = isDetached;
66
+ const imageDataLike = (like, pixels) => {
67
+ const {
68
+ width,
69
+ height,
70
+ colorSpace
71
+ } = like;
72
+ const own = like.constructor;
73
+ const make = typeof own === 'function' && own.name === 'ImageData' ? own : typeof ImageData === 'function' ? ImageData : null;
74
+ if (!make) {
75
+ throw fail('invalid-argument', "Invalid image: an ImageData whose class can't be used to make the result. Pass { data, format: 'rgba', width } instead.", 'image');
76
+ }
77
+ return colorSpace ? new make(pixels, width, height, {
78
+ colorSpace
79
+ }) : new make(pixels, width, height);
64
80
  };
65
- var isArrayBufferLike = exports.isArrayBufferLike = function isArrayBufferLike(value) {
66
- return tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
81
+
82
+ // What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
83
+ exports.imageDataLike = imageDataLike;
84
+ const imageHint = image => {
85
+ const decode = " Decode it to pixels first, then pass them.";
86
+ if (image === undefined || image === null) {
87
+ return ` Got ${image}.`;
88
+ }
89
+ if (typeof image === 'string') {
90
+ return ` Got a string (a file name, URL or data URL?): load and decode it to pixels first.`;
91
+ }
92
+ if (typeof image !== 'object') {
93
+ return ` Got a ${typeof image}.`;
94
+ }
95
+ if (Array.isArray(image)) {
96
+ return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
97
+ }
98
+ if (isArrayBufferLike(image)) {
99
+ return " Got an ArrayBuffer, which has no pixel layout: wrap it, new Uint8Array(buffer) for RGBA bytes (if it holds an encoded image file, decode it first).";
100
+ }
101
+ if (typeof image.getContext === 'function') {
102
+ return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
103
+ }
104
+ if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
105
+ return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
106
+ }
107
+ if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
108
+ return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
109
+ }
110
+ if (image.data && !image.format) {
111
+ return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
112
+ }
113
+ return '';
67
114
  };
68
115
 
69
116
  // An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
70
117
  // `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
71
118
  // (an iframe, a test sandbox) are fine.
72
- var isOptionsObject = exports.isOptionsObject = function isOptionsObject(value) {
73
- return value !== null && _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Object]';
74
- };
119
+ exports.imageHint = imageHint;
120
+ const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
75
121
 
76
122
  // One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
77
123
  // Object.create(defaults) work and an inherited typo is still caught), each read a single time. Everything after this
78
124
  // uses the copy, so what is validated is what is used, even if a property is a getter that answers differently each time.
79
125
  // The copy has no prototype, so a key like '__proto__' is just a name.
80
- var snapshot = exports.snapshot = function snapshot(options) {
81
- var copy = Object.create(null);
82
- for (var key in options) {
126
+ exports.isOptionsObject = isOptionsObject;
127
+ const snapshot = options => {
128
+ const copy = Object.create(null);
129
+ for (const key in options) {
83
130
  copy[key] = options[key];
84
131
  }
85
132
  return copy;
@@ -94,30 +141,23 @@ var snapshot = exports.snapshot = function snapshot(options) {
94
141
  // IndexedDB) give plain untagged Uint8Arrays. `Palette` and `Clustering` are how to make one by hand, and `instanceof`
95
142
  // recognises them. The tags are found by a symbol registered with Symbol.for, so a copy of the library loaded twice (the
96
143
  // ES module and CommonJS builds, a bundler's duplicate, the worker entry's own copy) recognises the other's.
97
- var paletteBrand = Symbol["for"]('agglomerative-clustering.palette');
98
- var clusteringBrand = Symbol["for"]('agglomerative-clustering.clustering');
99
- var isPalette = exports.isPalette = function isPalette(value) {
100
- return isUint8Array(value) && value[paletteBrand] === true;
101
- };
102
- var isClustering = exports.isClustering = function isClustering(value) {
103
- return isUint8Array(value) && value[clusteringBrand] === true;
104
- };
144
+ exports.snapshot = snapshot;
145
+ const paletteBrand = Symbol.for('agglomerative-clustering.palette');
146
+ const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
147
+ const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
148
+ exports.isPalette = isPalette;
149
+ const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
105
150
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
106
151
  // `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
107
- var inspect = Symbol["for"]('nodejs.util.inspect.custom');
108
- var view = function view(label) {
109
- return function (depth, options, nodeInspect) {
110
- var plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
111
- return "".concat(label(this), " ").concat(typeof nodeInspect === 'function' ? nodeInspect(plain, options) : "[".concat(plain.length, " bytes]"));
112
- };
152
+ exports.isClustering = isClustering;
153
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
154
+ const view = label => function (depth, options, nodeInspect) {
155
+ const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
156
+ return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
113
157
  };
114
- var paletteView = view(function (palette) {
115
- return "Palette(".concat(palette.colorSpace, ")");
116
- });
117
- var clusteringView = view(function () {
118
- return 'Clustering';
119
- });
120
- var markPalette = exports.markPalette = function markPalette(bytes, colorSpace) {
158
+ const paletteView = view(palette => `Palette(${palette.colorSpace})`);
159
+ const clusteringView = view(() => 'Clustering');
160
+ const markPalette = (bytes, colorSpace) => {
121
161
  Object.defineProperty(bytes, paletteBrand, {
122
162
  value: true
123
163
  });
@@ -129,7 +169,8 @@ var markPalette = exports.markPalette = function markPalette(bytes, colorSpace)
129
169
  });
130
170
  return bytes;
131
171
  };
132
- var markClustering = exports.markClustering = function markClustering(bytes) {
172
+ exports.markPalette = markPalette;
173
+ const markClustering = bytes => {
133
174
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
134
175
  checked.add(bytes);
135
176
  Object.defineProperty(bytes, clusteringBrand, {
@@ -145,8 +186,8 @@ var markClustering = exports.markClustering = function markClustering(bytes) {
145
186
  // 'oklab')` copies `bytes` (or makes `length` zeros, or takes an array of byte values) and returns a Uint8Array tagged so.
146
187
  // A function and not a `class`, because it returns a plain Uint8Array and answers `instanceof` itself, which transpiled class
147
188
  // checks would trip over.
148
- function Palette(source) {
149
- var colorSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'rgb';
189
+ exports.markClustering = markClustering;
190
+ function Palette(source, colorSpace = 'rgb') {
150
191
  if (!Object.keys(colorSpaces).includes(colorSpace)) {
151
192
  throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'colorSpace');
152
193
  }
@@ -170,27 +211,22 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
170
211
 
171
212
  // The bytes of a clustering, checked: `new Clustering(bytes)` is how stored clusterings get their type back. Arguments are
172
213
  // those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
173
- function Clustering() {
174
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
175
- args[_key] = arguments[_key];
176
- }
177
- var source = args[0];
214
+ function Clustering(...args) {
215
+ const [source] = args;
178
216
  // Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
179
217
  // would coerce. A plain array must hold byte values, as for a palette.
180
- var isBuffer = isArrayBufferLike(source);
218
+ const isBuffer = isArrayBufferLike(source);
181
219
  if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
182
220
  throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from getClustering.", 'clustering');
183
221
  }
184
- if (Array.isArray(source) && !source.every(function (value) {
185
- return Number.isInteger(value) && value >= 0 && value <= 255;
186
- })) {
222
+ if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
187
223
  throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
188
224
  }
189
- var bytes;
225
+ let bytes;
190
226
  try {
191
- bytes = _construct(Uint8Array, args);
227
+ bytes = new Uint8Array(...args);
192
228
  } catch (error) {
193
- throw fail('invalid-clustering', "Invalid clustering: ".concat(error.message, "."), 'clustering');
229
+ throw fail('invalid-clustering', `Invalid clustering: ${error.message}.`, 'clustering');
194
230
  }
195
231
  readHeader(bytes);
196
232
  return markClustering(bytes);
@@ -207,11 +243,11 @@ Object.defineProperty(Clustering, Symbol.hasInstance, {
207
243
  // version 3: [0xAC, 3, header length, record length, colour space, precision, weight unit, weight shift,
208
244
  // total weight (u32 LE), 0, grouped error (f32 LE, from header length 17), ...], then records of
209
245
  // colours, parent index, lighter weight and cost; from 3.0.0-beta.2 the header holds a checksum (bytes 17-20)
210
- var latestVersion = exports.latestVersion = 3;
246
+ const latestVersion = exports.latestVersion = 3;
211
247
 
212
248
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
213
249
  // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
214
- var formatVersion = exports.formatVersion = latestVersion;
250
+ const formatVersion = exports.formatVersion = latestVersion;
215
251
 
216
252
  // ----- Checksums -----------------------------------------------------------------------------------------------------
217
253
  // From 3.0.0-beta.2, a version 3 header holds the CRC-32 of the whole clustering (bytes 17-20, read as zeros while it is
@@ -219,56 +255,74 @@ var formatVersion = exports.formatVersion = latestVersion;
219
255
  // is used, and the arrays that passed (and the ones this library made) are remembered, so cutting one clustering
220
256
  // again and again checks it once. Changing a clustering's bytes after that is not detected here, but the records are
221
257
  // also checked as they are replayed, so it still can't give a palette of the wrong size.
222
- var checksumAt = 17;
223
- var crcTable = null;
224
- var crc32 = function crc32(bytes) {
225
- if (!crcTable) {
226
- crcTable = new Uint32Array(256);
227
- for (var n = 0; n < 256; n++) {
228
- var c = n;
229
- for (var b = 0; b < 8; b++) {
258
+ const checksumAt = 17;
259
+ // Computed 8 bytes at a time with eight tables (slicing-by-8), about 4 times faster than byte by byte: a clustering of a
260
+ // photo is 1-2 MB, and is checked the first time it is used.
261
+ let crcTables = null;
262
+ const crc32 = bytes => {
263
+ if (!crcTables) {
264
+ crcTables = Array.from({
265
+ length: 8
266
+ }, () => new Uint32Array(256));
267
+ for (let n = 0; n < 256; n++) {
268
+ let c = n;
269
+ for (let b = 0; b < 8; b++) {
230
270
  c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
231
271
  }
232
- crcTable[n] = c >>> 0;
272
+ crcTables[0][n] = c >>> 0;
273
+ }
274
+ for (let n = 0; n < 256; n++) {
275
+ for (let t = 1; t < 8; t++) {
276
+ crcTables[t][n] = crcTables[t - 1][n] >>> 8 ^ crcTables[0][crcTables[t - 1][n] & 0xFF];
277
+ }
233
278
  }
234
279
  }
235
- var crc = 0xFFFFFFFF;
236
- for (var i = 0; i < bytes.length; i++) {
237
- var _byte = i >= checksumAt && i < checksumAt + 4 ? 0 : bytes[i];
238
- crc = crcTable[(crc ^ _byte) & 0xFF] ^ crc >>> 8;
280
+ const [t0, t1, t2, t3, t4, t5, t6, t7] = crcTables;
281
+ let crc = 0xFFFFFFFF;
282
+ const byte = i => i >= checksumAt && i < checksumAt + 4 ? 0 : bytes[i];
283
+ let i = 0;
284
+ // The checksum field lies in the first 24 bytes, which go byte by byte; the rest 8 at a time.
285
+ for (; i < Math.min(24, bytes.length); i++) {
286
+ crc = t0[(crc ^ byte(i)) & 0xFF] ^ crc >>> 8;
287
+ }
288
+ const end = bytes.length - 7;
289
+ for (; i < end; i += 8) {
290
+ const a = (crc ^ (bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)) >>> 0;
291
+ crc = t7[a & 0xFF] ^ t6[a >>> 8 & 0xFF] ^ t5[a >>> 16 & 0xFF] ^ t4[a >>> 24] ^ t3[bytes[i + 4]] ^ t2[bytes[i + 5]] ^ t1[bytes[i + 6]] ^ t0[bytes[i + 7]];
292
+ }
293
+ for (; i < bytes.length; i++) {
294
+ crc = t0[(crc ^ bytes[i]) & 0xFF] ^ crc >>> 8;
239
295
  }
240
296
  return (crc ^ 0xFFFFFFFF) >>> 0;
241
297
  };
242
- var checked = new WeakSet();
243
- var damaged = function damaged() {
244
- return fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after getClustering made it. Cluster the image again.", 'clustering');
245
- };
298
+ const checked = new WeakSet();
299
+ const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after getClustering made it. Cluster the image again.", 'clustering');
246
300
 
247
301
  // The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
248
302
  // and a length of 0 or 3 more than a multiple of 9).
249
- var notAClustering = function notAClustering(clustering) {
250
- var length = clustering.length;
303
+ const notAClustering = clustering => {
304
+ const length = clustering.length;
251
305
  if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
252
306
  return fail('invalid-clustering', "Invalid clustering: not a clustering from getClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
253
307
  }
254
308
  if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
255
- return fail('invalid-clustering', "Invalid clustering: it starts like a format ".concat(clustering[1], " clustering, but its length or header doesn't fit one (").concat(length, " bytes): it was probably truncated or damaged. Cluster the image again."), 'clustering');
309
+ 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');
256
310
  }
257
- return fail('invalid-clustering', "Invalid clustering: not a clustering from getClustering (".concat(length, " bytes that don't start with a clustering header)."), 'clustering');
311
+ return fail('invalid-clustering', `Invalid clustering: not a clustering from getClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
258
312
  };
259
- var readHeader = exports.readHeader = function readHeader(clustering) {
313
+ const readHeader = clustering => {
260
314
  if (isPalette(clustering)) {
261
315
  throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from getPalette and getPaletteFromClustering; a clustering comes from getClustering.", 'clustering');
262
316
  }
263
317
  if (!isUint8Array(clustering)) {
264
318
  throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from getClustering.", 'clustering');
265
319
  }
266
- var length = clustering.length;
320
+ const length = clustering.length;
267
321
  if (length >= 4 && clustering[0] === 0xAC) {
268
- var _version = clustering[1];
269
- if (_version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
322
+ const version = clustering[1];
323
+ if (version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
270
324
  return {
271
- version: _version,
325
+ version,
272
326
  colorSpace: clustering[2],
273
327
  precision: clustering[3],
274
328
  transparent: 0,
@@ -277,41 +331,41 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
277
331
  merges: length === 4 ? 0 : (length - 7) / 9
278
332
  };
279
333
  }
280
- if (_version === 3 && length >= 13) {
281
- var headerLength = clustering[2],
334
+ if (version === 3 && length >= 13) {
335
+ const headerLength = clustering[2],
282
336
  recordLength = clustering[3];
283
337
  if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
284
338
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
285
339
  // doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
286
340
  if (clustering[4] > 1 || clustering[6] > 1) {
287
- throw fail('unsupported-version', "Invalid clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
341
+ throw fail('unsupported-version', "Unsupported clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
288
342
  }
289
- var merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
290
- var padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
343
+ const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
344
+ const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
291
345
  if (padding < 9) {
292
346
  // Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
293
347
  // makes one look that short skips this check, but then the records don't line up, which the replay reports.
294
348
  if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
295
- var stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
349
+ const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
296
350
  if (stored !== 0 && stored !== crc32(clustering)) {
297
351
  throw damaged();
298
352
  }
299
353
  checked.add(clustering);
300
354
  }
301
355
  return {
302
- version: _version,
356
+ version,
303
357
  colorSpace: clustering[4],
304
358
  precision: clustering[5],
305
359
  transparent: clustering[12],
306
- headerLength: headerLength,
307
- recordLength: recordLength,
308
- merges: merges
360
+ headerLength,
361
+ recordLength,
362
+ merges
309
363
  };
310
364
  }
311
365
  }
312
366
  }
313
- if (_version > latestVersion) {
314
- throw fail('unsupported-version', "Invalid clustering: format version ".concat(_version, " is newer than this version of agglomerative-clustering reads. Upgrade the package."), 'clustering');
367
+ if (version > latestVersion) {
368
+ throw fail('unsupported-version', `Unsupported clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
315
369
  }
316
370
  }
317
371
  throw notAClustering(clustering);
@@ -319,32 +373,27 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
319
373
 
320
374
  // Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
321
375
  // image, and quantize maps such an image the same way.
322
- var checkPalette = exports.checkPalette = function checkPalette(palette) {
376
+ exports.readHeader = readHeader;
377
+ const checkPalette = palette => {
323
378
  if (isClustering(palette)) {
324
379
  throw fail('invalid-argument', "Invalid palette: this is a clustering (from getClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
325
380
  }
326
381
  if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
327
382
  throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
328
383
  }
384
+ if (Array.isArray(palette) && palette.some(value => Array.isArray(value) || ArrayBuffer.isView(value))) {
385
+ throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255, not an array of [r, g, b] colours. Flatten it first: colours.flat().", 'palette');
386
+ }
329
387
  if (palette.length % 3 !== 0) {
330
388
  throw fail('invalid-argument', "Invalid palette: length must be a multiple of 3 (flat RGB bytes).", 'palette');
331
389
  }
332
390
  // Typed arrays are bytes already. A plain array is copied into bytes, which would turn an array of [r, g, b] colours
333
391
  // into zeros, strings into numbers and 300 into 44 without a word, so it must hold byte values.
334
392
  if (Array.isArray(palette)) {
335
- var _iterator = _createForOfIteratorHelper(palette),
336
- _step;
337
- try {
338
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
339
- var value = _step.value;
340
- if (!Number.isInteger(value) || value < 0 || value > 255) {
341
- throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255 (not an array of [r, g, b] colours).", 'palette');
342
- }
393
+ for (const value of palette) {
394
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
395
+ throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255 (not an array of [r, g, b] colours).", 'palette');
343
396
  }
344
- } catch (err) {
345
- _iterator.e(err);
346
- } finally {
347
- _iterator.f();
348
397
  }
349
398
  }
350
399
  };
@@ -353,32 +402,36 @@ var checkPalette = exports.checkPalette = function checkPalette(palette) {
353
402
  // A structured clone drops the tags (a palette's colour space with them), so palettes and clusterings cross to and from the
354
403
  // worker thread as small markers and become typed arrays again on the other side: `mark` before posting (an argument, a
355
404
  // result, or a property of a result), `revive` after receiving.
356
- var MARK = exports.MARK = '__agglomerativeClustering';
357
- var markOne = function markOne(value) {
405
+ exports.checkPalette = checkPalette;
406
+ const MARK = exports.MARK = '__agglomerativeClustering';
407
+ const markOne = value => {
358
408
  if (isPalette(value)) {
359
- return _defineProperty(_defineProperty(_defineProperty({}, MARK, 'palette'), "bytes", new Uint8Array(value.buffer, value.byteOffset, value.length)), "colorSpace", value.colorSpace);
409
+ return {
410
+ [MARK]: 'palette',
411
+ bytes: new Uint8Array(value.buffer, value.byteOffset, value.length),
412
+ colorSpace: value.colorSpace
413
+ };
360
414
  }
361
415
  if (isClustering(value)) {
362
- return _defineProperty(_defineProperty({}, MARK, 'clustering'), "bytes", new Uint8Array(value.buffer, value.byteOffset, value.length));
416
+ return {
417
+ [MARK]: 'clustering',
418
+ bytes: new Uint8Array(value.buffer, value.byteOffset, value.length)
419
+ };
363
420
  }
364
421
  return value;
365
422
  };
366
- var mark = exports.mark = function mark(value) {
367
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
423
+ const mark = value => {
424
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
368
425
  return markOne(value);
369
426
  }
370
427
  if (!isOptionsObject(value)) {
371
428
  return value;
372
429
  }
373
- return Object.fromEntries(Object.entries(value).map(function (_ref3) {
374
- var _ref4 = _slicedToArray(_ref3, 2),
375
- key = _ref4[0],
376
- part = _ref4[1];
377
- return [key, markOne(part)];
378
- }));
430
+ return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, markOne(part)]));
379
431
  };
380
- var reviveOne = function reviveOne(value) {
381
- if (!value || _typeof(value) !== 'object' || !value[MARK]) {
432
+ exports.mark = mark;
433
+ const reviveOne = value => {
434
+ if (!value || typeof value !== 'object' || !value[MARK]) {
382
435
  return value;
383
436
  }
384
437
  if (value[MARK] === 'palette') {
@@ -386,8 +439,8 @@ var reviveOne = function reviveOne(value) {
386
439
  }
387
440
  return markClustering(new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.length));
388
441
  };
389
- var revive = exports.revive = function revive(value) {
390
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
442
+ const revive = value => {
443
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
391
444
  return value;
392
445
  }
393
446
  if (value[MARK]) {
@@ -396,9 +449,9 @@ var revive = exports.revive = function revive(value) {
396
449
  if (!isOptionsObject(value)) {
397
450
  return value;
398
451
  }
399
- for (var _i = 0, _Object$keys = Object.keys(value); _i < _Object$keys.length; _i++) {
400
- var key = _Object$keys[_i];
452
+ for (const key of Object.keys(value)) {
401
453
  value[key] = reviveOne(value[key]);
402
454
  }
403
455
  return value;
404
- };
456
+ };
457
+ exports.revive = revive;