agglomerative-clustering 2.0.0 → 3.0.0-beta.1

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/index.mjs CHANGED
@@ -1,55 +1,336 @@
1
1
  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; } } }; }
2
- 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; } }
3
- 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; }
4
2
  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); }
5
3
  function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (c = i[4] || 3, u = i[5] === e ? i[3] : i[5], i[4] = 3, i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
6
4
  function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine2(e, r, n, t); }
7
5
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
8
6
  function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
7
+ function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
8
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
11
+ function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
12
+ 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; }
9
13
  import createWasmModule from './clustering.js';
14
+ import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, markPalette, markClustering, latestVersion, readHeader, checkPalette } from "./shared.mjs";
15
+
16
+ // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
17
+ export { version, Palette, Clustering } from "./shared.mjs";
18
+ // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
19
+ // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
20
+ export var formatVersion = latestVersion;
10
21
  var codes = {
11
22
  'rgba': 0,
12
23
  'rgb': 1
13
24
  };
14
- var colorSpaces = {
15
- 'rgb': 0,
16
- 'oklab': 1
17
- };
18
25
  var alphaModes = {
19
26
  'ignore': 0,
20
27
  'weight': 1
21
28
  };
22
29
  var Module = null;
23
- export var init = /*#__PURE__*/function () {
24
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
25
- return _regenerator().w(function (_context) {
26
- while (1) switch (_context.n) {
30
+
31
+ // Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
32
+ // itself by default (`new URL('clustering.wasm', import.meta.url)`); this lets a caller say where it is, or hand over
33
+ // the bytes or an already compiled module, for CDNs, strict CSPs and runtimes (such as Cloudflare Workers) that
34
+ // cannot fetch or compile it that way. `onError` receives instantiation errors, which the glue would otherwise swallow.
35
+ var wasmSettings = function wasmSettings(wasm, onError) {
36
+ if (wasm === undefined) {
37
+ return {};
38
+ }
39
+ if (typeof wasm === 'string' || wasm instanceof URL) {
40
+ var location = String(wasm);
41
+ return {
42
+ locateFile: function locateFile(path, directory) {
43
+ return path.endsWith('.wasm') ? location : directory + path;
44
+ }
45
+ };
46
+ }
47
+ // Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting.
48
+ if (isArrayBufferLike(wasm) || ArrayBuffer.isView(wasm)) {
49
+ var source = isArrayBufferLike(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
50
+ return {
51
+ instantiateWasm: function instantiateWasm(imports, receive) {
52
+ WebAssembly.instantiate(source, imports).then(function (_ref) {
53
+ var instance = _ref.instance;
54
+ return receive(instance);
55
+ }, onError);
56
+ }
57
+ };
58
+ }
59
+ if (typeof WebAssembly !== 'undefined' && wasm instanceof WebAssembly.Module) {
60
+ return {
61
+ instantiateWasm: function instantiateWasm(imports, receive) {
62
+ WebAssembly.instantiate(wasm, imports).then(receive, onError);
63
+ }
64
+ };
65
+ }
66
+ throw fail('invalid-argument', "Invalid wasm: must be a URL or path string, a URL, an ArrayBuffer or typed array of the .wasm bytes, or a WebAssembly.Module.", 'options.wasm');
67
+ };
68
+
69
+ // A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
70
+ // browser without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch) says little about which.
71
+ var wasmLoadFailed = function wasmLoadFailed(cause) {
72
+ return Object.assign(fail('wasm-load-failed', "Could not load the WebAssembly module (".concat(String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0].slice(0, 140), "). It needs WebAssembly with SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4 or newer). If the file is missing or blocked, check that the .wasm is served and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).")), {
73
+ cause: cause
74
+ });
75
+ };
76
+
77
+ // The .wasm and the script that drives it are built together, and the byte layouts and entry points between them are
78
+ // not a public interface. One left over from another version (a stale cache, a CDN serving an old file, an `init({ wasm })`
79
+ // pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
80
+ // mismatch is reported when it loads.
81
+ var checkWasmVersion = function checkWasmVersion(instance) {
82
+ var found = 'an unknown version (from before 3.0)';
83
+ if (typeof instance._library_version === 'function') {
84
+ var heap = instance.HEAPU8;
85
+ var end = instance._library_version();
86
+ var start = end;
87
+ while (heap[end] !== 0 && end - start < 64) {
88
+ end++;
89
+ }
90
+ found = String.fromCharCode.apply(String, _toConsumableArray(heap.subarray(start, end)));
91
+ }
92
+ var expected = "agglomerative-clustering@".concat(version);
93
+ if (found !== expected) {
94
+ throw fail('wasm-load-failed', "The WebAssembly module is ".concat(found, ", but this script is ").concat(expected, ": a stale or mixed-up clustering.wasm (a cache or CDN serving another version, or init({ wasm }) pointing at one). Serve the .wasm that came with this version of the package."));
95
+ }
96
+ };
97
+
98
+ // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
99
+ var loading = null;
100
+
101
+ // Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
102
+ // never changes the module under a call already in flight.
103
+ var acquire = /*#__PURE__*/function () {
104
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(options) {
105
+ var _i, _Object$keys, key, reject, failed, settings;
106
+ return _regenerator().w(function (_context2) {
107
+ while (1) switch (_context2.n) {
27
108
  case 0:
28
- if (Module) {
29
- _context.n = 2;
109
+ if (options === undefined) {
110
+ options = {};
111
+ }
112
+ if (isOptionsObject(options)) {
113
+ _context2.n = 1;
30
114
  break;
31
115
  }
32
- _context.n = 1;
33
- return createWasmModule();
116
+ throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
34
117
  case 1:
35
- Module = _context.v;
118
+ options = snapshot(options);
119
+ _i = 0, _Object$keys = Object.keys(options);
36
120
  case 2:
37
- return _context.a(2);
121
+ if (!(_i < _Object$keys.length)) {
122
+ _context2.n = 4;
123
+ break;
124
+ }
125
+ key = _Object$keys[_i];
126
+ if (!(key !== 'wasm')) {
127
+ _context2.n = 3;
128
+ break;
129
+ }
130
+ throw fail('invalid-argument', "Invalid option '".concat(key, "': expected wasm."), "options.".concat(key));
131
+ case 3:
132
+ _i++;
133
+ _context2.n = 2;
134
+ break;
135
+ case 4:
136
+ failed = new Promise(function (_, r) {
137
+ reject = r;
138
+ });
139
+ failed["catch"](function () {});
140
+ settings = wasmSettings(options.wasm, reject);
141
+ if (!Module) {
142
+ _context2.n = 5;
143
+ break;
144
+ }
145
+ return _context2.a(2, Module);
146
+ case 5:
147
+ if (!loading) {
148
+ loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
149
+ var instance;
150
+ return _regenerator().w(function (_context) {
151
+ while (1) switch (_context.n) {
152
+ case 0:
153
+ _context.n = 1;
154
+ return Promise.race([createWasmModule(settings), failed])["catch"](function (error) {
155
+ throw wasmLoadFailed(error);
156
+ });
157
+ case 1:
158
+ instance = _context.v;
159
+ checkWasmVersion(instance);
160
+ Module = instance;
161
+ return _context.a(2, instance);
162
+ }
163
+ }, _callee);
164
+ }))()["catch"](function (error) {
165
+ loading = null;
166
+ throw error;
167
+ });
168
+ }
169
+ return _context2.a(2, loading);
170
+ }
171
+ }, _callee2);
172
+ }));
173
+ return function acquire(_x) {
174
+ return _ref2.apply(this, arguments);
175
+ };
176
+ }();
177
+
178
+ // Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, except to
179
+ // say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
180
+ // later calls, with or without options, get the same module.
181
+ export var init = /*#__PURE__*/function () {
182
+ var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(options) {
183
+ return _regenerator().w(function (_context3) {
184
+ while (1) switch (_context3.n) {
185
+ case 0:
186
+ _context3.n = 1;
187
+ return acquire(options);
188
+ case 1:
189
+ return _context3.a(2);
38
190
  }
39
- }, _callee);
191
+ }, _callee3);
40
192
  }));
41
- return function init() {
42
- return _ref.apply(this, arguments);
193
+ return function init(_x2) {
194
+ return _ref4.apply(this, arguments);
43
195
  };
44
196
  }();
45
- var unpack = function unpack(pointer) {
46
- var lengthBuffer = new Uint8Array(Module.HEAPU8.subarray(pointer, pointer + 4));
197
+
198
+ // A WebAssembly abort, which is what running out of memory looks like, leaves the instance's heap full of whatever the
199
+ // failed call had allocated and never freed (the abort skips destructors), so every later large call on it would fail
200
+ // too. The instance is therefore discarded: the next call loads a fresh one, and calls already running keep theirs.
201
+ var isAbort = function isAbort(error) {
202
+ return error instanceof Error && error.name === 'RuntimeError' && /^Aborted\(/.test(error.message);
203
+ };
204
+ var discard = function discard(instance) {
205
+ if (Module === instance) {
206
+ Module = null;
207
+ loading = null;
208
+ }
209
+ };
210
+ var outOfMemory = function outOfMemory() {
211
+ return fail('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
212
+ };
213
+ var unpack = function unpack(wasm, pointer) {
214
+ var lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
47
215
  var length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
48
- var outputBuffer = new Uint8Array(Module.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
216
+ var outputBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
49
217
  return outputBuffer;
50
218
  };
219
+
220
+ // A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
221
+ var bytes = function bytes(data) {
222
+ return isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
223
+ };
224
+
225
+ // ----- Encoded image files -------------------------------------------------------------------------------------------
226
+ // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
227
+ // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
228
+ // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
229
+ // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
230
+ // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
231
+ //
232
+ // This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
233
+ // sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
234
+ // { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
235
+ var ascii = function ascii(bytes, at, text) {
236
+ for (var i = 0; i < text.length; i++) {
237
+ if (bytes[at + i] !== text.charCodeAt(i)) {
238
+ return false;
239
+ }
240
+ }
241
+ return true;
242
+ };
243
+
244
+ // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
245
+ // beyond the first few bytes, that raw pixels all but never match.
246
+ var sniffImageFormat = function sniffImageFormat(bytes) {
247
+ var length = bytes.length;
248
+ if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
249
+ return 'PNG';
250
+ }
251
+ // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
252
+ if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
253
+ return 'JPEG';
254
+ }
255
+ if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
256
+ return 'GIF';
257
+ }
258
+ if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
259
+ return 'WebP';
260
+ }
261
+ // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
262
+ if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
263
+ return 'BMP';
264
+ }
265
+ // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
266
+ if (length >= 12) {
267
+ var little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
268
+ var big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
269
+ if (little || big) {
270
+ var u16 = function u16(at) {
271
+ return little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
272
+ };
273
+ var offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
274
+ if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
275
+ return 'TIFF';
276
+ }
277
+ }
278
+ }
279
+ // ISO base media: a 'ftyp' box, then a brand
280
+ if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
281
+ if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
282
+ return 'AVIF';
283
+ }
284
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(function (brand) {
285
+ return ascii(bytes, 8, brand);
286
+ })) {
287
+ return 'HEIC';
288
+ }
289
+ }
290
+ return null;
291
+ };
292
+
293
+ // 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.
294
+ var imageHint = function imageHint(image) {
295
+ var decode = " Decode it to pixels first, then pass them.";
296
+ if (image === undefined || image === null) {
297
+ return " Got ".concat(image, ".");
298
+ }
299
+ if (typeof image === 'string') {
300
+ return " Got a string (a file name, URL or data URL?): load and decode it to pixels first.";
301
+ }
302
+ if (_typeof(image) !== 'object') {
303
+ return " Got a ".concat(_typeof(image), ".");
304
+ }
305
+ if (Array.isArray(image)) {
306
+ return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
307
+ }
308
+ if (isArrayBufferLike(image)) {
309
+ 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).";
310
+ }
311
+ if (typeof image.getContext === 'function') {
312
+ return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
313
+ }
314
+ if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
315
+ return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
316
+ }
317
+ if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
318
+ return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
319
+ }
320
+ if (image.data && !image.format) {
321
+ return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
322
+ }
323
+ return '';
324
+ };
51
325
  var load = function load(image) {
52
- if (image instanceof Uint8Array) {
326
+ if (isUint8Array(image)) {
327
+ var encoded = sniffImageFormat(image);
328
+ if (encoded) {
329
+ throw fail('invalid-argument', "Invalid image: these bytes are an encoded ".concat(encoded, " file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so."), 'image');
330
+ }
331
+ if (image.length % 4 !== 0) {
332
+ throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
333
+ }
53
334
  return {
54
335
  data: image,
55
336
  format: 'rgba'
@@ -57,35 +338,59 @@ var load = function load(image) {
57
338
  }
58
339
  if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
59
340
  return {
60
- data: new Uint8Array(image.data.buffer),
341
+ data: bytes(image.data),
61
342
  format: 'rgba',
62
343
  width: image.width
63
344
  };
64
345
  }
346
+ if (ArrayBuffer.isView(image)) {
347
+ throw fail('invalid-argument', "Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.", 'image');
348
+ }
65
349
  if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
66
- throw new Error("Invalid image: expected object with `data` and `format`.");
350
+ throw fail('invalid-argument', "Invalid image: expected object with `data` and `format`.".concat(imageHint(image)), 'image');
67
351
  }
68
- if (!(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray)) {
69
- throw new Error("Invalid image data: must be Uint8Array or Uint8ClampedArray.");
352
+ if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
353
+ throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
70
354
  }
71
355
  if (!Object.keys(codes).includes(image.format)) {
72
- throw new Error("Invalid format: must be 'rgb' or 'rgba'.");
356
+ throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
357
+ }
358
+ var channels = image.format === 'rgb' ? 3 : 4;
359
+ if (image.data.length % channels !== 0) {
360
+ throw fail('invalid-argument', "Invalid image data: length must be a multiple of ".concat(channels, " for '").concat(image.format, "'."), 'image');
361
+ }
362
+
363
+ // width and height are copied to results and used for dithering, so they must make sense: whole numbers that, when
364
+ // both are given, account for exactly the pixels in the data.
365
+ for (var _i2 = 0, _arr = ['width', 'height']; _i2 < _arr.length; _i2++) {
366
+ var key = _arr[_i2];
367
+ var value = image[key];
368
+ if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
369
+ throw fail('invalid-argument', "Invalid image ".concat(key, ": must be a whole number of pixels."), 'image');
370
+ }
371
+ }
372
+ if (image.width !== undefined && image.height !== undefined && image.width * image.height !== image.data.length / channels) {
373
+ throw fail('invalid-argument', "Invalid image: width x height (".concat(image.width, " x ").concat(image.height, ") does not match its ").concat(image.data.length / channels, " pixels."), 'image');
73
374
  }
74
375
  return {
75
- data: image.data instanceof Uint8ClampedArray ? new Uint8Array(image.data.buffer) : image.data,
376
+ data: bytes(image.data),
76
377
  format: image.format,
77
378
  width: image.width
78
379
  };
79
380
  };
80
381
  var getWrapper = function getWrapper(image) {
81
382
  if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
383
+ // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
82
384
  var width = image.width,
83
- height = image.height;
385
+ height = image.height,
386
+ colorSpace = image.colorSpace;
84
387
  return function (output) {
85
- return new ImageData(new Uint8ClampedArray(output.buffer), width, height);
388
+ return new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
389
+ colorSpace: colorSpace
390
+ } : undefined);
86
391
  };
87
392
  }
88
- if (!(image instanceof Uint8Array) && _typeof(image) === 'object' && image && image.data && image.format) {
393
+ if (!isUint8Array(image) && _typeof(image) === 'object' && image && image.data && image.format) {
89
394
  var format = image.format,
90
395
  _width = image.width,
91
396
  _height = image.height;
@@ -107,10 +412,48 @@ var getWrapper = function getWrapper(image) {
107
412
  return output;
108
413
  };
109
414
  };
415
+
416
+ // Decodes _quantize_indices output: [entries, transparent index, index bytes] as 32-bit little-endian values, then
417
+ // the palette, then the indices. `image` is the caller's original input, for its width and height.
418
+ var unpackIndices = function unpackIndices(output, image, colorSpace) {
419
+ var view = new DataView(output.buffer, output.byteOffset, output.byteLength);
420
+ var entries = view.getUint32(0, true);
421
+ var transparent = view.getInt32(4, true);
422
+ var indexBytes = view.getUint32(8, true);
423
+ var palette = markPalette(output.slice(12, 12 + 3 * entries), colorSpace);
424
+ var start = 12 + 3 * entries;
425
+ var count = (output.length - start) / indexBytes;
426
+ var Indices = indexBytes === 1 ? Uint8Array : indexBytes === 2 ? Uint16Array : Uint32Array;
427
+ var indices = new Indices(count);
428
+ // Little-endian, like the WASM heap, which Emscripten's own typed-array views already assume of the host.
429
+ new Uint8Array(indices.buffer).set(output.subarray(start));
430
+ // `colors` is the palette without the transparent entry, ready to map with again (the entry is black and takes no part in matching)
431
+ var colors = transparent < 0 ? palette : markPalette(palette.slice(0, 3 * transparent), colorSpace);
432
+ var result = {
433
+ palette: palette,
434
+ colors: colors,
435
+ indices: indices,
436
+ indexBits: 8 * indexBytes,
437
+ transparentIndex: transparent < 0 ? null : transparent
438
+ };
439
+ if (!isUint8Array(image)) {
440
+ if (image.width !== undefined) {
441
+ result.width = image.width;
442
+ }
443
+ if (image.height !== undefined) {
444
+ result.height = image.height;
445
+ }
446
+ }
447
+ return result;
448
+ };
449
+
450
+ // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
451
+ // the WASM side holds (a larger one would overflow its int).
110
452
  var check = function check(k) {
111
453
  if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
112
- throw new Error("Invalid k: must be a strictly positive integer.");
454
+ throw fail('invalid-argument', "Invalid k: must be a strictly positive integer.", 'k');
113
455
  }
456
+ return Math.min(k, 0x7FFFFFFF);
114
457
  };
115
458
 
116
459
  // Validates `options` against the keys a function accepts and fills in defaults:
@@ -120,88 +463,121 @@ var check = function check(k) {
120
463
  // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
121
464
  // dither: false (default), true, or a strength in [0, 1]; error diffusion when mapping pixels
122
465
  // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
466
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices (see clusterInSlices)
467
+ // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
468
+ // indexed output also gives them their own entry, which counts towards k
469
+
123
470
  var parseOptions = function parseOptions(options, allowed, image) {
124
471
  if (options === undefined) {
125
472
  options = {};
126
473
  }
127
- if (options === null || _typeof(options) !== 'object' || Array.isArray(options)) {
128
- throw new Error("Invalid options: expected an object.");
474
+ if (!isOptionsObject(options)) {
475
+ throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
129
476
  }
130
- for (var _i = 0, _Object$keys = Object.keys(options); _i < _Object$keys.length; _i++) {
131
- var key = _Object$keys[_i];
477
+ options = snapshot(options);
478
+ for (var _i3 = 0, _Object$keys2 = Object.keys(options); _i3 < _Object$keys2.length; _i3++) {
479
+ var key = _Object$keys2[_i3];
132
480
  if (!allowed.includes(key)) {
133
- throw new Error("Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."));
481
+ throw fail('invalid-argument', "Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."), "options.".concat(key));
134
482
  }
135
483
  }
136
484
  var colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
137
485
  if (!Object.keys(colorSpaces).includes(colorSpace)) {
138
- throw new Error("Invalid colorSpace: must be 'rgb' or 'oklab'.");
486
+ throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
139
487
  }
140
488
  var alpha = options.alpha === undefined ? 'weight' : options.alpha;
141
489
  if (!Object.keys(alphaModes).includes(alpha)) {
142
- throw new Error("Invalid alpha: must be 'weight' or 'ignore'.");
490
+ throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
143
491
  }
144
492
  var precision = options.precision === undefined ? 8 : options.precision;
145
493
  if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
146
- throw new Error("Invalid precision: must be an integer from 1 to 8.");
494
+ throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
147
495
  }
148
496
  var dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
149
497
  if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
150
- throw new Error("Invalid dither: must be a boolean or a number from 0 to 1.");
498
+ throw fail('invalid-argument', "Invalid dither: must be a boolean or a number from 0 to 1.", 'options.dither');
499
+ }
500
+
501
+ // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
502
+ // (a wrong row length would dither without an error, as long as it divides the pixel count).
503
+ if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
504
+ throw fail('invalid-argument', "Invalid width: options.width (".concat(options.width, ") does not match the image's width (").concat(image.width, ")."), 'options.width');
151
505
  }
152
506
  var width = options.width !== undefined ? options.width : image ? image.width : undefined;
153
507
  if (dither > 0) {
154
508
  var channels = image.format === 'rgb' ? 3 : 4;
155
509
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
156
- throw new Error("Invalid width: dithering needs the image width, as `options.width` or the image's `width`.");
510
+ throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
157
511
  }
158
512
  if (image.data.length / channels % width !== 0) {
159
- throw new Error("Invalid width: the image's pixel count is not a multiple of it.");
513
+ throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
160
514
  }
161
515
  }
516
+ var signal = options.signal;
517
+ if (signal !== undefined && (signal === null || _typeof(signal) !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
518
+ throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
519
+ }
520
+ var onProgress = options.onProgress;
521
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
522
+ throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
523
+ }
524
+
525
+ // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
526
+ var transparentOption = options.transparent === undefined ? false : options.transparent;
527
+ var transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
528
+ if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
529
+ throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
530
+ }
531
+
532
+ // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
533
+ if (transparent > 0 && options.alpha !== undefined) {
534
+ throw fail('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
535
+ }
162
536
  return {
163
537
  colorSpace: colorSpaces[colorSpace],
164
538
  colorSpaceGiven: options.colorSpace !== undefined,
165
539
  alpha: alphaModes[alpha],
166
540
  precision: precision,
167
541
  dither: dither,
168
- width: dither > 0 ? width : 0
542
+ width: dither > 0 ? width : 0,
543
+ transparent: transparent,
544
+ transparentGiven: options.transparent !== undefined,
545
+ signal: signal,
546
+ onProgress: onProgress
169
547
  };
170
548
  };
171
- var clusterOptions = ['colorSpace', 'precision', 'alpha'];
172
- var quantizeOptions = ['colorSpace', 'precision', 'alpha', 'dither', 'width'];
173
- var mapOptions = ['colorSpace', 'dither', 'width'];
549
+ var controlOptions = ['signal', 'onProgress'];
550
+ var clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent'].concat(controlOptions);
551
+ var quantizeOptions = [].concat(_toConsumableArray(clusterOptions), ['dither', 'width']);
552
+ // The functions that only map pixels take just `signal`: they finish in milliseconds, so there is nothing to report progress
553
+ // on or to interrupt part way; a signal that is already aborted does no work, which is all it can mean.
554
+ var mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
555
+ var quantizeIndexOptions = quantizeOptions;
556
+ var mapIndexOptions = [].concat(mapOptions, ['transparent']);
174
557
 
175
- // Clusterings are 0 or 3 bytes more than a multiple of 9 (1.x, no header), or 4 or 7 more with the 2.x header.
176
- var checkClustering = function checkClustering(clustering) {
177
- if (!(clustering instanceof Uint8Array)) {
178
- throw new Error("Invalid clustering: must be a Uint8Array from getClustering.");
179
- }
180
- var rest = clustering.length % 9;
181
- var legacy = clustering.length === 0 || rest === 3;
182
- var current = (clustering.length === 4 || rest === 7) && clustering[0] === 0xAC && clustering[1] === 2 && clustering[2] <= 1;
183
- if (!legacy && !current) {
184
- throw new Error("Invalid clustering: not a clustering from getClustering.");
185
- }
558
+ // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
559
+ var matchingSpace = function matchingSpace(o, palette) {
560
+ return o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
186
561
  };
187
562
 
188
563
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
189
564
  // freeing everything afterwards.
190
- var call = function call(buffers, fn) {
565
+ var call = function call(wasm, buffers, fn) {
191
566
  var pointers = [];
192
567
  var outputPointer = 0;
568
+ var aborted = false;
193
569
  try {
194
570
  var _iterator = _createForOfIteratorHelper(buffers),
195
571
  _step;
196
572
  try {
197
573
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
198
574
  var buffer = _step.value;
199
- var pointer = Module._malloc(buffer.length);
575
+ var pointer = wasm._malloc(buffer.length);
200
576
  if (!pointer) {
201
- throw new Error("Failed to allocate WASM memory.");
577
+ throw fail('out-of-memory', "Failed to allocate WASM memory.");
202
578
  }
203
579
  pointers.push(pointer);
204
- Module.HEAPU8.set(buffer, pointer);
580
+ wasm.HEAPU8.set(buffer, pointer);
205
581
  }
206
582
  } catch (err) {
207
583
  _iterator.e(err);
@@ -209,147 +585,601 @@ var call = function call(buffers, fn) {
209
585
  _iterator.f();
210
586
  }
211
587
  outputPointer = fn.apply(void 0, pointers);
212
- return unpack(outputPointer);
213
- } finally {
214
- for (var _i2 = 0, _pointers = pointers; _i2 < _pointers.length; _i2++) {
215
- var _pointer = _pointers[_i2];
216
- Module._free(_pointer);
588
+ return unpack(wasm, outputPointer);
589
+ } catch (error) {
590
+ if (!isAbort(error)) {
591
+ throw error;
217
592
  }
218
- if (outputPointer) {
219
- Module._free(outputPointer);
593
+ aborted = true;
594
+ discard(wasm);
595
+ throw outOfMemory();
596
+ } finally {
597
+ // After an abort the instance is being thrown away, and its allocator can't be trusted.
598
+ if (!aborted) {
599
+ var _iterator2 = _createForOfIteratorHelper(pointers),
600
+ _step2;
601
+ try {
602
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
603
+ var _pointer = _step2.value;
604
+ wasm._free(_pointer);
605
+ }
606
+ } catch (err) {
607
+ _iterator2.e(err);
608
+ } finally {
609
+ _iterator2.f();
610
+ }
611
+ if (outputPointer) {
612
+ wasm._free(outputPointer);
613
+ }
220
614
  }
221
615
  }
222
616
  };
617
+
618
+ // ----- Interruptible work -------------------------------------------------------------------------------------------
619
+ // A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
620
+ // event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
621
+ // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
622
+ // result is the same either way: the slices are the same steps in the same order.
623
+
624
+ var sliceMs = 10;
625
+
626
+ // Gives other tasks (a cancel message, timers, painting) a turn.
627
+ var yieldNow = function yieldNow() {
628
+ if (typeof setImmediate === 'function') {
629
+ return new Promise(function (resolve) {
630
+ return setImmediate(resolve);
631
+ });
632
+ }
633
+ if (typeof MessageChannel === 'function') {
634
+ return new Promise(function (resolve) {
635
+ var _MessageChannel = new MessageChannel(),
636
+ port1 = _MessageChannel.port1,
637
+ port2 = _MessageChannel.port2;
638
+ port1.onmessage = function () {
639
+ port1.close();
640
+ port2.close();
641
+ resolve();
642
+ };
643
+ port2.postMessage(null);
644
+ });
645
+ }
646
+ return new Promise(function (resolve) {
647
+ return setTimeout(resolve, 0);
648
+ });
649
+ };
650
+
651
+ // Like fetch, an aborted call rejects with the signal's reason (an AbortError unless the caller gave another).
652
+ var checkAborted = function checkAborted(signal) {
653
+ if (signal && signal.aborted) {
654
+ throw signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
655
+ }
656
+ };
657
+
658
+ // Reports progress as a fraction from 0 to 1, never going backwards and only when it changes.
659
+ var reporter = function reporter(o) {
660
+ var last = -1;
661
+ return function (fraction) {
662
+ var value = Math.min(1, Math.max(0, fraction));
663
+ if (o.onProgress && value > last) {
664
+ last = value;
665
+ o.onProgress(value);
666
+ }
667
+ };
668
+ };
669
+ var isControlled = function isControlled(o) {
670
+ return o.signal !== undefined || o.onProgress !== undefined;
671
+ };
672
+
673
+ // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
674
+ var clusterInSlices = /*#__PURE__*/function () {
675
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(wasm, image, o, report, share) {
676
+ var imagePointer, job, aborted, progress, pointer, _t;
677
+ return _regenerator().w(function (_context4) {
678
+ while (1) switch (_context4.n) {
679
+ case 0:
680
+ checkAborted(o.signal);
681
+ imagePointer = wasm._malloc(image.data.length);
682
+ if (imagePointer) {
683
+ _context4.n = 1;
684
+ break;
685
+ }
686
+ throw fail('out-of-memory', "Failed to allocate WASM memory.");
687
+ case 1:
688
+ job = 0;
689
+ aborted = false;
690
+ _context4.p = 2;
691
+ wasm.HEAPU8.set(image.data, imagePointer);
692
+ job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
693
+ report(0);
694
+ case 3:
695
+ if (!true) {
696
+ _context4.n = 6;
697
+ break;
698
+ }
699
+ progress = wasm._clustering_job_step(job, sliceMs);
700
+ if (!(progress >= 1000)) {
701
+ _context4.n = 4;
702
+ break;
703
+ }
704
+ return _context4.a(3, 6);
705
+ case 4:
706
+ report(share * progress / 1000);
707
+ _context4.n = 5;
708
+ return yieldNow();
709
+ case 5:
710
+ checkAborted(o.signal);
711
+ _context4.n = 3;
712
+ break;
713
+ case 6:
714
+ pointer = wasm._clustering_job_result(job);
715
+ _context4.p = 7;
716
+ return _context4.a(2, unpack(wasm, pointer));
717
+ case 8:
718
+ _context4.p = 8;
719
+ wasm._free(pointer);
720
+ return _context4.f(8);
721
+ case 9:
722
+ _context4.n = 12;
723
+ break;
724
+ case 10:
725
+ _context4.p = 10;
726
+ _t = _context4.v;
727
+ if (isAbort(_t)) {
728
+ _context4.n = 11;
729
+ break;
730
+ }
731
+ throw _t;
732
+ case 11:
733
+ aborted = true;
734
+ discard(wasm);
735
+ throw outOfMemory();
736
+ case 12:
737
+ _context4.p = 12;
738
+ if (!aborted) {
739
+ if (job) {
740
+ wasm._clustering_job_free(job);
741
+ }
742
+ wasm._free(imagePointer);
743
+ }
744
+ return _context4.f(12);
745
+ case 13:
746
+ return _context4.a(2);
747
+ }
748
+ }, _callee4, null, [[7,, 8, 9], [2, 10, 12, 13]]);
749
+ }));
750
+ return function clusterInSlices(_x3, _x4, _x5, _x6, _x7) {
751
+ return _ref5.apply(this, arguments);
752
+ };
753
+ }();
223
754
  export var getClustering = /*#__PURE__*/function () {
224
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image, options) {
225
- var o;
226
- return _regenerator().w(function (_context2) {
227
- while (1) switch (_context2.n) {
755
+ var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, options) {
756
+ var wasm, o, report, clustering;
757
+ return _regenerator().w(function (_context5) {
758
+ while (1) switch (_context5.n) {
228
759
  case 0:
229
- _context2.n = 1;
230
- return init();
760
+ _context5.n = 1;
761
+ return acquire();
231
762
  case 1:
763
+ wasm = _context5.v;
232
764
  image = load(image);
233
765
  o = parseOptions(options, clusterOptions, image);
234
- return _context2.a(2, call([image.data], function (imagePointer) {
235
- return Module._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha);
236
- }));
766
+ if (!isControlled(o)) {
767
+ _context5.n = 3;
768
+ break;
769
+ }
770
+ report = reporter(o);
771
+ _context5.n = 2;
772
+ return clusterInSlices(wasm, image, o, report, 1);
773
+ case 2:
774
+ clustering = _context5.v;
775
+ report(1);
776
+ return _context5.a(2, markClustering(clustering));
777
+ case 3:
778
+ return _context5.a(2, markClustering(call(wasm, [image.data], function (imagePointer) {
779
+ return wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
780
+ })));
237
781
  }
238
- }, _callee2);
782
+ }, _callee5);
239
783
  }));
240
- return function getClustering(_x, _x2) {
241
- return _ref2.apply(this, arguments);
784
+ return function getClustering(_x8, _x9) {
785
+ return _ref6.apply(this, arguments);
242
786
  };
243
787
  }();
244
788
  export var getPalette = /*#__PURE__*/function () {
245
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k, options) {
246
- var o;
247
- return _regenerator().w(function (_context3) {
248
- while (1) switch (_context3.n) {
789
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, k, options) {
790
+ var wasm, o, report, clustering, palette;
791
+ return _regenerator().w(function (_context6) {
792
+ while (1) switch (_context6.n) {
249
793
  case 0:
250
- _context3.n = 1;
251
- return init();
794
+ _context6.n = 1;
795
+ return acquire();
252
796
  case 1:
797
+ wasm = _context6.v;
253
798
  image = load(image);
254
- check(k);
799
+ k = check(k);
255
800
  o = parseOptions(options, clusterOptions, image);
256
- return _context3.a(2, call([image.data], function (imagePointer) {
257
- return Module._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha);
258
- }));
801
+ if (!isControlled(o)) {
802
+ _context6.n = 3;
803
+ break;
804
+ }
805
+ report = reporter(o);
806
+ _context6.n = 2;
807
+ return clusterInSlices(wasm, image, o, report, 0.99);
808
+ case 2:
809
+ clustering = _context6.v;
810
+ checkAborted(o.signal);
811
+ palette = call(wasm, [clustering], function (clusteringPointer) {
812
+ return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
813
+ });
814
+ report(1);
815
+ return _context6.a(2, markPalette(palette, colorSpaceName(o.colorSpace)));
816
+ case 3:
817
+ return _context6.a(2, markPalette(call(wasm, [image.data], function (imagePointer) {
818
+ return wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent);
819
+ }), colorSpaceName(o.colorSpace)));
259
820
  }
260
- }, _callee3);
821
+ }, _callee6);
261
822
  }));
262
- return function getPalette(_x3, _x4, _x5) {
263
- return _ref3.apply(this, arguments);
823
+ return function getPalette(_x0, _x1, _x10) {
824
+ return _ref7.apply(this, arguments);
264
825
  };
265
826
  }();
266
827
  export var getPaletteFromClustering = /*#__PURE__*/function () {
267
- var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(clustering, k) {
268
- return _regenerator().w(function (_context4) {
269
- while (1) switch (_context4.n) {
828
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(clustering, k) {
829
+ var wasm, header;
830
+ return _regenerator().w(function (_context7) {
831
+ while (1) switch (_context7.n) {
270
832
  case 0:
271
- _context4.n = 1;
272
- return init();
833
+ _context7.n = 1;
834
+ return acquire();
273
835
  case 1:
274
- checkClustering(clustering);
275
- check(k);
276
- return _context4.a(2, call([clustering], function (clusteringPointer) {
277
- return Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
278
- }));
836
+ wasm = _context7.v;
837
+ header = readHeader(clustering);
838
+ k = check(k);
839
+ return _context7.a(2, markPalette(call(wasm, [clustering], function (clusteringPointer) {
840
+ return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
841
+ }), colorSpaceName(header.colorSpace)));
279
842
  }
280
- }, _callee4);
843
+ }, _callee7);
281
844
  }));
282
- return function getPaletteFromClustering(_x6, _x7) {
283
- return _ref4.apply(this, arguments);
845
+ return function getPaletteFromClustering(_x11, _x12) {
846
+ return _ref8.apply(this, arguments);
847
+ };
848
+ }();
849
+
850
+ // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
851
+ var weightsOf = function weightsOf(wasm, clustering, header, k) {
852
+ var bytes = call(wasm, [clustering], function (clusteringPointer) {
853
+ return wasm._get_palette_weights(clusteringPointer, clustering.length, k);
854
+ });
855
+ if (header.merges > 0 && bytes.length === 0) {
856
+ throw fail('invalid-clustering', "Invalid clustering: its weights are inconsistent.", 'clustering');
857
+ }
858
+ return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
859
+ };
860
+
861
+ // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
862
+ // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
863
+ // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
864
+ export var getSwatchesFromClustering = /*#__PURE__*/function () {
865
+ var _ref9 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(clustering, k) {
866
+ var wasm, header, palette, weights, total, _iterator3, _step3, weight, shares, i;
867
+ return _regenerator().w(function (_context8) {
868
+ while (1) switch (_context8.n) {
869
+ case 0:
870
+ _context8.n = 1;
871
+ return acquire();
872
+ case 1:
873
+ wasm = _context8.v;
874
+ header = readHeader(clustering);
875
+ k = check(k);
876
+ if (!(header.version < 3)) {
877
+ _context8.n = 2;
878
+ break;
879
+ }
880
+ throw fail('unsupported-version', "Invalid clustering: format version ".concat(header.version, " (agglomerative-clustering ").concat(header.version, ".x) has no weights. Cluster the image again."), 'clustering');
881
+ case 2:
882
+ palette = markPalette(call(wasm, [clustering], function (clusteringPointer) {
883
+ return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
884
+ }), colorSpaceName(header.colorSpace));
885
+ weights = weightsOf(wasm, clustering, header, k);
886
+ total = 0;
887
+ _iterator3 = _createForOfIteratorHelper(weights);
888
+ try {
889
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
890
+ weight = _step3.value;
891
+ total += weight;
892
+ }
893
+ } catch (err) {
894
+ _iterator3.e(err);
895
+ } finally {
896
+ _iterator3.f();
897
+ }
898
+ shares = new Float64Array(weights.length);
899
+ if (total > 0) {
900
+ for (i = 0; i < weights.length; i++) {
901
+ shares[i] = weights[i] / total;
902
+ }
903
+ }
904
+ return _context8.a(2, {
905
+ palette: palette,
906
+ weights: weights,
907
+ shares: shares
908
+ });
909
+ }
910
+ }, _callee8);
911
+ }));
912
+ return function getSwatchesFromClustering(_x13, _x14) {
913
+ return _ref9.apply(this, arguments);
914
+ };
915
+ }();
916
+
917
+ // The same for an image: clusters it, then cuts, like getPalette.
918
+ export var getSwatches = /*#__PURE__*/function () {
919
+ var _ref0 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(image, k, options) {
920
+ var _t2, _t3, _t4;
921
+ return _regenerator().w(function (_context9) {
922
+ while (1) switch (_context9.n) {
923
+ case 0:
924
+ // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
925
+ load(image);
926
+ k = check(k);
927
+ _t2 = getSwatchesFromClustering;
928
+ _context9.n = 1;
929
+ return getClustering(image, options);
930
+ case 1:
931
+ _t3 = _context9.v;
932
+ _t4 = k;
933
+ return _context9.a(2, _t2(_t3, _t4));
934
+ }
935
+ }, _callee9);
936
+ }));
937
+ return function getSwatches(_x15, _x16, _x17) {
938
+ return _ref0.apply(this, arguments);
939
+ };
940
+ }();
941
+
942
+ // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
943
+ // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
944
+ // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
945
+ export var getClusteringInfo = /*#__PURE__*/function () {
946
+ var _ref1 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(clustering) {
947
+ var header, colors, info, view, pixels, total, remaining, i, _i4;
948
+ return _regenerator().w(function (_context0) {
949
+ while (1) switch (_context0.n) {
950
+ case 0:
951
+ header = readHeader(clustering);
952
+ colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
953
+ info = {
954
+ formatVersion: header.version,
955
+ colorSpace: colorSpaceName(header.colorSpace),
956
+ precision: header.precision,
957
+ transparent: header.transparent === 0 ? false : header.transparent,
958
+ maxColors: colors,
959
+ totalWeight: null,
960
+ mse: null,
961
+ explained: null
962
+ };
963
+ if (!(header.version < 3)) {
964
+ _context0.n = 1;
965
+ break;
966
+ }
967
+ return _context0.a(2, info);
968
+ case 1:
969
+ view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
970
+ pixels = Math.pow(2, clustering[7]) / (clustering[6] === 1 ? 255 : 1);
971
+ total = view.getUint32(8, true);
972
+ info.totalWeight = total * pixels;
973
+ info.mse = new Float64Array(colors);
974
+ info.explained = new Float64Array(colors);
975
+ // The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
976
+ remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
977
+ if (colors > 0) {
978
+ info.mse[colors - 1] = remaining / total / 3;
979
+ }
980
+ for (i = header.merges - 1; i >= 0; i--) {
981
+ remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
982
+ info.mse[i] = remaining / total / 3;
983
+ }
984
+ // The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
985
+ for (_i4 = 0; _i4 < colors; _i4++) {
986
+ info.explained[_i4] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[_i4] / info.mse[0])) : 1;
987
+ }
988
+ return _context0.a(2, info);
989
+ }
990
+ }, _callee0);
991
+ }));
992
+ return function getClusteringInfo(_x18) {
993
+ return _ref1.apply(this, arguments);
284
994
  };
285
995
  }();
286
996
  export var quantize = /*#__PURE__*/function () {
287
- var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k, options) {
288
- var wrap, o;
289
- return _regenerator().w(function (_context5) {
290
- while (1) switch (_context5.n) {
997
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(image, k, options) {
998
+ var wasm, wrap, o, report, clustering, mapped;
999
+ return _regenerator().w(function (_context1) {
1000
+ while (1) switch (_context1.n) {
291
1001
  case 0:
292
- _context5.n = 1;
293
- return init();
1002
+ _context1.n = 1;
1003
+ return acquire();
294
1004
  case 1:
1005
+ wasm = _context1.v;
295
1006
  wrap = getWrapper(image);
296
1007
  image = load(image);
297
- check(k);
1008
+ k = check(k);
298
1009
  o = parseOptions(options, quantizeOptions, image);
299
- return _context5.a(2, wrap(call([image.data], function (imagePointer) {
300
- return Module._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width);
1010
+ if (!isControlled(o)) {
1011
+ _context1.n = 3;
1012
+ break;
1013
+ }
1014
+ report = reporter(o);
1015
+ _context1.n = 2;
1016
+ return clusterInSlices(wasm, image, o, report, 0.9);
1017
+ case 2:
1018
+ clustering = _context1.v;
1019
+ checkAborted(o.signal);
1020
+ mapped = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1021
+ return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width);
1022
+ }));
1023
+ report(1);
1024
+ return _context1.a(2, mapped);
1025
+ case 3:
1026
+ return _context1.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
1027
+ return wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
301
1028
  })));
302
1029
  }
303
- }, _callee5);
1030
+ }, _callee1);
304
1031
  }));
305
- return function quantize(_x8, _x9, _x0) {
306
- return _ref5.apply(this, arguments);
1032
+ return function quantize(_x19, _x20, _x21) {
1033
+ return _ref10.apply(this, arguments);
307
1034
  };
308
1035
  }();
309
- export var quantizeWithClustering = /*#__PURE__*/function () {
310
- var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k, options) {
311
- var wrap, o, colorSpace;
312
- return _regenerator().w(function (_context6) {
313
- while (1) switch (_context6.n) {
1036
+ export var quantizeFromClustering = /*#__PURE__*/function () {
1037
+ var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, clustering, k, options) {
1038
+ var wasm, wrap, o, colorSpace, result;
1039
+ return _regenerator().w(function (_context10) {
1040
+ while (1) switch (_context10.n) {
314
1041
  case 0:
315
- _context6.n = 1;
316
- return init();
1042
+ _context10.n = 1;
1043
+ return acquire();
317
1044
  case 1:
1045
+ wasm = _context10.v;
318
1046
  wrap = getWrapper(image);
319
1047
  image = load(image);
320
- checkClustering(clustering);
321
- check(k);
1048
+ readHeader(clustering);
1049
+ k = check(k);
322
1050
  o = parseOptions(options, mapOptions, image);
1051
+ checkAborted(o.signal);
323
1052
  colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
324
- return _context6.a(2, wrap(call([image.data, clustering], function (imagePointer, clusteringPointer) {
325
- return Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
326
- })));
1053
+ result = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1054
+ return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
1055
+ }));
1056
+ return _context10.a(2, result);
327
1057
  }
328
- }, _callee6);
1058
+ }, _callee10);
329
1059
  }));
330
- return function quantizeWithClustering(_x1, _x10, _x11, _x12) {
331
- return _ref6.apply(this, arguments);
1060
+ return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
1061
+ return _ref11.apply(this, arguments);
332
1062
  };
333
1063
  }();
334
1064
  export var quantizeWithPalette = /*#__PURE__*/function () {
335
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette, options) {
336
- var wrap, o;
337
- return _regenerator().w(function (_context7) {
338
- while (1) switch (_context7.n) {
1065
+ var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, palette, options) {
1066
+ var wasm, wrap, o, result;
1067
+ return _regenerator().w(function (_context11) {
1068
+ while (1) switch (_context11.n) {
339
1069
  case 0:
340
- _context7.n = 1;
341
- return init();
1070
+ _context11.n = 1;
1071
+ return acquire();
342
1072
  case 1:
1073
+ wasm = _context11.v;
343
1074
  wrap = getWrapper(image);
344
1075
  image = load(image);
1076
+ checkPalette(palette);
345
1077
  o = parseOptions(options, mapOptions, image);
346
- return _context7.a(2, wrap(call([image.data, palette], function (imagePointer, palettePointer) {
347
- return Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, o.colorSpace, o.dither, o.width);
348
- })));
1078
+ checkAborted(o.signal);
1079
+ result = wrap(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1080
+ return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, matchingSpace(o, palette), o.dither, o.width);
1081
+ }));
1082
+ return _context11.a(2, result);
349
1083
  }
350
- }, _callee7);
1084
+ }, _callee11);
351
1085
  }));
352
- return function quantizeWithPalette(_x13, _x14, _x15) {
353
- return _ref7.apply(this, arguments);
1086
+ return function quantizeWithPalette(_x26, _x27, _x28) {
1087
+ return _ref12.apply(this, arguments);
1088
+ };
1089
+ }();
1090
+ export var quantizeToIndices = /*#__PURE__*/function () {
1091
+ var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, k, options) {
1092
+ var wasm, original, o, report, clustering, indexed;
1093
+ return _regenerator().w(function (_context12) {
1094
+ while (1) switch (_context12.n) {
1095
+ case 0:
1096
+ _context12.n = 1;
1097
+ return acquire();
1098
+ case 1:
1099
+ wasm = _context12.v;
1100
+ original = image;
1101
+ image = load(image);
1102
+ k = check(k);
1103
+ o = parseOptions(options, quantizeIndexOptions, image);
1104
+ if (!isControlled(o)) {
1105
+ _context12.n = 3;
1106
+ break;
1107
+ }
1108
+ report = reporter(o);
1109
+ _context12.n = 2;
1110
+ return clusterInSlices(wasm, image, o, report, 0.9);
1111
+ case 2:
1112
+ clustering = _context12.v;
1113
+ checkAborted(o.signal);
1114
+ indexed = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1115
+ return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width, o.transparent);
1116
+ }), original, colorSpaceName(o.colorSpace));
1117
+ report(1);
1118
+ return _context12.a(2, indexed);
1119
+ case 3:
1120
+ return _context12.a(2, unpackIndices(call(wasm, [image.data], function (imagePointer) {
1121
+ return wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
1122
+ }), original, colorSpaceName(o.colorSpace)));
1123
+ }
1124
+ }, _callee12);
1125
+ }));
1126
+ return function quantizeToIndices(_x29, _x30, _x31) {
1127
+ return _ref13.apply(this, arguments);
1128
+ };
1129
+ }();
1130
+ export var quantizeToIndicesFromClustering = /*#__PURE__*/function () {
1131
+ var _ref14 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(image, clustering, k, options) {
1132
+ var wasm, original, header, o, colorSpace, cutoff, result;
1133
+ return _regenerator().w(function (_context13) {
1134
+ while (1) switch (_context13.n) {
1135
+ case 0:
1136
+ _context13.n = 1;
1137
+ return acquire();
1138
+ case 1:
1139
+ wasm = _context13.v;
1140
+ original = image;
1141
+ image = load(image);
1142
+ header = readHeader(clustering);
1143
+ k = check(k);
1144
+ o = parseOptions(options, mapIndexOptions, image);
1145
+ checkAborted(o.signal);
1146
+ colorSpace = o.colorSpaceGiven ? o.colorSpace : -1; // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1147
+ cutoff = o.transparentGiven ? o.transparent : header.transparent;
1148
+ result = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1149
+ return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width, cutoff);
1150
+ }), original, colorSpaceName(header.colorSpace));
1151
+ return _context13.a(2, result);
1152
+ }
1153
+ }, _callee13);
1154
+ }));
1155
+ return function quantizeToIndicesFromClustering(_x32, _x33, _x34, _x35) {
1156
+ return _ref14.apply(this, arguments);
1157
+ };
1158
+ }();
1159
+ export var quantizeToIndicesWithPalette = /*#__PURE__*/function () {
1160
+ var _ref15 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(image, palette, options) {
1161
+ var wasm, original, o, space, result;
1162
+ return _regenerator().w(function (_context14) {
1163
+ while (1) switch (_context14.n) {
1164
+ case 0:
1165
+ _context14.n = 1;
1166
+ return acquire();
1167
+ case 1:
1168
+ wasm = _context14.v;
1169
+ original = image;
1170
+ image = load(image);
1171
+ checkPalette(palette);
1172
+ o = parseOptions(options, mapIndexOptions, image);
1173
+ checkAborted(o.signal);
1174
+ space = matchingSpace(o, palette);
1175
+ result = unpackIndices(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1176
+ return wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width, o.transparent);
1177
+ }), original, isPalette(palette) ? palette.colorSpace : colorSpaceName(space));
1178
+ return _context14.a(2, result);
1179
+ }
1180
+ }, _callee14);
1181
+ }));
1182
+ return function quantizeToIndicesWithPalette(_x36, _x37, _x38) {
1183
+ return _ref15.apply(this, arguments);
354
1184
  };
355
1185
  }();