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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.mjs CHANGED
@@ -1,114 +1,176 @@
1
- var _excluded = ["signal", "onProgress"];
2
- 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; } } }; }
3
- function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
4
- 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."); }
5
- 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; } }
6
- function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
7
- function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
8
- 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
- function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
10
- function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
11
- 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); }
12
- 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 }; })(); }
13
- 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); }
14
- 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); }
15
- 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); }); }; }
16
1
  // The `agglomerative-clustering/worker` entry: the same API, run in a Web Worker (browsers) or a worker thread
17
2
  // (Node), so clustering doesn't block the calling thread. `createWorker()` starts a worker with every function of
18
3
  // the main entry as a method, plus `cluster`, which keeps an image and its clustering in the worker behind a
19
4
  // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
20
5
  // worker, started on first use.
21
6
 
22
- import { fail, isOptionsObject, snapshot, mark, revive, latestVersion } from "./shared.mjs";
7
+ import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint } from "./shared.mjs";
23
8
 
24
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
25
10
  export { version, Palette, Clustering } from "./shared.mjs";
26
- export var formatVersion = latestVersion;
27
- var isNode = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && typeof window === 'undefined';
11
+ export const formatVersion = latestVersion;
12
+
13
+ // Node's worker_threads, where this script runs from a file in Node, Bun or Deno (from npm). A runtime that only imitates Node
14
+ // (Cloudflare Workers with nodejs_compat, a CDN copy in Deno) defines process.versions.node too, but isn't loaded from a file.
15
+ const isNode = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && typeof window === 'undefined' && typeof import.meta.url === 'string' && import.meta.url.startsWith('file:');
16
+
17
+ // The worker thread's script in Node: the one next to this file, which imports the main entry (index.mjs) next to it. A
18
+ // server bundle (Next.js with webpack or Turbopack) copies the script elsewhere without what it imports, and may hand
19
+ // over its URL as another realm's URL object, which Node's Worker rejects. Then the package's own copy is used, found the
20
+ // way Node resolves packages from the working directory. Built from strings so Node's own URL class makes it.
21
+ const nodeWorkerScript = async () => {
22
+ const load = name => import(/* webpackIgnore: true */ /* @vite-ignore */['node', name].join(':'));
23
+ // The base is a variable so bundlers don't take this Node-only URL for an asset to emit (Vite would copy the script a
24
+ // second time for it): they look for `new URL('…', import.meta.url)` written out, which the browser branch of `start` keeps.
25
+ const here = import.meta.url;
26
+ const file = './worker-thread.mjs';
27
+ let script = null;
28
+ try {
29
+ const made = new URL(file, here);
30
+ script = new URL(typeof made.href === 'string' ? made.href : String(made));
31
+ } catch (error) {/* a URL Node can't read: use the package's copy */}
32
+ try {
33
+ const [{
34
+ existsSync
35
+ }, {
36
+ fileURLToPath,
37
+ pathToFileURL
38
+ }] = await Promise.all([load('fs'), load('url')]);
39
+ if (script && script.protocol === 'file:' && existsSync(fileURLToPath(script)) && existsSync(fileURLToPath(new URL('./index.mjs', script)))) {
40
+ return script;
41
+ }
42
+ const {
43
+ createRequire
44
+ } = await load('module');
45
+ const packaged = new URL('./dist/worker-thread.mjs', pathToFileURL(createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/package.json')));
46
+ if (existsSync(fileURLToPath(packaged))) {
47
+ return packaged;
48
+ }
49
+ } catch (error) {/* not found: start the script as it is, and report what happens */}
50
+ return script || new URL(file, here);
51
+ };
52
+
53
+ // Whether a worker script at `url` is on another origin than the page (or worker) starting it.
54
+ const isCrossOrigin = url => {
55
+ try {
56
+ const here = typeof location !== 'undefined' && location.origin;
57
+ return Boolean(here) && here !== 'null' && (url.protocol === 'http:' || url.protocol === 'https:') && url.origin !== here;
58
+ } catch (error) {
59
+ return false;
60
+ }
61
+ };
28
62
 
29
63
  // Starts the worker and returns {post, terminate, ref, unref}, with messages delivered to `receive`.
30
- var start = /*#__PURE__*/function () {
31
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(receive) {
32
- var _worker, _yield$import, NodeWorker, worker;
33
- return _regenerator().w(function (_context) {
34
- while (1) switch (_context.n) {
35
- case 0:
36
- if (isNode) {
37
- _context.n = 1;
38
- break;
39
- }
40
- // Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
41
- _worker = new Worker(new URL('./worker-thread.mjs', import.meta.url), {
42
- type: 'module'
43
- });
44
- _worker.addEventListener('message', function (event) {
45
- return receive(event.data);
46
- });
47
- _worker.addEventListener('error', function (event) {
48
- return receive({
49
- failure: event.message || 'The worker failed to start.'
50
- });
51
- });
52
- return _context.a(2, {
53
- post: function post(message, transfer) {
54
- return _worker.postMessage(message, transfer);
55
- },
56
- terminate: function terminate() {
57
- return _worker.terminate();
58
- },
59
- ref: function ref() {},
60
- unref: function unref() {}
61
- });
62
- case 1:
63
- _context.n = 2;
64
- return import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
65
- case 2:
66
- _yield$import = _context.v;
67
- NodeWorker = _yield$import.Worker;
68
- // The worker script needs none of the parent's flags, and some (like --input-type) are invalid in a worker.
69
- worker = new NodeWorker(new URL('./worker-thread.mjs', import.meta.url), {
70
- execArgv: []
71
- });
72
- worker.on('message', receive);
73
- worker.on('error', function (error) {
74
- return receive({
75
- failure: error.message
76
- });
77
- });
78
- worker.on('exit', function (code) {
79
- return receive({
80
- failure: "The worker exited unexpectedly (code ".concat(code, ").")
81
- });
82
- });
83
- worker.unref();
84
- return _context.a(2, {
85
- post: function post(message, transfer) {
86
- return worker.postMessage(message, transfer);
87
- },
88
- terminate: function terminate() {
89
- return worker.terminate();
90
- },
91
- ref: function ref() {
92
- return worker.ref();
93
- },
94
- unref: function unref() {
95
- return worker.unref();
96
- }
97
- });
98
- }
99
- }, _callee);
64
+ const start = async receive => {
65
+ if (!isNode) {
66
+ if (typeof Worker !== 'function') {
67
+ throw fail('worker-failed', "Worker failed: this runtime has no Worker (Cloudflare Workers, for one, can't start threads). Use the main entry, 'agglomerative-clustering', instead.");
68
+ }
69
+ // Where the script is when the package is used unbundled (from a CDN, say). The base is a variable so bundlers
70
+ // leave this one alone; they rewrite the literal `new Worker(new URL(...))` below, which must stay written out.
71
+ const here = import.meta.url;
72
+ const script = new URL('./worker-thread.mjs', here);
73
+ const crossOrigin = isCrossOrigin(script);
74
+ let worker,
75
+ source = null;
76
+ if (crossOrigin) {
77
+ // A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
78
+ // module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
79
+ // Content-Security-Policy then needs `worker-src blob:`.
80
+ source = URL.createObjectURL(new Blob([`import ${JSON.stringify(script.href)};`], {
81
+ type: 'text/javascript'
82
+ }));
83
+ worker = new Worker(source, {
84
+ type: 'module'
85
+ });
86
+ setTimeout(() => URL.revokeObjectURL(source), 60000);
87
+ } else {
88
+ // Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
89
+ worker = new Worker(new URL('./worker-thread.mjs', import.meta.url), {
90
+ type: 'module'
91
+ });
92
+ }
93
+ worker.addEventListener('message', event => receive(event.data));
94
+ worker.addEventListener('error', event => receive({
95
+ failure: event.message || (crossOrigin ? `The worker failed to start: its script comes from another origin (${script.origin}), so it was started through a blob: URL, which also failed. Check that the server sends CORS headers and that a Content-Security-Policy allows worker-src blob:.` : 'The worker failed to start: check that its script (worker-thread) is served next to the package, or emitted by your bundler, and that a Content-Security-Policy allows it as a worker.')
96
+ }));
97
+ return {
98
+ post: (message, transfer) => worker.postMessage(message, transfer),
99
+ terminate: () => worker.terminate(),
100
+ ref: () => {},
101
+ unref: () => {}
102
+ };
103
+ }
104
+ // The specifier is built at run time so no bundler tries to resolve it (esbuild ignores comment hints on a literal).
105
+ const {
106
+ Worker: NodeWorker
107
+ } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
108
+ // The worker script needs none of the parent's flags, and some (like --input-type) are invalid in a worker.
109
+ const worker = new NodeWorker(await nodeWorkerScript(), {
110
+ execArgv: []
111
+ });
112
+ worker.on('message', receive);
113
+ worker.on('error', error => receive({
114
+ failure: error.message
115
+ }));
116
+ worker.on('exit', code => receive({
117
+ failure: `The worker exited unexpectedly (code ${code}).`
100
118
  }));
101
- return function start(_x) {
102
- return _ref.apply(this, arguments);
119
+ worker.unref();
120
+ return {
121
+ post: (message, transfer) => worker.postMessage(message, transfer),
122
+ terminate: () => worker.terminate(),
123
+ ref: () => worker.ref(),
124
+ unref: () => worker.unref()
103
125
  };
104
- }();
126
+ };
127
+
128
+ // Checked by tag as well as `instanceof`, so an ImageData from another realm (an iframe's canvas) or a module compiled by a
129
+ // bundler's runtime is recognised (see index.js).
130
+ const tagOf = value => Object.prototype.toString.call(value);
131
+ const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
132
+ const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
133
+
134
+ // A copy of the bytes in an argument (a typed array, or an image's `data`), for a call made before the worker is ready to
135
+ // take it: the caller may change or reuse its arrays as soon as the call returns, as with the main entry. Once the worker
136
+ // is running, a call posts (and so copies or transfers) its arguments before it returns.
137
+ const own = value => {
138
+ if (ArrayBuffer.isView(value)) {
139
+ const copy = value.slice();
140
+ // A Palette or Clustering keeps its tags (slice gives a plain array).
141
+ for (const key of Object.getOwnPropertySymbols(value)) {
142
+ Object.defineProperty(copy, key, {
143
+ value: value[key]
144
+ });
145
+ }
146
+ if (Object.prototype.hasOwnProperty.call(value, 'colorSpace')) {
147
+ Object.defineProperty(copy, 'colorSpace', {
148
+ value: value.colorSpace
149
+ });
150
+ }
151
+ return copy;
152
+ }
153
+ if (isOptionsObject(value) && ArrayBuffer.isView(value.data)) {
154
+ return {
155
+ ...value,
156
+ data: value.data.slice()
157
+ };
158
+ }
159
+ return value;
160
+ };
105
161
 
106
162
  // Images cross to the worker as plain {data, format, width?, height?} objects (ImageData can't cross into Node
107
163
  // worker threads, and its clamped array needn't), and mapped images are rebuilt in the caller's type on return.
108
164
  // Anything else is sent as it is, so the worker's validation gives the usual errors.
109
- var send = function send(image) {
110
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
111
- var data = image.data;
165
+ // Things that aren't pixels and can't be posted (a canvas, an image element, an ImageBitmap, a Blob) are reported here with
166
+ // the main entry's hint, rather than as the structured clone's own error, which says nothing about what to pass instead.
167
+ const notPixels = image => image !== null && typeof image === 'object' && !ArrayBuffer.isView(image) && !isImageData(image) && (typeof image.getContext === 'function' || typeof image.close === 'function' || typeof image.nodeName === 'string' || typeof image.arrayBuffer === 'function' && typeof image.type === 'string');
168
+ const send = image => {
169
+ if (notPixels(image)) {
170
+ throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
171
+ }
172
+ if (isImageData(image)) {
173
+ const data = image.data;
112
174
  return {
113
175
  data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
114
176
  format: 'rgba',
@@ -116,8 +178,8 @@ var send = function send(image) {
116
178
  height: image.height
117
179
  };
118
180
  }
119
- if (image && _typeof(image) === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
120
- var sent = {
181
+ if (image && typeof image === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
182
+ const sent = {
121
183
  data: image.data,
122
184
  format: image.format
123
185
  };
@@ -134,27 +196,25 @@ var send = function send(image) {
134
196
 
135
197
  // The worker returns what the main entry gives for the image it was sent: the same type for a Uint8Array or a
136
198
  // RawImage, and a RawImage for ImageData, which is turned back into ImageData here.
137
- var rebuild = function rebuild(image) {
138
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
139
- var width = image.width,
140
- height = image.height,
141
- colorSpace = image.colorSpace;
142
- return function (result) {
143
- return new ImageData(new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength), width, height, colorSpace ? {
144
- colorSpace: colorSpace
145
- } : undefined);
146
- };
199
+ const rebuild = image => {
200
+ if (isImageData(image)) {
201
+ const {
202
+ width,
203
+ height,
204
+ colorSpace
205
+ } = image;
206
+ return result => new ImageData(new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength), width, height, colorSpace ? {
207
+ colorSpace
208
+ } : undefined);
147
209
  }
148
- return function (result) {
149
- return result;
150
- };
210
+ return result => result;
151
211
  };
152
212
 
153
213
  // The buffer behind an image's pixels, to transfer when the worker was created with `transfer: true`: only when the
154
214
  // pixels are the whole of an ordinary ArrayBuffer. Transferring empties every view of the buffer, so a view into part
155
215
  // of a larger one (a subarray, a small Node Buffer from Node's shared pool) is copied instead, as is shared memory.
156
- var pixelBuffers = function pixelBuffers(sent) {
157
- var data = ArrayBuffer.isView(sent) ? sent : sent && ArrayBuffer.isView(sent.data) ? sent.data : null;
216
+ const pixelBuffers = sent => {
217
+ const data = ArrayBuffer.isView(sent) ? sent : sent && ArrayBuffer.isView(sent.data) ? sent.data : null;
158
218
  if (!data || !(data.buffer instanceof ArrayBuffer) || data.byteOffset !== 0 || data.byteLength !== data.buffer.byteLength) {
159
219
  return [];
160
220
  }
@@ -163,8 +223,8 @@ var pixelBuffers = function pixelBuffers(sent) {
163
223
 
164
224
  // Rebuilds an error that happened in the worker: same name, message and code as the main entry gives for the same
165
225
  // input, the stack of the call that failed (`origin`, made when the call was sent), and the worker's own stack as `cause`.
166
- var remoteError = function remoteError(info, origin) {
167
- var error = new Error(info.message);
226
+ const remoteError = (info, origin) => {
227
+ const error = new Error(info.message);
168
228
  if (info.name && info.name !== 'Error') {
169
229
  error.name = info.name;
170
230
  }
@@ -175,10 +235,10 @@ var remoteError = function remoteError(info, origin) {
175
235
  error.argument = info.argument;
176
236
  }
177
237
  if (origin.stack) {
178
- error.stack = "".concat(error.name, ": ").concat(error.message).concat(origin.stack.slice(origin.stack.indexOf('\n')));
238
+ error.stack = `${error.name}: ${error.message}${origin.stack.slice(origin.stack.indexOf('\n'))}`;
179
239
  }
180
240
  if (info.stack) {
181
- var cause = new Error(info.message);
241
+ const cause = new Error(info.message);
182
242
  cause.name = error.name;
183
243
  cause.stack = info.stack;
184
244
  error.cause = cause;
@@ -188,24 +248,24 @@ var remoteError = function remoteError(info, origin) {
188
248
 
189
249
  // Checks the `wasm` option (see init in the main entry) and makes it fit for posting to the worker: a URL becomes its
190
250
  // string, and bytes and compiled modules are cloned across.
191
- var wasmOption = function wasmOption(wasm) {
251
+ const wasmOption = wasm => {
192
252
  if (typeof wasm === 'string') {
193
253
  return wasm;
194
254
  }
195
- if (typeof URL !== 'undefined' && wasm instanceof URL) {
255
+ if (typeof wasm === 'object' && wasm !== null && (typeof URL !== 'undefined' && wasm instanceof URL || tagOf(wasm) === '[object URL]')) {
196
256
  return wasm.href;
197
257
  }
198
- if (wasm instanceof ArrayBuffer || ArrayBuffer.isView(wasm)) {
258
+ if (wasm instanceof ArrayBuffer || tagOf(wasm) === '[object ArrayBuffer]' || ArrayBuffer.isView(wasm)) {
199
259
  return wasm;
200
260
  }
201
- if (typeof WebAssembly !== 'undefined' && wasm instanceof WebAssembly.Module) {
261
+ if (isWasmModule(wasm)) {
202
262
  return wasm;
203
263
  }
204
264
  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');
205
265
  };
206
266
 
207
267
  // Options for init: only `wasm`, or none.
208
- var initOptions = function initOptions(options) {
268
+ const initOptions = options => {
209
269
  if (options === undefined) {
210
270
  return undefined;
211
271
  }
@@ -213,10 +273,9 @@ var initOptions = function initOptions(options) {
213
273
  throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
214
274
  }
215
275
  options = snapshot(options);
216
- for (var _i = 0, _Object$keys = Object.keys(options); _i < _Object$keys.length; _i++) {
217
- var key = _Object$keys[_i];
276
+ for (const key of Object.keys(options)) {
218
277
  if (key !== 'wasm') {
219
- throw fail('invalid-argument', "Invalid option '".concat(key, "': expected wasm."), "options.".concat(key));
278
+ throw fail('invalid-argument', `Invalid option '${key}': expected wasm.`, `options.${key}`);
220
279
  }
221
280
  }
222
281
  return options.wasm === undefined ? {} : {
@@ -226,50 +285,51 @@ var initOptions = function initOptions(options) {
226
285
 
227
286
  // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
228
287
  // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
229
- var takeControls = function takeControls(options) {
230
- var progressAllowed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
288
+ const takeControls = (options, progressAllowed = true) => {
231
289
  // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
232
290
  // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
233
291
  if (!isOptionsObject(options)) {
234
292
  return {
235
- options: options,
293
+ options,
236
294
  signal: undefined,
237
295
  onProgress: undefined
238
296
  };
239
297
  }
240
298
  options = snapshot(options);
241
- var _options = options,
242
- signal = _options.signal,
243
- onProgress = _options.onProgress;
299
+ const {
300
+ signal,
301
+ onProgress
302
+ } = options;
244
303
  if (!progressAllowed && onProgress !== undefined) {
245
304
  throw fail('invalid-argument', "Invalid option 'onProgress': the functions that only map pixels take just `signal`.", 'options.onProgress');
246
305
  }
247
306
  if (signal === undefined && onProgress === undefined) {
248
307
  return {
249
- options: options,
250
- signal: signal,
251
- onProgress: onProgress
308
+ options,
309
+ signal,
310
+ onProgress
252
311
  };
253
312
  }
254
- if (signal !== undefined && (signal === null || _typeof(signal) !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
313
+ if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
255
314
  throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
256
315
  }
257
316
  if (onProgress !== undefined && typeof onProgress !== 'function') {
258
317
  throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
259
318
  }
260
- var _options2 = options,
261
- _signal = _options2.signal,
262
- _onProgress = _options2.onProgress,
263
- rest = _objectWithoutProperties(_options2, _excluded);
319
+ const {
320
+ signal: _signal,
321
+ onProgress: _onProgress,
322
+ ...rest
323
+ } = options;
264
324
  return {
265
325
  options: rest,
266
- signal: signal,
267
- onProgress: onProgress
326
+ signal,
327
+ onProgress
268
328
  };
269
329
  };
270
330
 
271
331
  // Where the options sit among a function's arguments after the image (see takeControls).
272
- var optionsPosition = {
332
+ const optionsPosition = {
273
333
  getClustering: 0,
274
334
  getPalette: 1,
275
335
  getSwatches: 1,
@@ -282,15 +342,13 @@ var optionsPosition = {
282
342
  };
283
343
 
284
344
  // Like fetch: an aborted call rejects with the signal's reason, an AbortError unless the caller gave another.
285
- var abortReason = function abortReason(signal) {
286
- return signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
287
- };
288
- var imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
289
- var mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
345
+ const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
346
+ const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
347
+ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
290
348
  // These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
291
- var mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
292
- var otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
293
- export var createWorker = function createWorker(options) {
349
+ const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
350
+ const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
351
+ export const createWorker = options => {
294
352
  if (options === undefined) {
295
353
  options = {};
296
354
  }
@@ -298,45 +356,60 @@ export var createWorker = function createWorker(options) {
298
356
  throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
299
357
  }
300
358
  options = snapshot(options);
301
- for (var _i2 = 0, _Object$keys2 = Object.keys(options); _i2 < _Object$keys2.length; _i2++) {
302
- var key = _Object$keys2[_i2];
359
+ for (const key of Object.keys(options)) {
303
360
  if (key !== 'transfer' && key !== 'wasm') {
304
- throw fail('invalid-argument', "Invalid option '".concat(key, "': expected transfer, wasm."), "options.".concat(key));
361
+ throw fail('invalid-argument', `Invalid option '${key}': expected transfer, wasm.`, `options.${key}`);
305
362
  }
306
363
  }
307
364
  if (options.transfer !== undefined && typeof options.transfer !== 'boolean') {
308
365
  throw fail('invalid-argument', "Invalid transfer: must be a boolean.", 'options.transfer');
309
366
  }
310
- var transfer = options.transfer === true;
367
+ const transfer = options.transfer === true;
311
368
  // Where the worker finds its .wasm: sent as the worker's first call, and repeated until it has succeeded.
312
- var initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
313
- var initial = initialWasm === undefined ? null : {
369
+ const initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
370
+ let initial = initialWasm === undefined ? null : {
314
371
  wasm: initialWasm
315
372
  };
316
- var initialising = null;
317
- var connection = null;
318
- var starting = null;
373
+ let initialising = null;
374
+ let connection = null;
375
+ let starting = null;
319
376
  // Counts the workers this instance has started, so a late message or error from one it already dropped is ignored.
320
- var generation = 0;
321
- var startingGeneration = 0;
322
- var terminated = false;
323
- var nextId = 1;
324
- var nextHandle = 1;
325
- var pending = new Map();
377
+ let generation = 0;
378
+ let startingGeneration = 0;
379
+ let terminated = false;
380
+ let nextId = 1;
381
+ let nextHandle = 1;
382
+ const pending = new Map();
383
+ // Whether a call made now is posted before it returns (see `own`).
384
+ const ready = () => connection !== null && !initial;
385
+ // The image of a call made before the worker is ready: with `transfer: true` its buffer is moved out of the caller's
386
+ // hands at once (a structured clone that transfers it, so the caller's array empties now, as it would on posting),
387
+ // otherwise copied.
388
+ const take = sent => {
389
+ const buffers = transfer ? pixelBuffers(sent) : [];
390
+ if (buffers.length > 0 && typeof structuredClone === 'function') {
391
+ try {
392
+ return structuredClone(sent, {
393
+ transfer: buffers
394
+ });
395
+ } catch (error) {/* untransferable: copy it */}
396
+ }
397
+ return own(sent);
398
+ };
326
399
 
327
400
  // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
328
401
  // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
329
- var reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (id) {
402
+ const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
330
403
  if (!terminated) {
331
- invoke('release', [id], [], new Error())["catch"](function () {});
404
+ invoke('release', [id], [], new Error()).catch(() => {});
332
405
  }
333
406
  }) : null;
334
407
 
335
408
  // A worker that failed (could not start, crashed or exited) is dropped: the calls waiting on it get the failure, and
336
409
  // the next call starts a new one, which either works or fails the same clear way. Without this, later calls would be
337
410
  // posted to a thread that will never answer and hang forever. Handles kept in the dropped worker are gone with it.
338
- var lose = function lose(reason) {
339
- var lost = connection;
411
+ const lose = reason => {
412
+ const lost = connection;
340
413
  generation++;
341
414
  connection = null;
342
415
  starting = null;
@@ -346,35 +419,26 @@ export var createWorker = function createWorker(options) {
346
419
  wasm: initialWasm
347
420
  };
348
421
  }
349
- var calls = _toConsumableArray(pending.values());
422
+ const calls = [...pending.values()];
350
423
  pending.clear();
351
- var _iterator = _createForOfIteratorHelper(calls),
352
- _step;
353
- try {
354
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
355
- var call = _step.value;
356
- call.cleanup();
357
- call.reject(fail('worker-failed', reason));
358
- }
359
- } catch (err) {
360
- _iterator.e(err);
361
- } finally {
362
- _iterator.f();
424
+ for (const call of calls) {
425
+ call.cleanup();
426
+ call.reject(fail('worker-failed', reason));
363
427
  }
364
428
  if (lost) {
365
429
  try {
366
- Promise.resolve(lost.terminate())["catch"](function () {});
430
+ Promise.resolve(lost.terminate()).catch(() => {});
367
431
  } catch (ignored) {/* already gone */}
368
432
  }
369
433
  };
370
- var receive = function receive(message) {
434
+ const receive = message => {
371
435
  if (message.failure !== undefined) {
372
436
  if (!terminated) {
373
- lose("Worker failed: ".concat(message.failure));
437
+ lose(`Worker failed: ${message.failure}`);
374
438
  }
375
439
  return;
376
440
  }
377
- var call = pending.get(message.id);
441
+ const call = pending.get(message.id);
378
442
  if (!call) {
379
443
  return;
380
444
  }
@@ -384,7 +448,7 @@ export var createWorker = function createWorker(options) {
384
448
  try {
385
449
  call.onProgress(message.progress);
386
450
  } catch (error) {
387
- pending["delete"](message.id);
451
+ pending.delete(message.id);
388
452
  call.cleanup();
389
453
  if (pending.size === 0 && connection) {
390
454
  connection.unref();
@@ -399,7 +463,7 @@ export var createWorker = function createWorker(options) {
399
463
  }
400
464
  return;
401
465
  }
402
- pending["delete"](message.id);
466
+ pending.delete(message.id);
403
467
  call.cleanup();
404
468
  if (pending.size === 0 && connection) {
405
469
  connection.unref();
@@ -413,112 +477,78 @@ export var createWorker = function createWorker(options) {
413
477
 
414
478
  // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
415
479
  // from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
416
- var invoke = /*#__PURE__*/function () {
417
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(method, args, transferable, origin) {
418
- var controls,
419
- mine,
420
- waitingFor,
421
- started,
422
- _args2 = arguments;
423
- return _regenerator().w(function (_context2) {
424
- while (1) switch (_context2.n) {
425
- case 0:
426
- controls = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : {};
427
- if (!terminated) {
428
- _context2.n = 1;
429
- break;
430
- }
431
- throw fail('worker-terminated', "Worker terminated.");
432
- case 1:
433
- if (connection) {
434
- _context2.n = 5;
435
- break;
436
- }
437
- if (!starting) {
438
- mine = ++generation;
439
- startingGeneration = mine;
440
- // A start that fails is not kept, so the next call tries again.
441
- starting = start(function (message) {
442
- if (mine === generation) {
443
- receive(message);
444
- }
445
- })["catch"](function (error) {
446
- if (mine === generation) {
447
- starting = null;
448
- }
449
- throw Object.assign(fail('worker-failed', "Worker failed: ".concat(error && error.message)), {
450
- cause: error
451
- });
452
- });
453
- }
454
- waitingFor = startingGeneration;
455
- _context2.n = 2;
456
- return starting;
457
- case 2:
458
- started = _context2.v;
459
- if (!terminated) {
460
- _context2.n = 3;
461
- break;
462
- }
463
- started.terminate();
464
- throw fail('worker-terminated', "Worker terminated.");
465
- case 3:
466
- if (!(waitingFor !== generation)) {
467
- _context2.n = 4;
468
- break;
469
- }
470
- throw fail('worker-failed', 'Worker failed while starting.');
471
- case 4:
472
- connection = connection || started;
473
- case 5:
474
- if (!(initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined))) {
475
- _context2.n = 6;
476
- break;
477
- }
478
- initialising = initialising || post('init', [initial], [], origin).then(function () {
479
- initial = null;
480
- }, function (error) {
481
- initialising = null;
482
- throw error;
483
- });
484
- _context2.n = 6;
485
- return initialising;
486
- case 6:
487
- return _context2.a(2, post(method, args, transferable, origin, controls));
488
- }
489
- }, _callee2);
490
- }));
491
- return function invoke(_x2, _x3, _x4, _x5) {
492
- return _ref2.apply(this, arguments);
493
- };
494
- }();
495
- var post = function post(method, args, transferable, origin) {
496
- var _ref3 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {},
497
- signal = _ref3.signal,
498
- onProgress = _ref3.onProgress;
480
+ const invoke = async (method, args, transferable, origin, controls = {}) => {
481
+ if (terminated) {
482
+ throw fail('worker-terminated', "Worker terminated.");
483
+ }
484
+ if (!connection) {
485
+ if (!starting) {
486
+ const mine = ++generation;
487
+ startingGeneration = mine;
488
+ // A start that fails is not kept, so the next call tries again.
489
+ starting = start(message => {
490
+ if (mine === generation) {
491
+ receive(message);
492
+ }
493
+ }).catch(error => {
494
+ if (mine === generation) {
495
+ starting = null;
496
+ }
497
+ throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message}`), {
498
+ cause: error
499
+ });
500
+ });
501
+ }
502
+ const waitingFor = startingGeneration;
503
+ const started = await starting;
504
+ if (terminated) {
505
+ started.terminate();
506
+ throw fail('worker-terminated', "Worker terminated.");
507
+ }
508
+ // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
509
+ if (waitingFor !== generation) {
510
+ throw fail('worker-failed', 'Worker failed while starting.');
511
+ }
512
+ connection = connection || started;
513
+ }
514
+ if (initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined)) {
515
+ initialising = initialising || post('init', [initial], [], origin).then(() => {
516
+ initial = null;
517
+ }, error => {
518
+ initialising = null;
519
+ throw error;
520
+ });
521
+ await initialising;
522
+ }
523
+ return post(method, args, transferable, origin, controls);
524
+ };
525
+ const post = (method, args, transferable, origin, {
526
+ signal,
527
+ onProgress
528
+ } = {}) => {
499
529
  if (terminated) {
500
530
  return Promise.reject(fail('worker-terminated', "Worker terminated."));
501
531
  }
502
532
  if (signal && signal.aborted) {
503
533
  return Promise.reject(abortReason(signal));
504
534
  }
505
- var id = nextId++;
506
- return new Promise(function (resolve, reject) {
535
+ const id = nextId++;
536
+ return new Promise((resolve, reject) => {
507
537
  if (pending.size === 0) {
508
538
  connection.ref();
509
539
  }
510
- var call = {
511
- resolve: resolve,
512
- reject: reject,
513
- origin: origin,
514
- onProgress: onProgress,
515
- cleanup: function cleanup() {}
540
+ const call = {
541
+ resolve,
542
+ reject,
543
+ origin,
544
+ onProgress,
545
+ cleanup: () => {}
516
546
  };
517
547
  if (signal) {
518
548
  // Rejects at once; the worker is told to stop (it may still be working on an earlier call or this one,
519
549
  // and drops whatever it produces). The thread no longer keeps a Node process alive for this call.
520
- var abort = function abort() {
521
- if (!pending["delete"](id)) {
550
+ const abort = () => {
551
+ if (!pending.delete(id)) {
522
552
  return;
523
553
  }
524
554
  if (pending.size === 0) {
@@ -534,15 +564,13 @@ export var createWorker = function createWorker(options) {
534
564
  signal.addEventListener('abort', abort, {
535
565
  once: true
536
566
  });
537
- call.cleanup = function () {
538
- return signal.removeEventListener('abort', abort);
539
- };
567
+ call.cleanup = () => signal.removeEventListener('abort', abort);
540
568
  }
541
569
  pending.set(id, call);
542
570
  try {
543
- var message = {
544
- id: id,
545
- method: method,
571
+ const message = {
572
+ id,
573
+ method,
546
574
  args: args.map(mark),
547
575
  cancellable: signal !== undefined || onProgress !== undefined,
548
576
  progress: onProgress !== undefined
@@ -558,396 +586,202 @@ export var createWorker = function createWorker(options) {
558
586
  connection.post(message, []);
559
587
  }
560
588
  } catch (error) {
561
- pending["delete"](id);
589
+ pending.delete(id);
562
590
  call.cleanup();
563
591
  if (pending.size === 0) {
564
592
  connection.unref();
565
593
  }
566
594
  // A value that can't be structured-cloned (a function, symbol or promise) is an invalid argument, as it
567
595
  // would be if the main entry were called with it.
568
- reject(error && error.name === 'DataCloneError' ? Object.assign(fail('invalid-argument', "Invalid argument: it cannot be sent to the worker (".concat(error.message, ")")), {
596
+ reject(error && error.name === 'DataCloneError' ? Object.assign(fail('invalid-argument', `Invalid argument: it cannot be sent to the worker (${error.message})`), {
569
597
  cause: error
570
598
  }) : error);
571
599
  }
572
600
  });
573
601
  };
574
- var instance = {};
575
- var _loop = function _loop() {
576
- var name = _imageFunctions[_i3];
577
- var mapped = mappedImageFunctions.includes(name);
578
- instance[name] = function (image) {
579
- for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
580
- rest[_key - 1] = arguments[_key];
581
- }
582
- var origin = new Error();
583
- return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
584
- var position, _takeControls, options, signal, onProgress, args, sent, result;
585
- return _regenerator().w(function (_context3) {
586
- while (1) switch (_context3.n) {
587
- case 0:
588
- position = optionsPosition[name];
589
- _takeControls = takeControls(rest[position], !mappingOnlyFunctions.includes(name)), options = _takeControls.options, signal = _takeControls.signal, onProgress = _takeControls.onProgress; // Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
590
- if (!(signal && signal.aborted)) {
591
- _context3.n = 1;
592
- break;
593
- }
594
- throw abortReason(signal);
595
- case 1:
596
- args = rest.slice();
597
- if (position < args.length) {
598
- args[position] = options;
599
- }
600
- sent = send(image);
601
- _context3.n = 2;
602
- return invoke(name, [sent].concat(_toConsumableArray(args)), pixelBuffers(sent), origin, {
603
- signal: signal,
604
- onProgress: onProgress
605
- });
606
- case 2:
607
- result = _context3.v;
608
- return _context3.a(2, mapped ? rebuild(image)(result) : result);
609
- }
610
- }, _callee3);
611
- }))();
612
- };
613
- };
614
- for (var _i3 = 0, _imageFunctions = imageFunctions; _i3 < _imageFunctions.length; _i3++) {
615
- _loop();
616
- }
617
- var _loop2 = function _loop2() {
618
- var name = _otherFunctions[_i4];
619
- instance[name] = function () {
620
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
621
- args[_key2] = arguments[_key2];
622
- }
623
- return invoke(name, args, [], new Error());
602
+ const instance = {};
603
+ for (const name of imageFunctions) {
604
+ const mapped = mappedImageFunctions.includes(name);
605
+ instance[name] = (image, ...rest) => {
606
+ const origin = new Error();
607
+ return (async () => {
608
+ const position = optionsPosition[name];
609
+ const {
610
+ options,
611
+ signal,
612
+ onProgress
613
+ } = takeControls(rest[position], !mappingOnlyFunctions.includes(name));
614
+ // Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
615
+ if (signal && signal.aborted) {
616
+ throw abortReason(signal);
617
+ }
618
+ let args = rest.slice();
619
+ if (position < args.length) {
620
+ args[position] = options;
621
+ }
622
+ let sent = send(image);
623
+ if (!ready()) {
624
+ sent = take(sent);
625
+ args = args.map(own);
626
+ }
627
+ const result = await invoke(name, [sent, ...args], pixelBuffers(sent), origin, {
628
+ signal,
629
+ onProgress
630
+ });
631
+ return mapped ? rebuild(image)(result) : result;
632
+ })();
624
633
  };
625
- };
626
- for (var _i4 = 0, _otherFunctions = otherFunctions; _i4 < _otherFunctions.length; _i4++) {
627
- _loop2();
628
634
  }
629
- instance.init = function (initArgs) {
630
- var origin = new Error();
631
- var checked;
635
+ for (const name of otherFunctions) {
636
+ instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
637
+ }
638
+ instance.init = initArgs => {
639
+ const origin = new Error();
640
+ let checked;
632
641
  try {
633
642
  checked = initOptions(initArgs);
634
643
  } catch (error) {
635
644
  return Promise.reject(error);
636
645
  }
637
- return invoke('init', checked === undefined ? [] : [checked], [], origin).then(function () {
638
- return undefined;
639
- });
646
+ return invoke('init', checked === undefined ? [] : [checked], [], origin).then(() => undefined);
640
647
  };
641
648
 
642
649
  // Clusters `image` and keeps it, with its clustering, in the worker.
643
- instance.cluster = function (image, clusterOptions) {
644
- var origin = new Error();
645
- return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7() {
646
- var _takeControls2, options, signal, onProgress, id, sent, output, released, use, withControls, handle, _t6;
647
- return _regenerator().w(function (_context7) {
648
- while (1) switch (_context7.n) {
649
- case 0:
650
- _takeControls2 = takeControls(clusterOptions), options = _takeControls2.options, signal = _takeControls2.signal, onProgress = _takeControls2.onProgress;
651
- if (!(signal && signal.aborted)) {
652
- _context7.n = 1;
653
- break;
654
- }
655
- throw abortReason(signal);
656
- case 1:
657
- id = nextHandle++;
658
- sent = send(image);
659
- _context7.p = 2;
660
- _context7.n = 3;
661
- return invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
662
- signal: signal,
663
- onProgress: onProgress
664
- });
665
- case 3:
666
- _context7.n = 5;
667
- break;
668
- case 4:
669
- _context7.p = 4;
670
- _t6 = _context7.v;
671
- // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
672
- // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
673
- // is harmless, and this message follows the cluster call in the worker's queue.
674
- if (!terminated) {
675
- invoke('release', [id], [], new Error())["catch"](function () {});
676
- }
677
- throw _t6;
678
- case 5:
679
- output = rebuild(image);
680
- released = false; // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
681
- // keeps it alive and it is not reclaimed while still in use.
682
- use = function use(method, args, controls) {
683
- if (released || !handle) {
684
- return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
685
- }
686
- return invoke(method, [id].concat(_toConsumableArray(args)), [], new Error(), controls);
687
- }; // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
688
- withControls = function withControls(method, leading, mapOptions) {
689
- var taken;
690
- try {
691
- taken = takeControls(mapOptions, false);
692
- } catch (error) {
693
- return Promise.reject(error);
694
- }
695
- return use(method, [].concat(_toConsumableArray(leading), [taken.options]), {
696
- signal: taken.signal,
697
- onProgress: taken.onProgress
698
- });
699
- };
700
- handle = {
701
- getClustering: function getClustering() {
702
- return use('handleGetClustering', []);
703
- },
704
- getPalette: function getPalette(k) {
705
- return use('handleGetPalette', [k]);
706
- },
707
- getSwatches: function getSwatches(k) {
708
- return use('handleGetSwatches', [k]);
709
- },
710
- getClusteringInfo: function getClusteringInfo() {
711
- return use('handleGetClusteringInfo', []);
712
- },
713
- quantize: function () {
714
- var _quantize = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(k, mapOptions) {
715
- var _t, _t2;
716
- return _regenerator().w(function (_context4) {
717
- while (1) switch (_context4.n) {
718
- case 0:
719
- _t = output;
720
- _context4.n = 1;
721
- return withControls('handleQuantize', [k], mapOptions);
722
- case 1:
723
- _t2 = _context4.v;
724
- return _context4.a(2, _t(_t2));
725
- }
726
- }, _callee4);
727
- }));
728
- function quantize(_x6, _x7) {
729
- return _quantize.apply(this, arguments);
730
- }
731
- return quantize;
732
- }(),
733
- quantizeToIndices: function quantizeToIndices(k, mapOptions) {
734
- return withControls('handleQuantizeToIndices', [k], mapOptions);
735
- },
736
- quantizeWithPalette: function () {
737
- var _quantizeWithPalette = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(palette, mapOptions) {
738
- var _t3, _t4;
739
- return _regenerator().w(function (_context5) {
740
- while (1) switch (_context5.n) {
741
- case 0:
742
- _t3 = output;
743
- _context5.n = 1;
744
- return withControls('handleQuantizeWithPalette', [palette], mapOptions);
745
- case 1:
746
- _t4 = _context5.v;
747
- return _context5.a(2, _t3(_t4));
748
- }
749
- }, _callee5);
750
- }));
751
- function quantizeWithPalette(_x8, _x9) {
752
- return _quantizeWithPalette.apply(this, arguments);
753
- }
754
- return quantizeWithPalette;
755
- }(),
756
- quantizeToIndicesWithPalette: function quantizeToIndicesWithPalette(palette, mapOptions) {
757
- return withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions);
758
- },
759
- release: function () {
760
- var _release = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {
761
- var _t5;
762
- return _regenerator().w(function (_context6) {
763
- while (1) switch (_context6.n) {
764
- case 0:
765
- if (!released) {
766
- _context6.n = 1;
767
- break;
768
- }
769
- return _context6.a(2);
770
- case 1:
771
- released = true;
772
- if (reclaim) {
773
- reclaim.unregister(handle);
774
- }
775
- // If the worker has been terminated there is nothing left to free (so `await using` and
776
- // terminate() can come in either order); any other failure is reported.
777
- _context6.p = 2;
778
- _context6.n = 3;
779
- return invoke('release', [id], [], new Error());
780
- case 3:
781
- _context6.n = 5;
782
- break;
783
- case 4:
784
- _context6.p = 4;
785
- _t5 = _context6.v;
786
- if (!(_t5.code !== 'worker-terminated')) {
787
- _context6.n = 5;
788
- break;
789
- }
790
- throw _t5;
791
- case 5:
792
- return _context6.a(2);
793
- }
794
- }, _callee6, null, [[2, 4]]);
795
- }));
796
- function release() {
797
- return _release.apply(this, arguments);
798
- }
799
- return release;
800
- }()
801
- }; // `await using handle = await worker.cluster(image)` releases it at the end of the block.
802
- if (_typeof(Symbol.asyncDispose) === 'symbol') {
803
- handle[Symbol.asyncDispose] = handle.release;
804
- }
805
- if (reclaim) {
806
- reclaim.register(handle, id, handle);
807
- }
808
- return _context7.a(2, handle);
650
+ instance.cluster = (image, clusterOptions) => {
651
+ const origin = new Error();
652
+ return (async () => {
653
+ const {
654
+ options,
655
+ signal,
656
+ onProgress
657
+ } = takeControls(clusterOptions);
658
+ if (signal && signal.aborted) {
659
+ throw abortReason(signal);
660
+ }
661
+ const id = nextHandle++;
662
+ const sent = ready() ? send(image) : take(send(image));
663
+ try {
664
+ await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
665
+ signal,
666
+ onProgress
667
+ });
668
+ } catch (error) {
669
+ // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
670
+ // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
671
+ // is harmless, and this message follows the cluster call in the worker's queue.
672
+ if (!terminated) {
673
+ invoke('release', [id], [], new Error()).catch(() => {});
809
674
  }
810
- }, _callee7, null, [[2, 4]]);
811
- }))();
812
- };
813
-
814
- // Stops the worker. Calls still waiting are rejected, and later calls fail.
815
- instance.terminate = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8() {
816
- var _iterator2, _step2, call, _t7;
817
- return _regenerator().w(function (_context8) {
818
- while (1) switch (_context8.n) {
819
- case 0:
820
- if (!terminated) {
821
- _context8.n = 1;
822
- break;
675
+ throw error;
676
+ }
677
+ const output = rebuild(image);
678
+ let released = false;
679
+ // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
680
+ // keeps it alive and it is not reclaimed while still in use.
681
+ const use = (method, args, controls) => {
682
+ if (released || !handle) {
683
+ return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
684
+ }
685
+ return invoke(method, [id, ...args], [], new Error(), controls);
686
+ };
687
+ // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
688
+ const withControls = (method, leading, mapOptions) => {
689
+ let taken;
690
+ try {
691
+ taken = takeControls(mapOptions, false);
692
+ } catch (error) {
693
+ return Promise.reject(error);
694
+ }
695
+ return use(method, [...leading, taken.options], {
696
+ signal: taken.signal,
697
+ onProgress: taken.onProgress
698
+ });
699
+ };
700
+ // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
701
+ // as in the main entry, rather than silently ignored.
702
+ const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
703
+ const handle = {
704
+ getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
705
+ getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
706
+ getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
707
+ getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
708
+ quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
709
+ quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
710
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
711
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
712
+ release: async () => {
713
+ if (released) {
714
+ return;
715
+ }
716
+ released = true;
717
+ if (reclaim) {
718
+ reclaim.unregister(handle);
823
719
  }
824
- return _context8.a(2);
825
- case 1:
826
- terminated = true;
827
- _iterator2 = _createForOfIteratorHelper(pending.values());
720
+ // If the worker has been terminated there is nothing left to free (so `await using` and
721
+ // terminate() can come in either order); any other failure is reported.
828
722
  try {
829
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
830
- call = _step2.value;
831
- call.cleanup();
832
- call.reject(fail('worker-terminated', "Worker terminated."));
723
+ await invoke('release', [id], [], new Error());
724
+ } catch (error) {
725
+ if (error.code !== 'worker-terminated') {
726
+ throw error;
833
727
  }
834
- } catch (err) {
835
- _iterator2.e(err);
836
- } finally {
837
- _iterator2.f();
838
- }
839
- pending.clear();
840
- if (!connection) {
841
- _context8.n = 3;
842
- break;
843
- }
844
- _context8.n = 2;
845
- return connection.terminate();
846
- case 2:
847
- _context8.n = 7;
848
- break;
849
- case 3:
850
- if (!starting) {
851
- _context8.n = 7;
852
- break;
853
728
  }
854
- _context8.p = 4;
855
- _context8.n = 5;
856
- return starting;
857
- case 5:
858
- _context8.v.terminate();
859
- _context8.n = 7;
860
- break;
861
- case 6:
862
- _context8.p = 6;
863
- _t7 = _context8.v;
864
- case 7:
865
- return _context8.a(2);
729
+ }
730
+ };
731
+ // `await using handle = await worker.cluster(image)` releases it at the end of the block.
732
+ if (typeof Symbol.asyncDispose === 'symbol') {
733
+ handle[Symbol.asyncDispose] = handle.release;
866
734
  }
867
- }, _callee8, null, [[4, 6]]);
868
- }));
735
+ if (reclaim) {
736
+ reclaim.register(handle, id, handle);
737
+ }
738
+ return handle;
739
+ })();
740
+ };
741
+
742
+ // Stops the worker. Calls still waiting are rejected, and later calls fail.
743
+ instance.terminate = async () => {
744
+ if (terminated) {
745
+ return;
746
+ }
747
+ terminated = true;
748
+ for (const call of pending.values()) {
749
+ call.cleanup();
750
+ call.reject(fail('worker-terminated', "Worker terminated."));
751
+ }
752
+ pending.clear();
753
+ if (connection) {
754
+ await connection.terminate();
755
+ } else if (starting) {
756
+ try {
757
+ (await starting).terminate();
758
+ } catch (ignored) {/* it never started */}
759
+ }
760
+ };
869
761
  return instance;
870
762
  };
871
- var shared = null;
872
- var sharedWorker = function sharedWorker() {
873
- return shared = shared || createWorker();
874
- };
763
+ let shared = null;
764
+ const sharedWorker = () => shared = shared || createWorker();
875
765
 
876
766
  // Stops the shared worker, rejecting calls still waiting. The next call starts a fresh one.
877
- export var terminate = /*#__PURE__*/function () {
878
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() {
879
- var stopping;
880
- return _regenerator().w(function (_context9) {
881
- while (1) switch (_context9.n) {
882
- case 0:
883
- if (shared) {
884
- _context9.n = 1;
885
- break;
886
- }
887
- return _context9.a(2);
888
- case 1:
889
- stopping = shared;
890
- shared = null;
891
- _context9.n = 2;
892
- return stopping.terminate();
893
- case 2:
894
- return _context9.a(2);
895
- }
896
- }, _callee9);
897
- }));
898
- return function terminate() {
899
- return _ref7.apply(this, arguments);
900
- };
901
- }();
902
- export var init = function init() {
903
- var _sharedWorker;
904
- return (_sharedWorker = sharedWorker()).init.apply(_sharedWorker, arguments);
905
- };
906
- export var getClustering = function getClustering() {
907
- var _sharedWorker2;
908
- return (_sharedWorker2 = sharedWorker()).getClustering.apply(_sharedWorker2, arguments);
909
- };
910
- export var getPalette = function getPalette() {
911
- var _sharedWorker3;
912
- return (_sharedWorker3 = sharedWorker()).getPalette.apply(_sharedWorker3, arguments);
913
- };
914
- export var getPaletteFromClustering = function getPaletteFromClustering() {
915
- var _sharedWorker4;
916
- return (_sharedWorker4 = sharedWorker()).getPaletteFromClustering.apply(_sharedWorker4, arguments);
917
- };
918
- export var getSwatches = function getSwatches() {
919
- var _sharedWorker5;
920
- return (_sharedWorker5 = sharedWorker()).getSwatches.apply(_sharedWorker5, arguments);
921
- };
922
- export var getSwatchesFromClustering = function getSwatchesFromClustering() {
923
- var _sharedWorker6;
924
- return (_sharedWorker6 = sharedWorker()).getSwatchesFromClustering.apply(_sharedWorker6, arguments);
925
- };
926
- export var getClusteringInfo = function getClusteringInfo() {
927
- var _sharedWorker7;
928
- return (_sharedWorker7 = sharedWorker()).getClusteringInfo.apply(_sharedWorker7, arguments);
929
- };
930
- export var quantize = function quantize() {
931
- var _sharedWorker8;
932
- return (_sharedWorker8 = sharedWorker()).quantize.apply(_sharedWorker8, arguments);
933
- };
934
- export var quantizeFromClustering = function quantizeFromClustering() {
935
- var _sharedWorker9;
936
- return (_sharedWorker9 = sharedWorker()).quantizeFromClustering.apply(_sharedWorker9, arguments);
937
- };
938
- export var quantizeWithPalette = function quantizeWithPalette() {
939
- var _sharedWorker0;
940
- return (_sharedWorker0 = sharedWorker()).quantizeWithPalette.apply(_sharedWorker0, arguments);
941
- };
942
- export var quantizeToIndices = function quantizeToIndices() {
943
- var _sharedWorker1;
944
- return (_sharedWorker1 = sharedWorker()).quantizeToIndices.apply(_sharedWorker1, arguments);
945
- };
946
- export var quantizeToIndicesFromClustering = function quantizeToIndicesFromClustering() {
947
- var _sharedWorker10;
948
- return (_sharedWorker10 = sharedWorker()).quantizeToIndicesFromClustering.apply(_sharedWorker10, arguments);
767
+ export const terminate = async () => {
768
+ if (!shared) {
769
+ return;
770
+ }
771
+ const stopping = shared;
772
+ shared = null;
773
+ await stopping.terminate();
949
774
  };
950
- export var quantizeToIndicesWithPalette = function quantizeToIndicesWithPalette() {
951
- var _sharedWorker11;
952
- return (_sharedWorker11 = sharedWorker()).quantizeToIndicesWithPalette.apply(_sharedWorker11, arguments);
953
- };
775
+ export const init = (...args) => sharedWorker().init(...args);
776
+ export const getClustering = (...args) => sharedWorker().getClustering(...args);
777
+ export const getPalette = (...args) => sharedWorker().getPalette(...args);
778
+ export const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
779
+ export const getSwatches = (...args) => sharedWorker().getSwatches(...args);
780
+ export const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
781
+ export const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
782
+ export const quantize = (...args) => sharedWorker().quantize(...args);
783
+ export const quantizeFromClustering = (...args) => sharedWorker().quantizeFromClustering(...args);
784
+ export const quantizeWithPalette = (...args) => sharedWorker().quantizeWithPalette(...args);
785
+ export const quantizeToIndices = (...args) => sharedWorker().quantizeToIndices(...args);
786
+ export const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
787
+ export const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);