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

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