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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/shared.cjs CHANGED
@@ -6,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.isClustering = exports.isArrayBufferLike = exports.imageHint = 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.3';
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,72 @@ 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]';
61
- };
62
- var isUint8ClampedArray = exports.isUint8ClampedArray = function isUint8ClampedArray(value) {
63
- return ArrayBuffer.isView(value) && tag(value) === '[object Uint8ClampedArray]';
64
- };
65
- var isArrayBufferLike = exports.isArrayBufferLike = function isArrayBufferLike(value) {
66
- return tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
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
+ // 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.
48
+ exports.isArrayBufferLike = isArrayBufferLike;
49
+ const imageHint = image => {
50
+ const decode = " Decode it to pixels first, then pass them.";
51
+ if (image === undefined || image === null) {
52
+ return ` Got ${image}.`;
53
+ }
54
+ if (typeof image === 'string') {
55
+ return ` Got a string (a file name, URL or data URL?): load and decode it to pixels first.`;
56
+ }
57
+ if (typeof image !== 'object') {
58
+ return ` Got a ${typeof image}.`;
59
+ }
60
+ if (Array.isArray(image)) {
61
+ return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
62
+ }
63
+ if (isArrayBufferLike(image)) {
64
+ 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).";
65
+ }
66
+ if (typeof image.getContext === 'function') {
67
+ return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
68
+ }
69
+ if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
70
+ return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
71
+ }
72
+ if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
73
+ return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
74
+ }
75
+ if (image.data && !image.format) {
76
+ return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
77
+ }
78
+ return '';
67
79
  };
68
80
 
69
81
  // An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
70
82
  // `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
71
83
  // (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
- };
84
+ exports.imageHint = imageHint;
85
+ const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
75
86
 
76
87
  // One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
77
88
  // Object.create(defaults) work and an inherited typo is still caught), each read a single time. Everything after this
78
89
  // uses the copy, so what is validated is what is used, even if a property is a getter that answers differently each time.
79
90
  // 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) {
91
+ exports.isOptionsObject = isOptionsObject;
92
+ const snapshot = options => {
93
+ const copy = Object.create(null);
94
+ for (const key in options) {
83
95
  copy[key] = options[key];
84
96
  }
85
97
  return copy;
@@ -94,30 +106,23 @@ var snapshot = exports.snapshot = function snapshot(options) {
94
106
  // IndexedDB) give plain untagged Uint8Arrays. `Palette` and `Clustering` are how to make one by hand, and `instanceof`
95
107
  // recognises them. The tags are found by a symbol registered with Symbol.for, so a copy of the library loaded twice (the
96
108
  // 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
- };
109
+ exports.snapshot = snapshot;
110
+ const paletteBrand = Symbol.for('agglomerative-clustering.palette');
111
+ const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
112
+ const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
113
+ exports.isPalette = isPalette;
114
+ const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
105
115
  // Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
106
116
  // `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
- };
117
+ exports.isClustering = isClustering;
118
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
119
+ const view = label => function (depth, options, nodeInspect) {
120
+ const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
121
+ return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
113
122
  };
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) {
123
+ const paletteView = view(palette => `Palette(${palette.colorSpace})`);
124
+ const clusteringView = view(() => 'Clustering');
125
+ const markPalette = (bytes, colorSpace) => {
121
126
  Object.defineProperty(bytes, paletteBrand, {
122
127
  value: true
123
128
  });
@@ -129,7 +134,8 @@ var markPalette = exports.markPalette = function markPalette(bytes, colorSpace)
129
134
  });
130
135
  return bytes;
131
136
  };
132
- var markClustering = exports.markClustering = function markClustering(bytes) {
137
+ exports.markPalette = markPalette;
138
+ const markClustering = bytes => {
133
139
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
134
140
  checked.add(bytes);
135
141
  Object.defineProperty(bytes, clusteringBrand, {
@@ -145,8 +151,8 @@ var markClustering = exports.markClustering = function markClustering(bytes) {
145
151
  // 'oklab')` copies `bytes` (or makes `length` zeros, or takes an array of byte values) and returns a Uint8Array tagged so.
146
152
  // A function and not a `class`, because it returns a plain Uint8Array and answers `instanceof` itself, which transpiled class
147
153
  // checks would trip over.
148
- function Palette(source) {
149
- var colorSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'rgb';
154
+ exports.markClustering = markClustering;
155
+ function Palette(source, colorSpace = 'rgb') {
150
156
  if (!Object.keys(colorSpaces).includes(colorSpace)) {
151
157
  throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'colorSpace');
152
158
  }
@@ -170,27 +176,22 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
170
176
 
171
177
  // The bytes of a clustering, checked: `new Clustering(bytes)` is how stored clusterings get their type back. Arguments are
172
178
  // 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];
179
+ function Clustering(...args) {
180
+ const [source] = args;
178
181
  // Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
179
182
  // would coerce. A plain array must hold byte values, as for a palette.
180
- var isBuffer = isArrayBufferLike(source);
183
+ const isBuffer = isArrayBufferLike(source);
181
184
  if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
182
185
  throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from getClustering.", 'clustering');
183
186
  }
184
- if (Array.isArray(source) && !source.every(function (value) {
185
- return Number.isInteger(value) && value >= 0 && value <= 255;
186
- })) {
187
+ if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
187
188
  throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
188
189
  }
189
- var bytes;
190
+ let bytes;
190
191
  try {
191
- bytes = _construct(Uint8Array, args);
192
+ bytes = new Uint8Array(...args);
192
193
  } catch (error) {
193
- throw fail('invalid-clustering', "Invalid clustering: ".concat(error.message, "."), 'clustering');
194
+ throw fail('invalid-clustering', `Invalid clustering: ${error.message}.`, 'clustering');
194
195
  }
195
196
  readHeader(bytes);
196
197
  return markClustering(bytes);
@@ -207,11 +208,11 @@ Object.defineProperty(Clustering, Symbol.hasInstance, {
207
208
  // version 3: [0xAC, 3, header length, record length, colour space, precision, weight unit, weight shift,
208
209
  // total weight (u32 LE), 0, grouped error (f32 LE, from header length 17), ...], then records of
209
210
  // 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;
211
+ const latestVersion = exports.latestVersion = 3;
211
212
 
212
213
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
213
214
  // `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;
215
+ const formatVersion = exports.formatVersion = latestVersion;
215
216
 
216
217
  // ----- Checksums -----------------------------------------------------------------------------------------------------
217
218
  // 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 +220,74 @@ var formatVersion = exports.formatVersion = latestVersion;
219
220
  // is used, and the arrays that passed (and the ones this library made) are remembered, so cutting one clustering
220
221
  // again and again checks it once. Changing a clustering's bytes after that is not detected here, but the records are
221
222
  // 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++) {
223
+ const checksumAt = 17;
224
+ // Computed 8 bytes at a time with eight tables (slicing-by-8), about 4 times faster than byte by byte: a clustering of a
225
+ // photo is 1-2 MB, and is checked the first time it is used.
226
+ let crcTables = null;
227
+ const crc32 = bytes => {
228
+ if (!crcTables) {
229
+ crcTables = Array.from({
230
+ length: 8
231
+ }, () => new Uint32Array(256));
232
+ for (let n = 0; n < 256; n++) {
233
+ let c = n;
234
+ for (let b = 0; b < 8; b++) {
230
235
  c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
231
236
  }
232
- crcTable[n] = c >>> 0;
237
+ crcTables[0][n] = c >>> 0;
233
238
  }
239
+ for (let n = 0; n < 256; n++) {
240
+ for (let t = 1; t < 8; t++) {
241
+ crcTables[t][n] = crcTables[t - 1][n] >>> 8 ^ crcTables[0][crcTables[t - 1][n] & 0xFF];
242
+ }
243
+ }
244
+ }
245
+ const [t0, t1, t2, t3, t4, t5, t6, t7] = crcTables;
246
+ let crc = 0xFFFFFFFF;
247
+ const byte = i => i >= checksumAt && i < checksumAt + 4 ? 0 : bytes[i];
248
+ let i = 0;
249
+ // The checksum field lies in the first 24 bytes, which go byte by byte; the rest 8 at a time.
250
+ for (; i < Math.min(24, bytes.length); i++) {
251
+ crc = t0[(crc ^ byte(i)) & 0xFF] ^ crc >>> 8;
252
+ }
253
+ const end = bytes.length - 7;
254
+ for (; i < end; i += 8) {
255
+ const a = (crc ^ (bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)) >>> 0;
256
+ 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]];
234
257
  }
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;
258
+ for (; i < bytes.length; i++) {
259
+ crc = t0[(crc ^ bytes[i]) & 0xFF] ^ crc >>> 8;
239
260
  }
240
261
  return (crc ^ 0xFFFFFFFF) >>> 0;
241
262
  };
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
- };
263
+ const checked = new WeakSet();
264
+ 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
265
 
247
266
  // The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
248
267
  // and a length of 0 or 3 more than a multiple of 9).
249
- var notAClustering = function notAClustering(clustering) {
250
- var length = clustering.length;
268
+ const notAClustering = clustering => {
269
+ const length = clustering.length;
251
270
  if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
252
271
  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
272
  }
254
273
  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');
274
+ 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
275
  }
257
- return fail('invalid-clustering', "Invalid clustering: not a clustering from getClustering (".concat(length, " bytes that don't start with a clustering header)."), 'clustering');
276
+ return fail('invalid-clustering', `Invalid clustering: not a clustering from getClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
258
277
  };
259
- var readHeader = exports.readHeader = function readHeader(clustering) {
278
+ const readHeader = clustering => {
260
279
  if (isPalette(clustering)) {
261
280
  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
281
  }
263
282
  if (!isUint8Array(clustering)) {
264
283
  throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from getClustering.", 'clustering');
265
284
  }
266
- var length = clustering.length;
285
+ const length = clustering.length;
267
286
  if (length >= 4 && clustering[0] === 0xAC) {
268
- var _version = clustering[1];
269
- if (_version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
287
+ const version = clustering[1];
288
+ if (version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
270
289
  return {
271
- version: _version,
290
+ version,
272
291
  colorSpace: clustering[2],
273
292
  precision: clustering[3],
274
293
  transparent: 0,
@@ -277,8 +296,8 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
277
296
  merges: length === 4 ? 0 : (length - 7) / 9
278
297
  };
279
298
  }
280
- if (_version === 3 && length >= 13) {
281
- var headerLength = clustering[2],
299
+ if (version === 3 && length >= 13) {
300
+ const headerLength = clustering[2],
282
301
  recordLength = clustering[3];
283
302
  if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
284
303
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
@@ -286,32 +305,32 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
286
305
  if (clustering[4] > 1 || clustering[6] > 1) {
287
306
  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');
288
307
  }
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;
308
+ const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
309
+ const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
291
310
  if (padding < 9) {
292
311
  // Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
293
312
  // makes one look that short skips this check, but then the records don't line up, which the replay reports.
294
313
  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;
314
+ const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
296
315
  if (stored !== 0 && stored !== crc32(clustering)) {
297
316
  throw damaged();
298
317
  }
299
318
  checked.add(clustering);
300
319
  }
301
320
  return {
302
- version: _version,
321
+ version,
303
322
  colorSpace: clustering[4],
304
323
  precision: clustering[5],
305
324
  transparent: clustering[12],
306
- headerLength: headerLength,
307
- recordLength: recordLength,
308
- merges: merges
325
+ headerLength,
326
+ recordLength,
327
+ merges
309
328
  };
310
329
  }
311
330
  }
312
331
  }
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');
332
+ if (version > latestVersion) {
333
+ throw fail('unsupported-version', `Invalid clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
315
334
  }
316
335
  }
317
336
  throw notAClustering(clustering);
@@ -319,7 +338,8 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
319
338
 
320
339
  // Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
321
340
  // image, and quantize maps such an image the same way.
322
- var checkPalette = exports.checkPalette = function checkPalette(palette) {
341
+ exports.readHeader = readHeader;
342
+ const checkPalette = palette => {
323
343
  if (isClustering(palette)) {
324
344
  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
345
  }
@@ -332,19 +352,10 @@ var checkPalette = exports.checkPalette = function checkPalette(palette) {
332
352
  // Typed arrays are bytes already. A plain array is copied into bytes, which would turn an array of [r, g, b] colours
333
353
  // into zeros, strings into numbers and 300 into 44 without a word, so it must hold byte values.
334
354
  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
- }
355
+ for (const value of palette) {
356
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
357
+ 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
358
  }
344
- } catch (err) {
345
- _iterator.e(err);
346
- } finally {
347
- _iterator.f();
348
359
  }
349
360
  }
350
361
  };
@@ -353,32 +364,36 @@ var checkPalette = exports.checkPalette = function checkPalette(palette) {
353
364
  // A structured clone drops the tags (a palette's colour space with them), so palettes and clusterings cross to and from the
354
365
  // worker thread as small markers and become typed arrays again on the other side: `mark` before posting (an argument, a
355
366
  // result, or a property of a result), `revive` after receiving.
356
- var MARK = exports.MARK = '__agglomerativeClustering';
357
- var markOne = function markOne(value) {
367
+ exports.checkPalette = checkPalette;
368
+ const MARK = exports.MARK = '__agglomerativeClustering';
369
+ const markOne = value => {
358
370
  if (isPalette(value)) {
359
- return _defineProperty(_defineProperty(_defineProperty({}, MARK, 'palette'), "bytes", new Uint8Array(value.buffer, value.byteOffset, value.length)), "colorSpace", value.colorSpace);
371
+ return {
372
+ [MARK]: 'palette',
373
+ bytes: new Uint8Array(value.buffer, value.byteOffset, value.length),
374
+ colorSpace: value.colorSpace
375
+ };
360
376
  }
361
377
  if (isClustering(value)) {
362
- return _defineProperty(_defineProperty({}, MARK, 'clustering'), "bytes", new Uint8Array(value.buffer, value.byteOffset, value.length));
378
+ return {
379
+ [MARK]: 'clustering',
380
+ bytes: new Uint8Array(value.buffer, value.byteOffset, value.length)
381
+ };
363
382
  }
364
383
  return value;
365
384
  };
366
- var mark = exports.mark = function mark(value) {
367
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
385
+ const mark = value => {
386
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
368
387
  return markOne(value);
369
388
  }
370
389
  if (!isOptionsObject(value)) {
371
390
  return value;
372
391
  }
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
- }));
392
+ return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, markOne(part)]));
379
393
  };
380
- var reviveOne = function reviveOne(value) {
381
- if (!value || _typeof(value) !== 'object' || !value[MARK]) {
394
+ exports.mark = mark;
395
+ const reviveOne = value => {
396
+ if (!value || typeof value !== 'object' || !value[MARK]) {
382
397
  return value;
383
398
  }
384
399
  if (value[MARK] === 'palette') {
@@ -386,8 +401,8 @@ var reviveOne = function reviveOne(value) {
386
401
  }
387
402
  return markClustering(new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.length));
388
403
  };
389
- var revive = exports.revive = function revive(value) {
390
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
404
+ const revive = value => {
405
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
391
406
  return value;
392
407
  }
393
408
  if (value[MARK]) {
@@ -396,9 +411,9 @@ var revive = exports.revive = function revive(value) {
396
411
  if (!isOptionsObject(value)) {
397
412
  return value;
398
413
  }
399
- for (var _i = 0, _Object$keys = Object.keys(value); _i < _Object$keys.length; _i++) {
400
- var key = _Object$keys[_i];
414
+ for (const key of Object.keys(value)) {
401
415
  value[key] = reviveOne(value[key]);
402
416
  }
403
417
  return value;
404
- };
418
+ };
419
+ exports.revive = revive;