agglomerative-clustering 3.0.0-beta.1 → 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.1';
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,10 @@ 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 => {
139
+ // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
140
+ checked.add(bytes);
133
141
  Object.defineProperty(bytes, clusteringBrand, {
134
142
  value: true
135
143
  });
@@ -143,8 +151,8 @@ var markClustering = exports.markClustering = function markClustering(bytes) {
143
151
  // 'oklab')` copies `bytes` (or makes `length` zeros, or takes an array of byte values) and returns a Uint8Array tagged so.
144
152
  // A function and not a `class`, because it returns a plain Uint8Array and answers `instanceof` itself, which transpiled class
145
153
  // checks would trip over.
146
- function Palette(source) {
147
- var colorSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'rgb';
154
+ exports.markClustering = markClustering;
155
+ function Palette(source, colorSpace = 'rgb') {
148
156
  if (!Object.keys(colorSpaces).includes(colorSpace)) {
149
157
  throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'colorSpace');
150
158
  }
@@ -168,27 +176,22 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
168
176
 
169
177
  // The bytes of a clustering, checked: `new Clustering(bytes)` is how stored clusterings get their type back. Arguments are
170
178
  // those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
171
- function Clustering() {
172
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
173
- args[_key] = arguments[_key];
174
- }
175
- var source = args[0];
179
+ function Clustering(...args) {
180
+ const [source] = args;
176
181
  // Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
177
182
  // would coerce. A plain array must hold byte values, as for a palette.
178
- var isBuffer = isArrayBufferLike(source);
183
+ const isBuffer = isArrayBufferLike(source);
179
184
  if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
180
185
  throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from getClustering.", 'clustering');
181
186
  }
182
- if (Array.isArray(source) && !source.every(function (value) {
183
- return Number.isInteger(value) && value >= 0 && value <= 255;
184
- })) {
187
+ if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
185
188
  throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
186
189
  }
187
- var bytes;
190
+ let bytes;
188
191
  try {
189
- bytes = _construct(Uint8Array, args);
192
+ bytes = new Uint8Array(...args);
190
193
  } catch (error) {
191
- throw fail('invalid-clustering', "Invalid clustering: ".concat(error.message, "."), 'clustering');
194
+ throw fail('invalid-clustering', `Invalid clustering: ${error.message}.`, 'clustering');
192
195
  }
193
196
  readHeader(bytes);
194
197
  return markClustering(bytes);
@@ -204,25 +207,87 @@ Object.defineProperty(Clustering, Symbol.hasInstance, {
204
207
  // version 2: [0xAC, 2, colour space, precision], then 9-byte records of colours
205
208
  // version 3: [0xAC, 3, header length, record length, colour space, precision, weight unit, weight shift,
206
209
  // total weight (u32 LE), 0, grouped error (f32 LE, from header length 17), ...], then records of
207
- // colours, parent index, lighter weight and cost
208
- var latestVersion = exports.latestVersion = 3;
210
+ // colours, parent index, lighter weight and cost; from 3.0.0-beta.2 the header holds a checksum (bytes 17-20)
211
+ const latestVersion = exports.latestVersion = 3;
209
212
 
210
213
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
211
214
  // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
212
- var formatVersion = exports.formatVersion = latestVersion;
213
- var readHeader = exports.readHeader = function readHeader(clustering) {
215
+ const formatVersion = exports.formatVersion = latestVersion;
216
+
217
+ // ----- Checksums -----------------------------------------------------------------------------------------------------
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
+ // computed; see src/clustering.cpp). 0 means none: beta.1 wrote zeros there. A clustering is checked the first time it
220
+ // is used, and the arrays that passed (and the ones this library made) are remembered, so cutting one clustering
221
+ // again and again checks it once. Changing a clustering's bytes after that is not detected here, but the records are
222
+ // also checked as they are replayed, so it still can't give a palette of the wrong size.
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++) {
235
+ c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
236
+ }
237
+ crcTables[0][n] = c >>> 0;
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]];
257
+ }
258
+ for (; i < bytes.length; i++) {
259
+ crc = t0[(crc ^ bytes[i]) & 0xFF] ^ crc >>> 8;
260
+ }
261
+ return (crc ^ 0xFFFFFFFF) >>> 0;
262
+ };
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');
265
+
266
+ // The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
267
+ // and a length of 0 or 3 more than a multiple of 9).
268
+ const notAClustering = clustering => {
269
+ const length = clustering.length;
270
+ if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
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');
272
+ }
273
+ if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
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');
275
+ }
276
+ return fail('invalid-clustering', `Invalid clustering: not a clustering from getClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
277
+ };
278
+ const readHeader = clustering => {
214
279
  if (isPalette(clustering)) {
215
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');
216
281
  }
217
282
  if (!isUint8Array(clustering)) {
218
283
  throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from getClustering.", 'clustering');
219
284
  }
220
- var length = clustering.length;
285
+ const length = clustering.length;
221
286
  if (length >= 4 && clustering[0] === 0xAC) {
222
- var _version = clustering[1];
223
- 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)) {
224
289
  return {
225
- version: _version,
290
+ version,
226
291
  colorSpace: clustering[2],
227
292
  precision: clustering[3],
228
293
  transparent: 0,
@@ -231,8 +296,8 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
231
296
  merges: length === 4 ? 0 : (length - 7) / 9
232
297
  };
233
298
  }
234
- if (_version === 3 && length >= 13) {
235
- var headerLength = clustering[2],
299
+ if (version === 3 && length >= 13) {
300
+ const headerLength = clustering[2],
236
301
  recordLength = clustering[3];
237
302
  if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
238
303
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
@@ -240,31 +305,41 @@ var readHeader = exports.readHeader = function readHeader(clustering) {
240
305
  if (clustering[4] > 1 || clustering[6] > 1) {
241
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');
242
307
  }
243
- var merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
244
- 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;
245
310
  if (padding < 9) {
311
+ // Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
312
+ // makes one look that short skips this check, but then the records don't line up, which the replay reports.
313
+ if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
314
+ const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
315
+ if (stored !== 0 && stored !== crc32(clustering)) {
316
+ throw damaged();
317
+ }
318
+ checked.add(clustering);
319
+ }
246
320
  return {
247
- version: _version,
321
+ version,
248
322
  colorSpace: clustering[4],
249
323
  precision: clustering[5],
250
324
  transparent: clustering[12],
251
- headerLength: headerLength,
252
- recordLength: recordLength,
253
- merges: merges
325
+ headerLength,
326
+ recordLength,
327
+ merges
254
328
  };
255
329
  }
256
330
  }
257
331
  }
258
- if (_version > latestVersion) {
259
- 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');
260
334
  }
261
335
  }
262
- throw fail('invalid-clustering', "Invalid clustering: not a clustering from getClustering. (Clusterings from agglomerative-clustering 1.x are no longer read: cluster the image again.)", 'clustering');
336
+ throw notAClustering(clustering);
263
337
  };
264
338
 
265
339
  // Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
266
340
  // image, and quantize maps such an image the same way.
267
- var checkPalette = exports.checkPalette = function checkPalette(palette) {
341
+ exports.readHeader = readHeader;
342
+ const checkPalette = palette => {
268
343
  if (isClustering(palette)) {
269
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');
270
345
  }
@@ -277,19 +352,10 @@ var checkPalette = exports.checkPalette = function checkPalette(palette) {
277
352
  // Typed arrays are bytes already. A plain array is copied into bytes, which would turn an array of [r, g, b] colours
278
353
  // into zeros, strings into numbers and 300 into 44 without a word, so it must hold byte values.
279
354
  if (Array.isArray(palette)) {
280
- var _iterator = _createForOfIteratorHelper(palette),
281
- _step;
282
- try {
283
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
284
- var value = _step.value;
285
- if (!Number.isInteger(value) || value < 0 || value > 255) {
286
- 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');
287
- }
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');
288
358
  }
289
- } catch (err) {
290
- _iterator.e(err);
291
- } finally {
292
- _iterator.f();
293
359
  }
294
360
  }
295
361
  };
@@ -298,32 +364,36 @@ var checkPalette = exports.checkPalette = function checkPalette(palette) {
298
364
  // A structured clone drops the tags (a palette's colour space with them), so palettes and clusterings cross to and from the
299
365
  // worker thread as small markers and become typed arrays again on the other side: `mark` before posting (an argument, a
300
366
  // result, or a property of a result), `revive` after receiving.
301
- var MARK = exports.MARK = '__agglomerativeClustering';
302
- var markOne = function markOne(value) {
367
+ exports.checkPalette = checkPalette;
368
+ const MARK = exports.MARK = '__agglomerativeClustering';
369
+ const markOne = value => {
303
370
  if (isPalette(value)) {
304
- 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
+ };
305
376
  }
306
377
  if (isClustering(value)) {
307
- 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
+ };
308
382
  }
309
383
  return value;
310
384
  };
311
- var mark = exports.mark = function mark(value) {
312
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
385
+ const mark = value => {
386
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
313
387
  return markOne(value);
314
388
  }
315
389
  if (!isOptionsObject(value)) {
316
390
  return value;
317
391
  }
318
- return Object.fromEntries(Object.entries(value).map(function (_ref3) {
319
- var _ref4 = _slicedToArray(_ref3, 2),
320
- key = _ref4[0],
321
- part = _ref4[1];
322
- return [key, markOne(part)];
323
- }));
392
+ return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, markOne(part)]));
324
393
  };
325
- var reviveOne = function reviveOne(value) {
326
- if (!value || _typeof(value) !== 'object' || !value[MARK]) {
394
+ exports.mark = mark;
395
+ const reviveOne = value => {
396
+ if (!value || typeof value !== 'object' || !value[MARK]) {
327
397
  return value;
328
398
  }
329
399
  if (value[MARK] === 'palette') {
@@ -331,8 +401,8 @@ var reviveOne = function reviveOne(value) {
331
401
  }
332
402
  return markClustering(new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.length));
333
403
  };
334
- var revive = exports.revive = function revive(value) {
335
- if (!value || _typeof(value) !== 'object' || ArrayBuffer.isView(value)) {
404
+ const revive = value => {
405
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
336
406
  return value;
337
407
  }
338
408
  if (value[MARK]) {
@@ -341,9 +411,9 @@ var revive = exports.revive = function revive(value) {
341
411
  if (!isOptionsObject(value)) {
342
412
  return value;
343
413
  }
344
- for (var _i = 0, _Object$keys = Object.keys(value); _i < _Object$keys.length; _i++) {
345
- var key = _Object$keys[_i];
414
+ for (const key of Object.keys(value)) {
346
415
  value[key] = reviveOne(value[key]);
347
416
  }
348
417
  return value;
349
- };
418
+ };
419
+ exports.revive = revive;