agglomerative-clustering 3.0.0-beta.4 → 3.0.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +207 -40
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +111 -18
- package/dist/index.d.cts +12 -1
- package/dist/index.d.ts +12 -1
- package/dist/index.mjs +97 -17
- package/dist/shared.cjs +34 -6
- package/dist/shared.mjs +29 -4
- package/dist/worker.cjs +1032 -0
- package/dist/worker.d.cts +149 -0
- package/dist/worker.d.ts +14 -1
- package/dist/worker.mjs +111 -29
- package/package.json +15 -6
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// `[Symbol.asyncDispose]` on handles needs TypeScript's `esnext.disposable` lib (TypeScript 5.2 and newer); this
|
|
2
|
+
// directive pulls it in. Older TypeScript versions report it unless `skipLibCheck` is on, as it is in most setups.
|
|
3
|
+
/// <reference lib="esnext.disposable" />
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
ImageLike, RawImage, ClusteringOptions, MappingOptions, QuantizeOptions, QuantizeIndexOptions, MappingIndexOptions,
|
|
7
|
+
IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches,
|
|
8
|
+
} from './index.cjs';
|
|
9
|
+
import type { Palette, Clustering } from './index.cjs';
|
|
10
|
+
|
|
11
|
+
/** The same class as the main entry's `Palette`: flat RGB bytes that know their colour space. */
|
|
12
|
+
export { Palette } from './index.cjs';
|
|
13
|
+
|
|
14
|
+
/** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
|
|
15
|
+
export { Clustering } from './index.cjs';
|
|
16
|
+
|
|
17
|
+
/** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
|
|
18
|
+
export { errorCodes } from './index.cjs';
|
|
19
|
+
|
|
20
|
+
/** The main entry's `isCodedError`: true for this library's errors, from either entry. */
|
|
21
|
+
export { isCodedError } from './index.cjs';
|
|
22
|
+
|
|
23
|
+
/** The version of this library, as in its `package.json`: the same value as the main entry's `version`. */
|
|
24
|
+
export const version: string;
|
|
25
|
+
|
|
26
|
+
/** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
|
|
27
|
+
export const formatVersion: 3;
|
|
28
|
+
|
|
29
|
+
export type {
|
|
30
|
+
ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
|
|
31
|
+
ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
|
|
32
|
+
} from './index.cjs';
|
|
33
|
+
|
|
34
|
+
/** Options for `createWorker`. */
|
|
35
|
+
export interface WorkerOptions {
|
|
36
|
+
/**
|
|
37
|
+
* `false` (default): images are copied to the worker. `true`: their pixel buffers are transferred instead,
|
|
38
|
+
* which is faster for large images but leaves the caller's buffer detached (empty) afterwards. Only pixels that
|
|
39
|
+
* are a whole buffer of their own are transferred: a view into part of a larger buffer (a subarray, a small Node
|
|
40
|
+
* Buffer) is copied, so the caller's other data in that buffer is never detached.
|
|
41
|
+
*/
|
|
42
|
+
transfer?: boolean | undefined;
|
|
43
|
+
/** Where the worker gets its WebAssembly module; see `InitOptions`. It is sent as the worker's first call. */
|
|
44
|
+
wasm?: InitOptions['wasm'] | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* The worker script to start, where the package's own isn't emitted or found: Angular's application builder, esbuild
|
|
47
|
+
* or Rollup without a worker plugin, a bundled Electron main process run from another directory. Point it at a copy
|
|
48
|
+
* of the package's `dist/worker-thread.mjs`, served or kept next to the rest of `dist/` (which it imports). A URL
|
|
49
|
+
* (relative URLs resolve against the page), or in Node a path (relative to the working directory) or `file:` URL.
|
|
50
|
+
*/
|
|
51
|
+
script?: string | URL | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Options for the worker entry's shared `init`: the main entry's, plus the shared worker's `script`. */
|
|
55
|
+
export interface SharedInitOptions extends InitOptions {
|
|
56
|
+
/**
|
|
57
|
+
* The shared worker's script (see `WorkerOptions.script`). Give it before any other call to the worker entry's
|
|
58
|
+
* functions: once the shared worker has started, a different script is rejected (call `terminate()` first).
|
|
59
|
+
*/
|
|
60
|
+
script?: string | URL | undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
|
|
64
|
+
export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
|
|
65
|
+
getClustering(): Promise<Clustering>;
|
|
66
|
+
getPalette(k: number): Promise<Palette>;
|
|
67
|
+
getSwatches(k: number): Promise<Swatches>;
|
|
68
|
+
getClusteringInfo(): Promise<ClusteringInfo>;
|
|
69
|
+
/** Maps the kept image to the k-colour palette. Returns the same type as the image given to `cluster`. */
|
|
70
|
+
quantize(k: number, options?: MappingOptions): Promise<Image>;
|
|
71
|
+
quantizeToIndices(k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
72
|
+
/** Maps the kept image to a palette of your own (an edited swatch, a brand palette) without sending the pixels again. */
|
|
73
|
+
quantizeWithPalette(palette: PaletteLike, options?: MappingOptions): Promise<Image>;
|
|
74
|
+
quantizeToIndicesWithPalette(palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
75
|
+
/**
|
|
76
|
+
* Frees the image and clustering in the worker. Later calls on the handle fail. Call it when you are done, or
|
|
77
|
+
* declare the handle with `await using`, which does. A handle that is dropped without either is freed once it is
|
|
78
|
+
* garbage-collected, but when that happens is up to the JavaScript engine.
|
|
79
|
+
*/
|
|
80
|
+
release(): Promise<void>;
|
|
81
|
+
/** The same as `release()`, for `await using`. Present where the runtime has `Symbol.asyncDispose`. */
|
|
82
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The main entry's functions, run in a worker, plus handles and `terminate`. */
|
|
86
|
+
export interface AgglomerativeWorker {
|
|
87
|
+
/** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
|
|
88
|
+
init(options?: InitOptions): Promise<void>;
|
|
89
|
+
getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
90
|
+
getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
91
|
+
getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
92
|
+
getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
93
|
+
getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
94
|
+
getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
95
|
+
quantize<Image extends ImageLike>(image: Image, k: number, options?: QuantizeOptions): Promise<ImageResult<Image>>;
|
|
96
|
+
quantizeFromClustering<Image extends ImageLike>(image: Image, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
|
|
97
|
+
quantizeWithPalette<Image extends ImageLike>(image: Image, palette: PaletteLike, options?: MappingOptions): Promise<ImageResult<Image>>;
|
|
98
|
+
quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
99
|
+
quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
100
|
+
quantizeToIndicesWithPalette(image: ImageLike, palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
101
|
+
/** Clusters `image` and keeps it, with its clustering, in the worker. */
|
|
102
|
+
cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
|
|
103
|
+
/** Stops the worker. Calls still waiting are rejected, and later calls fail. */
|
|
104
|
+
terminate(): Promise<void>;
|
|
105
|
+
/** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
|
|
106
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle.
|
|
111
|
+
* Call `terminate()` when you are done with it (or use `await using`): its thread and memory stay until then. As a
|
|
112
|
+
* safety net, a worker you dropped without terminating is stopped some time after it is garbage-collected, once no call
|
|
113
|
+
* is in flight and no handle from it is left; when that happens is up to the engine.
|
|
114
|
+
*/
|
|
115
|
+
export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
|
|
116
|
+
|
|
117
|
+
/** Stops the shared worker used by the exports below, rejecting calls still waiting. The next call starts a new one. */
|
|
118
|
+
export function terminate(): Promise<void>;
|
|
119
|
+
|
|
120
|
+
// The main entry's functions, run in one shared worker started on first use.
|
|
121
|
+
/**
|
|
122
|
+
* The main entry's `init`, run in the shared worker (see `createWorker` for a worker of your own). It also takes the
|
|
123
|
+
* shared worker's `script`, before any other call.
|
|
124
|
+
*/
|
|
125
|
+
export function init(options?: SharedInitOptions): Promise<void>;
|
|
126
|
+
/** The main entry's `getClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
127
|
+
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
128
|
+
/** The main entry's `getPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
129
|
+
export const getPalette: AgglomerativeWorker['getPalette'];
|
|
130
|
+
/** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
131
|
+
export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
|
|
132
|
+
/** The main entry's `getSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
133
|
+
export const getSwatches: AgglomerativeWorker['getSwatches'];
|
|
134
|
+
/** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
135
|
+
export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
|
|
136
|
+
/** The main entry's `getClusteringInfo`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
137
|
+
export const getClusteringInfo: AgglomerativeWorker['getClusteringInfo'];
|
|
138
|
+
/** The main entry's `quantize`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
139
|
+
export const quantize: AgglomerativeWorker['quantize'];
|
|
140
|
+
/** The main entry's `quantizeFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
141
|
+
export const quantizeFromClustering: AgglomerativeWorker['quantizeFromClustering'];
|
|
142
|
+
/** The main entry's `quantizeWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
143
|
+
export const quantizeWithPalette: AgglomerativeWorker['quantizeWithPalette'];
|
|
144
|
+
/** The main entry's `quantizeToIndices`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
145
|
+
export const quantizeToIndices: AgglomerativeWorker['quantizeToIndices'];
|
|
146
|
+
/** The main entry's `quantizeToIndicesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
147
|
+
export const quantizeToIndicesFromClustering: AgglomerativeWorker['quantizeToIndicesFromClustering'];
|
|
148
|
+
/** The main entry's `quantizeToIndicesWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
149
|
+
export const quantizeToIndicesWithPalette: AgglomerativeWorker['quantizeToIndicesWithPalette'];
|
package/dist/worker.d.ts
CHANGED
|
@@ -14,6 +14,12 @@ export { Palette } from './index.js';
|
|
|
14
14
|
/** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
|
|
15
15
|
export { Clustering } from './index.js';
|
|
16
16
|
|
|
17
|
+
/** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
|
|
18
|
+
export { errorCodes } from './index.js';
|
|
19
|
+
|
|
20
|
+
/** The main entry's `isCodedError`: true for this library's errors, from either entry. */
|
|
21
|
+
export { isCodedError } from './index.js';
|
|
22
|
+
|
|
17
23
|
/** The version of this library, as in its `package.json`: the same value as the main entry's `version`. */
|
|
18
24
|
export const version: string;
|
|
19
25
|
|
|
@@ -96,9 +102,16 @@ export interface AgglomerativeWorker {
|
|
|
96
102
|
cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
|
|
97
103
|
/** Stops the worker. Calls still waiting are rejected, and later calls fail. */
|
|
98
104
|
terminate(): Promise<void>;
|
|
105
|
+
/** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
|
|
106
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
99
107
|
}
|
|
100
108
|
|
|
101
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle.
|
|
111
|
+
* Call `terminate()` when you are done with it (or use `await using`): its thread and memory stay until then. As a
|
|
112
|
+
* safety net, a worker you dropped without terminating is stopped some time after it is garbage-collected, once no call
|
|
113
|
+
* is in flight and no handle from it is left; when that happens is up to the engine.
|
|
114
|
+
*/
|
|
102
115
|
export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
|
|
103
116
|
|
|
104
117
|
/** Stops the shared worker used by the exports below, rejecting calls still waiting. The next call starts a new one. */
|
package/dist/worker.mjs
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
// handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
|
|
5
5
|
// worker, started on first use.
|
|
6
6
|
|
|
7
|
-
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike } from "./shared.mjs";
|
|
7
|
+
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
|
|
8
8
|
|
|
9
9
|
// The same version, types and data-format version as the main entry (one implementation, in shared.js).
|
|
10
|
-
export { version, Palette, Clustering } from "./shared.mjs";
|
|
10
|
+
export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
|
|
11
11
|
export const formatVersion = latestVersion;
|
|
12
12
|
|
|
13
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
|
|
@@ -87,6 +87,15 @@ const isCrossOrigin = url => {
|
|
|
87
87
|
}
|
|
88
88
|
};
|
|
89
89
|
|
|
90
|
+
// Whether the page (or worker) has an opaque origin: a sandboxed iframe without allow-same-origin, or a data: page.
|
|
91
|
+
const isOpaqueOrigin = () => {
|
|
92
|
+
try {
|
|
93
|
+
return typeof location !== 'undefined' && location.origin === 'null';
|
|
94
|
+
} catch (error) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
90
99
|
// The page's (or worker's) base URL, to resolve relative URLs given in options against: the page, as fetch would, not the
|
|
91
100
|
// worker script's folder, where the worker would otherwise resolve them.
|
|
92
101
|
const pageBase = () => {
|
|
@@ -104,7 +113,7 @@ const pageBase = () => {
|
|
|
104
113
|
// Why the worker can't start where there is no Worker, by what the runtime is.
|
|
105
114
|
const noWorker = () => {
|
|
106
115
|
if (!scriptUrl) {
|
|
107
|
-
return "the worker entry can't find its worker script:
|
|
116
|
+
return "the worker entry can't find its worker script: it doesn't know its own URL, so it was bundled into CommonJS or a classic script, or loaded with require() (which gives the CommonJS build, made for Node and Jest). Import it as 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
117
|
}
|
|
109
118
|
if (typeof ServiceWorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof ServiceWorkerGlobalScope) {
|
|
110
119
|
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.";
|
|
@@ -124,32 +133,46 @@ const start = async (receive, chosen) => {
|
|
|
124
133
|
const here = scriptUrl;
|
|
125
134
|
const script = chosen ? new URL(chosen, pageBase()) : new URL('./worker-thread.mjs', here);
|
|
126
135
|
const crossOrigin = isCrossOrigin(script);
|
|
136
|
+
// A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
|
|
137
|
+
// start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
|
|
138
|
+
const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
|
|
139
|
+
const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
|
|
127
140
|
let worker,
|
|
128
141
|
source = null;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
142
|
+
try {
|
|
143
|
+
if (opaque) {
|
|
144
|
+
worker = new Worker(`data:text/javascript,${encodeURIComponent(`import ${JSON.stringify(script.href)};`)}`, {
|
|
145
|
+
type: 'module'
|
|
146
|
+
});
|
|
147
|
+
} else if (chosen && !crossOrigin) {
|
|
148
|
+
worker = new Worker(script, {
|
|
149
|
+
type: 'module'
|
|
150
|
+
});
|
|
151
|
+
} else if (crossOrigin) {
|
|
152
|
+
// A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
|
|
153
|
+
// module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
|
|
154
|
+
// Content-Security-Policy then needs `worker-src blob:` and the script's origin.
|
|
155
|
+
source = URL.createObjectURL(new Blob([`import ${JSON.stringify(script.href)};`], {
|
|
156
|
+
type: 'text/javascript'
|
|
157
|
+
}));
|
|
158
|
+
worker = new Worker(source, {
|
|
159
|
+
type: 'module'
|
|
160
|
+
});
|
|
161
|
+
setTimeout(() => URL.revokeObjectURL(source), 60000);
|
|
162
|
+
} else {
|
|
163
|
+
// Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
|
|
164
|
+
worker = new Worker(new URL('./worker-thread.mjs', import.meta.url), {
|
|
165
|
+
type: 'module'
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
} catch (error) {
|
|
169
|
+
throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message} ${scriptHint}`), {
|
|
170
|
+
cause: error
|
|
148
171
|
});
|
|
149
172
|
}
|
|
150
173
|
worker.addEventListener('message', event => receive(event.data));
|
|
151
174
|
worker.addEventListener('error', event => receive({
|
|
152
|
-
failure: event.message
|
|
175
|
+
failure: event.message ? `${event.message} ${scriptHint}` : 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 the worker: worker-src needs both blob: and ${script.origin} (the blob: worker imports the script from there). Or serve a copy of dist/ from this origin and say where with createWorker({ script }) or init({ script }).` : opaque ? `The worker failed to start from this page, whose origin is opaque (a sandboxed iframe): it was started from a data: URL importing ${script.href}, which needs CORS headers on that script and on what it imports. Or bundle worker-thread.mjs and its imports into one file, and pass it as a data: URL with createWorker({ script }).` : `The worker failed to start${chosen ? ` from ${script.href}` : ''}. ${scriptHint} A Content-Security-Policy must also allow it as a worker (worker-src).`
|
|
153
176
|
}));
|
|
154
177
|
return {
|
|
155
178
|
post: (message, transfer) => worker.postMessage(message, transfer),
|
|
@@ -167,8 +190,12 @@ const start = async (receive, chosen) => {
|
|
|
167
190
|
execArgv: []
|
|
168
191
|
});
|
|
169
192
|
worker.on('message', receive);
|
|
193
|
+
// A worker script that can't be found, or that can't find what it imports: a copy of dist/ split up or bundled away.
|
|
194
|
+
const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module|Qualified path resolution failed/.test(String(error.message)));
|
|
195
|
+
// Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
|
|
196
|
+
const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
|
|
170
197
|
worker.on('error', error => receive({
|
|
171
|
-
failure: error.message
|
|
198
|
+
failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
|
|
172
199
|
}));
|
|
173
200
|
worker.on('exit', code => receive({
|
|
174
201
|
failure: `The worker exited unexpectedly (code ${code}).`
|
|
@@ -182,10 +209,8 @@ const start = async (receive, chosen) => {
|
|
|
182
209
|
};
|
|
183
210
|
};
|
|
184
211
|
|
|
185
|
-
// Checked by tag as well as `instanceof`, so
|
|
186
|
-
// bundler's runtime is recognised (see index.js).
|
|
212
|
+
// Checked by tag as well as `instanceof`, so a module compiled by a bundler's runtime is recognised (see index.js).
|
|
187
213
|
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
214
|
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
190
215
|
|
|
191
216
|
// 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
|
|
@@ -232,6 +257,7 @@ const send = image => {
|
|
|
232
257
|
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
258
|
}
|
|
234
259
|
if (isImageData(image)) {
|
|
260
|
+
checkImageDataPixels(image);
|
|
235
261
|
const data = image.data;
|
|
236
262
|
return {
|
|
237
263
|
data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
@@ -434,6 +460,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
|
|
|
434
460
|
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
435
461
|
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
436
462
|
|
|
463
|
+
// Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
|
|
464
|
+
const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
|
|
465
|
+
|
|
437
466
|
// `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
|
|
438
467
|
const makeWorker = (options, allowScript) => {
|
|
439
468
|
if (options === undefined) {
|
|
@@ -466,6 +495,13 @@ const makeWorker = (options, allowScript) => {
|
|
|
466
495
|
let generation = 0;
|
|
467
496
|
let startingGeneration = 0;
|
|
468
497
|
let terminated = false;
|
|
498
|
+
// A worker created with createWorker() and then dropped without terminate() would keep its thread (and its memory) until
|
|
499
|
+
// the process or page ends: a running worker is never garbage-collected. So once the instance itself has been collected
|
|
500
|
+
// (`abandoned`), no call is in flight (`active`) and no handle is left (`liveHandles`), the thread is stopped. Nothing
|
|
501
|
+
// the worker's own listeners reach refers to `instance`, which is what lets it be collected while the thread runs.
|
|
502
|
+
let active = 0;
|
|
503
|
+
let liveHandles = 0;
|
|
504
|
+
let abandoned = false;
|
|
469
505
|
let nextId = 1;
|
|
470
506
|
let nextHandle = 1;
|
|
471
507
|
const pending = new Map();
|
|
@@ -489,6 +525,12 @@ const makeWorker = (options, allowScript) => {
|
|
|
489
525
|
// Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
|
|
490
526
|
// kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
|
|
491
527
|
const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
|
|
528
|
+
liveHandles--;
|
|
529
|
+
// The last thing keeping an abandoned worker going: stopping it frees everything, so there is nothing to release.
|
|
530
|
+
if (abandoned && liveHandles === 0) {
|
|
531
|
+
stopIfAbandoned();
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
492
534
|
if (!terminated) {
|
|
493
535
|
invoke('release', [id], [], new Error()).catch(() => {});
|
|
494
536
|
}
|
|
@@ -566,7 +608,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
566
608
|
|
|
567
609
|
// `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
|
|
568
610
|
// from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
|
|
569
|
-
const
|
|
611
|
+
const run = async (method, args, transferable, origin, controls = {}) => {
|
|
570
612
|
if (terminated) {
|
|
571
613
|
throw fail('worker-terminated', "Worker terminated.");
|
|
572
614
|
}
|
|
@@ -614,6 +656,23 @@ const makeWorker = (options, allowScript) => {
|
|
|
614
656
|
}
|
|
615
657
|
return post(method, args, transferable, origin, controls);
|
|
616
658
|
};
|
|
659
|
+
|
|
660
|
+
// Every call counts as in flight from the moment it is made (while the worker starts, too) until it settles, so an
|
|
661
|
+
// abandoned worker is never stopped under a call: `createWorker().getPalette(image)` keeps only the promise.
|
|
662
|
+
const invoke = (...args) => {
|
|
663
|
+
active++;
|
|
664
|
+
const settled = () => {
|
|
665
|
+
active--;
|
|
666
|
+
stopIfAbandoned();
|
|
667
|
+
};
|
|
668
|
+
return run(...args).then(value => {
|
|
669
|
+
settled();
|
|
670
|
+
return value;
|
|
671
|
+
}, error => {
|
|
672
|
+
settled();
|
|
673
|
+
throw error;
|
|
674
|
+
});
|
|
675
|
+
};
|
|
617
676
|
const post = (method, args, transferable, origin, {
|
|
618
677
|
signal,
|
|
619
678
|
onProgress
|
|
@@ -765,12 +824,16 @@ const makeWorker = (options, allowScript) => {
|
|
|
765
824
|
}
|
|
766
825
|
const id = nextHandle++;
|
|
767
826
|
const sent = ready() ? send(image) : take(send(image));
|
|
827
|
+
// Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
|
|
828
|
+
// existing (see `abandoned`).
|
|
829
|
+
liveHandles++;
|
|
768
830
|
try {
|
|
769
831
|
await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
|
|
770
832
|
signal,
|
|
771
833
|
onProgress
|
|
772
834
|
});
|
|
773
835
|
} catch (error) {
|
|
836
|
+
liveHandles--;
|
|
774
837
|
// A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
|
|
775
838
|
// would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
|
|
776
839
|
// is harmless, and this message follows the cluster call in the worker's queue.
|
|
@@ -819,6 +882,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
819
882
|
return;
|
|
820
883
|
}
|
|
821
884
|
released = true;
|
|
885
|
+
liveHandles--;
|
|
822
886
|
if (reclaim) {
|
|
823
887
|
reclaim.unregister(handle);
|
|
824
888
|
}
|
|
@@ -831,6 +895,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
831
895
|
throw error;
|
|
832
896
|
}
|
|
833
897
|
}
|
|
898
|
+
stopIfAbandoned();
|
|
834
899
|
}
|
|
835
900
|
};
|
|
836
901
|
// `await using handle = await worker.cluster(image)` releases it at the end of the block.
|
|
@@ -845,7 +910,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
845
910
|
};
|
|
846
911
|
|
|
847
912
|
// Stops the worker. Calls still waiting are rejected, and later calls fail.
|
|
848
|
-
|
|
913
|
+
const stop = async () => {
|
|
849
914
|
if (terminated) {
|
|
850
915
|
return;
|
|
851
916
|
}
|
|
@@ -863,6 +928,23 @@ const makeWorker = (options, allowScript) => {
|
|
|
863
928
|
} catch (ignored) {/* it never started */}
|
|
864
929
|
}
|
|
865
930
|
};
|
|
931
|
+
// An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
|
|
932
|
+
const stopIfAbandoned = () => {
|
|
933
|
+
if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
|
|
934
|
+
stop().catch(() => {});
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
instance.terminate = stop;
|
|
938
|
+
// `await using worker = createWorker()` terminates it at the end of the block.
|
|
939
|
+
if (typeof Symbol.asyncDispose === 'symbol') {
|
|
940
|
+
instance[Symbol.asyncDispose] = stop;
|
|
941
|
+
}
|
|
942
|
+
if (allowScript === false && abandonment) {
|
|
943
|
+
abandonment.register(instance, () => {
|
|
944
|
+
abandoned = true;
|
|
945
|
+
stopIfAbandoned();
|
|
946
|
+
});
|
|
947
|
+
}
|
|
866
948
|
return instance;
|
|
867
949
|
};
|
|
868
950
|
export const createWorker = options => makeWorker(options, false);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.6",
|
|
4
4
|
"description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Rohan Fredriksson",
|
|
@@ -50,9 +50,18 @@
|
|
|
50
50
|
}
|
|
51
51
|
},
|
|
52
52
|
"./worker": {
|
|
53
|
-
"
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
"import": {
|
|
54
|
+
"types": "./dist/worker.d.ts",
|
|
55
|
+
"default": "./dist/worker.mjs"
|
|
56
|
+
},
|
|
57
|
+
"require": {
|
|
58
|
+
"types": "./dist/worker.d.cts",
|
|
59
|
+
"default": "./dist/worker.cjs"
|
|
60
|
+
},
|
|
61
|
+
"default": {
|
|
62
|
+
"types": "./dist/worker.d.ts",
|
|
63
|
+
"default": "./dist/worker.mjs"
|
|
64
|
+
}
|
|
56
65
|
},
|
|
57
66
|
"./clustering.wasm": "./dist/clustering.wasm",
|
|
58
67
|
"./package.json": "./package.json"
|
|
@@ -73,9 +82,9 @@
|
|
|
73
82
|
],
|
|
74
83
|
"scripts": {
|
|
75
84
|
"build:wasm": "mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_get_palette','_get_palette_from_clustering','_get_palette_weights','_quantize','_quantize_with_clustering','_quantize_with_palette','_quantize_indices','_quantize_indices_with_clustering','_quantize_indices_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
|
|
76
|
-
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker
|
|
85
|
+
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker-thread.js\" --out-file-extension .cjs && node scripts/patch-cjs.mjs",
|
|
77
86
|
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
|
|
78
|
-
"build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts');\"",
|
|
87
|
+
"build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts'); fs.writeFileSync('dist/worker.d.cts', fs.readFileSync('src/worker.d.ts', 'utf8').replaceAll(\\\"'./index.js'\\\", \\\"'./index.cjs'\\\"));\"",
|
|
79
88
|
"build:js": "npm run build:types && npm run build:cjs && npm run build:esm",
|
|
80
89
|
"build": "node scripts/sync-version.mjs --check && npm run build:wasm && npm run build:js",
|
|
81
90
|
"version": "node scripts/sync-version.mjs && git add src/shared.js src/version.hpp",
|