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