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
package/dist/index.cjs
CHANGED
|
@@ -15,7 +15,20 @@ Object.defineProperty(exports, "Palette", {
|
|
|
15
15
|
return _shared.Palette;
|
|
16
16
|
}
|
|
17
17
|
});
|
|
18
|
-
|
|
18
|
+
Object.defineProperty(exports, "errorCodes", {
|
|
19
|
+
enumerable: true,
|
|
20
|
+
get: function () {
|
|
21
|
+
return _shared.errorCodes;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
|
|
25
|
+
Object.defineProperty(exports, "isCodedError", {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
get: function () {
|
|
28
|
+
return _shared.isCodedError;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = void 0;
|
|
19
32
|
Object.defineProperty(exports, "version", {
|
|
20
33
|
enumerable: true,
|
|
21
34
|
get: function () {
|
|
@@ -41,8 +54,6 @@ const formatVersion = exports.formatVersion = _shared.latestVersion;
|
|
|
41
54
|
// canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
|
|
42
55
|
// from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
|
|
43
56
|
const tagOf = value => Object.prototype.toString.call(value);
|
|
44
|
-
// (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
|
|
45
|
-
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
46
57
|
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
47
58
|
const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
|
|
48
59
|
const codes = {
|
|
@@ -116,6 +127,11 @@ const hasSimd = () => {
|
|
|
116
127
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
117
128
|
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
118
129
|
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
130
|
+
// A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
|
|
131
|
+
// Deno Deploy): only those have a document, a worker scope or a browser's user agent.
|
|
132
|
+
const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
|
|
133
|
+
// Where the advice for a server runtime ends: a deployment that left the .wasm behind.
|
|
134
|
+
const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
|
|
119
135
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
120
136
|
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
121
137
|
const wasmLoadFailed = (cause, given) => {
|
|
@@ -135,18 +151,51 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
135
151
|
// Where an explicit init({ wasm }) URL or path pointed, to name in the message.
|
|
136
152
|
const where = typeof given === 'string' ? ` (${given})` : '';
|
|
137
153
|
let advice;
|
|
138
|
-
if (/
|
|
154
|
+
if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
|
|
155
|
+
// Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
|
|
156
|
+
advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
|
|
157
|
+
} else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
|
|
158
|
+
// A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
|
|
159
|
+
// though it only uses what it needs; an address-space limit refuses that reservation.
|
|
160
|
+
advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
|
|
161
|
+
} else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
|
|
139
162
|
// Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
|
|
140
|
-
|
|
163
|
+
// Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
|
|
164
|
+
// does that for a script from another origin, a content script's included) follows the page's.
|
|
165
|
+
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
|
|
141
166
|
} else if (!hasSimd()) {
|
|
142
167
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
168
|
+
} else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
|
|
169
|
+
// What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
|
|
170
|
+
if (given === true) {
|
|
171
|
+
reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
|
|
172
|
+
advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
|
|
173
|
+
} else {
|
|
174
|
+
reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
|
|
175
|
+
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
|
|
176
|
+
}
|
|
177
|
+
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
|
|
178
|
+
// In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
|
|
179
|
+
reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
|
|
180
|
+
advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
|
|
143
181
|
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
|
|
144
182
|
reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
|
|
145
|
-
|
|
183
|
+
const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
|
|
184
|
+
advice = given ? `Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type.${blocked}` : `Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).${blocked}`;
|
|
146
185
|
} else if (given) {
|
|
147
186
|
advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
|
|
148
187
|
} else if (isNodeLike) {
|
|
149
|
-
|
|
188
|
+
// The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
|
|
189
|
+
if (/Invalid URL/i.test(reason)) {
|
|
190
|
+
reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
|
|
191
|
+
}
|
|
192
|
+
advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
|
|
193
|
+
} else if (!isBrowserLike()) {
|
|
194
|
+
// A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
|
|
195
|
+
if (/Invalid URL/i.test(reason)) {
|
|
196
|
+
reason = "the package can't tell where clustering.wasm is in this runtime";
|
|
197
|
+
}
|
|
198
|
+
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
|
|
150
199
|
} else {
|
|
151
200
|
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
152
201
|
}
|
|
@@ -212,6 +261,35 @@ const packagedWasm = async () => {
|
|
|
212
261
|
return readFile(file);
|
|
213
262
|
};
|
|
214
263
|
|
|
264
|
+
// In Node, init({ wasm }) given a path or a file: URL reads the file here and hands the glue its bytes. The glue reads files
|
|
265
|
+
// itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
|
|
266
|
+
// (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
|
|
267
|
+
// Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
|
|
268
|
+
const nodeWasmFile = async wasm => {
|
|
269
|
+
if (!isNodeLike) {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
|
|
273
|
+
if (text === null) {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
const isFileUrl = /^file:/i.test(text);
|
|
277
|
+
// A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
|
|
278
|
+
if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
const {
|
|
282
|
+
readFile
|
|
283
|
+
} = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
284
|
+
if (!isFileUrl) {
|
|
285
|
+
return readFile(text);
|
|
286
|
+
}
|
|
287
|
+
const {
|
|
288
|
+
fileURLToPath
|
|
289
|
+
} = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
|
|
290
|
+
return readFile(fileURLToPath(text));
|
|
291
|
+
};
|
|
292
|
+
|
|
215
293
|
// The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
|
|
216
294
|
let loading = null;
|
|
217
295
|
|
|
@@ -240,7 +318,8 @@ const acquire = async options => {
|
|
|
240
318
|
loading = (async () => {
|
|
241
319
|
let instance;
|
|
242
320
|
try {
|
|
243
|
-
|
|
321
|
+
const file = await nodeWasmFile(wasm);
|
|
322
|
+
instance = await instantiate(file === null ? wasm : file);
|
|
244
323
|
} catch (error) {
|
|
245
324
|
// In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
|
|
246
325
|
// build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
|
|
@@ -407,10 +486,11 @@ const load = image => {
|
|
|
407
486
|
format: 'rgba'
|
|
408
487
|
};
|
|
409
488
|
}
|
|
410
|
-
if (isImageData(image)) {
|
|
489
|
+
if ((0, _shared.isImageData)(image)) {
|
|
411
490
|
if ((0, _shared.isDetached)(image.data)) {
|
|
412
491
|
throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
|
|
413
492
|
}
|
|
493
|
+
(0, _shared.checkImageDataPixels)(image);
|
|
414
494
|
return {
|
|
415
495
|
data: held(bytes(image.data)),
|
|
416
496
|
format: 'rgba',
|
|
@@ -449,7 +529,7 @@ const load = image => {
|
|
|
449
529
|
};
|
|
450
530
|
};
|
|
451
531
|
const getWrapper = image => {
|
|
452
|
-
if (isImageData(image)) {
|
|
532
|
+
if ((0, _shared.isImageData)(image)) {
|
|
453
533
|
// In the input's own class and colour space (see imageDataLike).
|
|
454
534
|
return output => (0, _shared.imageDataLike)(image, new Uint8ClampedArray(output.buffer));
|
|
455
535
|
}
|
|
@@ -642,6 +722,25 @@ const checkNotEmpty = (palette, image, cutoff) => {
|
|
|
642
722
|
// The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
|
|
643
723
|
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
|
|
644
724
|
|
|
725
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
726
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
727
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
|
|
728
|
+
const maxBytes = 2 ** 31;
|
|
729
|
+
const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
730
|
+
const tooLarge = bytes => (0, _shared.fail)('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
731
|
+
|
|
732
|
+
// Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
|
|
733
|
+
const allocate = (wasm, length) => {
|
|
734
|
+
if (length >= maxBytes) {
|
|
735
|
+
throw tooLarge(length);
|
|
736
|
+
}
|
|
737
|
+
const pointer = wasm._malloc(length);
|
|
738
|
+
if (!pointer) {
|
|
739
|
+
throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
|
|
740
|
+
}
|
|
741
|
+
return pointer;
|
|
742
|
+
};
|
|
743
|
+
|
|
645
744
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
646
745
|
// freeing everything afterwards.
|
|
647
746
|
const call = (wasm, buffers, fn) => {
|
|
@@ -650,10 +749,7 @@ const call = (wasm, buffers, fn) => {
|
|
|
650
749
|
let aborted = false;
|
|
651
750
|
try {
|
|
652
751
|
for (const buffer of buffers) {
|
|
653
|
-
const pointer = wasm
|
|
654
|
-
if (!pointer) {
|
|
655
|
-
throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
|
|
656
|
-
}
|
|
752
|
+
const pointer = allocate(wasm, buffer.length);
|
|
657
753
|
pointers.push(pointer);
|
|
658
754
|
wasm.HEAPU8.set(buffer, pointer);
|
|
659
755
|
}
|
|
@@ -738,10 +834,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
|
738
834
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
739
835
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
740
836
|
checkAborted(o.signal);
|
|
741
|
-
const imagePointer = wasm
|
|
742
|
-
if (!imagePointer) {
|
|
743
|
-
throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
|
|
744
|
-
}
|
|
837
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
745
838
|
let job = 0;
|
|
746
839
|
let aborted = false;
|
|
747
840
|
try {
|
package/dist/index.d.cts
CHANGED
|
@@ -19,7 +19,7 @@ export type ErrorCode = 'invalid-argument' | 'invalid-clustering' | 'unsupported
|
|
|
19
19
|
*/
|
|
20
20
|
export type ErrorArgument = 'image' | 'k' | 'clustering' | 'palette' | 'colorSpace' | 'options' | `options.${string}`;
|
|
21
21
|
|
|
22
|
-
/** An `Error` thrown by this library. There is no class to test with `instanceof`: check `code`. */
|
|
22
|
+
/** An `Error` thrown by this library. There is no class to test with `instanceof`: use `isCodedError`, or check `code`. */
|
|
23
23
|
export interface CodedError extends Error {
|
|
24
24
|
code: ErrorCode;
|
|
25
25
|
/**
|
|
@@ -30,6 +30,17 @@ export interface CodedError extends Error {
|
|
|
30
30
|
argument?: ErrorArgument;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** Every `ErrorCode`, in a frozen array: for code that forwards or lists them (a wrapper package, an IPC bridge). */
|
|
34
|
+
export const errorCodes: readonly ErrorCode[];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether `value` is one of this library's errors: something with a string `message` and a `code` from `errorCodes`.
|
|
38
|
+
* Unlike checking `code` alone, it is false for Node's own errors (`'ENOENT'`) and for an abort (the signal's reason).
|
|
39
|
+
* It also accepts a plain object with those fields, which is what an error becomes after Electron's IPC or a
|
|
40
|
+
* `postMessage`; such an object has no `stack`, and is not an `instanceof Error`.
|
|
41
|
+
*/
|
|
42
|
+
export function isCodedError(value: unknown): value is CodedError;
|
|
43
|
+
|
|
33
44
|
/**
|
|
34
45
|
* An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
|
|
35
46
|
* `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
|
package/dist/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export type ErrorCode = 'invalid-argument' | 'invalid-clustering' | 'unsupported
|
|
|
19
19
|
*/
|
|
20
20
|
export type ErrorArgument = 'image' | 'k' | 'clustering' | 'palette' | 'colorSpace' | 'options' | `options.${string}`;
|
|
21
21
|
|
|
22
|
-
/** An `Error` thrown by this library. There is no class to test with `instanceof`: check `code`. */
|
|
22
|
+
/** An `Error` thrown by this library. There is no class to test with `instanceof`: use `isCodedError`, or check `code`. */
|
|
23
23
|
export interface CodedError extends Error {
|
|
24
24
|
code: ErrorCode;
|
|
25
25
|
/**
|
|
@@ -30,6 +30,17 @@ export interface CodedError extends Error {
|
|
|
30
30
|
argument?: ErrorArgument;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** Every `ErrorCode`, in a frozen array: for code that forwards or lists them (a wrapper package, an IPC bridge). */
|
|
34
|
+
export const errorCodes: readonly ErrorCode[];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether `value` is one of this library's errors: something with a string `message` and a `code` from `errorCodes`.
|
|
38
|
+
* Unlike checking `code` alone, it is false for Node's own errors (`'ENOENT'`) and for an abort (the signal's reason).
|
|
39
|
+
* It also accepts a plain object with those fields, which is what an error becomes after Electron's IPC or a
|
|
40
|
+
* `postMessage`; such an object has no `stack`, and is not an `instanceof Error`.
|
|
41
|
+
*/
|
|
42
|
+
export function isCodedError(value: unknown): value is CodedError;
|
|
43
|
+
|
|
33
44
|
/**
|
|
34
45
|
* An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
|
|
35
46
|
* `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike } from "./shared.mjs";
|
|
2
|
+
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
|
|
3
3
|
|
|
4
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
|
-
export { version, Palette, Clustering } from "./shared.mjs";
|
|
5
|
+
export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
|
|
6
6
|
// The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
|
|
7
7
|
// `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
|
|
8
8
|
export const formatVersion = latestVersion;
|
|
@@ -11,8 +11,6 @@ export const formatVersion = latestVersion;
|
|
|
11
11
|
// canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
|
|
12
12
|
// from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
|
|
13
13
|
const tagOf = value => Object.prototype.toString.call(value);
|
|
14
|
-
// (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
|
|
15
|
-
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
16
14
|
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
17
15
|
const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
|
|
18
16
|
const codes = {
|
|
@@ -86,6 +84,11 @@ const hasSimd = () => {
|
|
|
86
84
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
87
85
|
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
88
86
|
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
87
|
+
// A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
|
|
88
|
+
// Deno Deploy): only those have a document, a worker scope or a browser's user agent.
|
|
89
|
+
const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
|
|
90
|
+
// Where the advice for a server runtime ends: a deployment that left the .wasm behind.
|
|
91
|
+
const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
|
|
89
92
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
90
93
|
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
91
94
|
const wasmLoadFailed = (cause, given) => {
|
|
@@ -105,18 +108,51 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
105
108
|
// Where an explicit init({ wasm }) URL or path pointed, to name in the message.
|
|
106
109
|
const where = typeof given === 'string' ? ` (${given})` : '';
|
|
107
110
|
let advice;
|
|
108
|
-
if (/
|
|
111
|
+
if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
|
|
112
|
+
// Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
|
|
113
|
+
advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
|
|
114
|
+
} else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
|
|
115
|
+
// A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
|
|
116
|
+
// though it only uses what it needs; an address-space limit refuses that reservation.
|
|
117
|
+
advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
|
|
118
|
+
} else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
|
|
109
119
|
// Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
|
|
110
|
-
|
|
120
|
+
// Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
|
|
121
|
+
// does that for a script from another origin, a content script's included) follows the page's.
|
|
122
|
+
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
|
|
111
123
|
} else if (!hasSimd()) {
|
|
112
124
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
125
|
+
} else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
|
|
126
|
+
// What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
|
|
127
|
+
if (given === true) {
|
|
128
|
+
reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
|
|
129
|
+
advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
|
|
130
|
+
} else {
|
|
131
|
+
reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
|
|
132
|
+
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
|
|
133
|
+
}
|
|
134
|
+
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
|
|
135
|
+
// In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
|
|
136
|
+
reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
|
|
137
|
+
advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
|
|
113
138
|
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
|
|
114
139
|
reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
|
|
115
|
-
|
|
140
|
+
const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
|
|
141
|
+
advice = given ? `Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type.${blocked}` : `Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).${blocked}`;
|
|
116
142
|
} else if (given) {
|
|
117
143
|
advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
|
|
118
144
|
} else if (isNodeLike) {
|
|
119
|
-
|
|
145
|
+
// The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
|
|
146
|
+
if (/Invalid URL/i.test(reason)) {
|
|
147
|
+
reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
|
|
148
|
+
}
|
|
149
|
+
advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
|
|
150
|
+
} else if (!isBrowserLike()) {
|
|
151
|
+
// A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
|
|
152
|
+
if (/Invalid URL/i.test(reason)) {
|
|
153
|
+
reason = "the package can't tell where clustering.wasm is in this runtime";
|
|
154
|
+
}
|
|
155
|
+
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
|
|
120
156
|
} else {
|
|
121
157
|
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
122
158
|
}
|
|
@@ -182,6 +218,35 @@ const packagedWasm = async () => {
|
|
|
182
218
|
return readFile(file);
|
|
183
219
|
};
|
|
184
220
|
|
|
221
|
+
// In Node, init({ wasm }) given a path or a file: URL reads the file here and hands the glue its bytes. The glue reads files
|
|
222
|
+
// itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
|
|
223
|
+
// (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
|
|
224
|
+
// Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
|
|
225
|
+
const nodeWasmFile = async wasm => {
|
|
226
|
+
if (!isNodeLike) {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
|
|
230
|
+
if (text === null) {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
const isFileUrl = /^file:/i.test(text);
|
|
234
|
+
// A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
|
|
235
|
+
if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
const {
|
|
239
|
+
readFile
|
|
240
|
+
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
241
|
+
if (!isFileUrl) {
|
|
242
|
+
return readFile(text);
|
|
243
|
+
}
|
|
244
|
+
const {
|
|
245
|
+
fileURLToPath
|
|
246
|
+
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
|
|
247
|
+
return readFile(fileURLToPath(text));
|
|
248
|
+
};
|
|
249
|
+
|
|
185
250
|
// The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
|
|
186
251
|
let loading = null;
|
|
187
252
|
|
|
@@ -210,7 +275,8 @@ const acquire = async options => {
|
|
|
210
275
|
loading = (async () => {
|
|
211
276
|
let instance;
|
|
212
277
|
try {
|
|
213
|
-
|
|
278
|
+
const file = await nodeWasmFile(wasm);
|
|
279
|
+
instance = await instantiate(file === null ? wasm : file);
|
|
214
280
|
} catch (error) {
|
|
215
281
|
// In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
|
|
216
282
|
// build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
|
|
@@ -380,6 +446,7 @@ const load = image => {
|
|
|
380
446
|
if (isDetached(image.data)) {
|
|
381
447
|
throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
|
|
382
448
|
}
|
|
449
|
+
checkImageDataPixels(image);
|
|
383
450
|
return {
|
|
384
451
|
data: held(bytes(image.data)),
|
|
385
452
|
format: 'rgba',
|
|
@@ -611,6 +678,25 @@ const checkNotEmpty = (palette, image, cutoff) => {
|
|
|
611
678
|
// The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
|
|
612
679
|
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
613
680
|
|
|
681
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
682
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
683
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
|
|
684
|
+
const maxBytes = 2 ** 31;
|
|
685
|
+
const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
686
|
+
const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
687
|
+
|
|
688
|
+
// Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
|
|
689
|
+
const allocate = (wasm, length) => {
|
|
690
|
+
if (length >= maxBytes) {
|
|
691
|
+
throw tooLarge(length);
|
|
692
|
+
}
|
|
693
|
+
const pointer = wasm._malloc(length);
|
|
694
|
+
if (!pointer) {
|
|
695
|
+
throw fail('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
|
|
696
|
+
}
|
|
697
|
+
return pointer;
|
|
698
|
+
};
|
|
699
|
+
|
|
614
700
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
615
701
|
// freeing everything afterwards.
|
|
616
702
|
const call = (wasm, buffers, fn) => {
|
|
@@ -619,10 +705,7 @@ const call = (wasm, buffers, fn) => {
|
|
|
619
705
|
let aborted = false;
|
|
620
706
|
try {
|
|
621
707
|
for (const buffer of buffers) {
|
|
622
|
-
const pointer = wasm
|
|
623
|
-
if (!pointer) {
|
|
624
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
625
|
-
}
|
|
708
|
+
const pointer = allocate(wasm, buffer.length);
|
|
626
709
|
pointers.push(pointer);
|
|
627
710
|
wasm.HEAPU8.set(buffer, pointer);
|
|
628
711
|
}
|
|
@@ -707,10 +790,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
|
707
790
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
708
791
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
709
792
|
checkAborted(o.signal);
|
|
710
|
-
const imagePointer = wasm
|
|
711
|
-
if (!imagePointer) {
|
|
712
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
713
|
-
}
|
|
793
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
714
794
|
let job = 0;
|
|
715
795
|
let aborted = false;
|
|
716
796
|
try {
|
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isDetached = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
|
|
9
|
+
exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '3.0.0-beta.
|
|
16
|
+
const version = exports.version = '3.0.0-beta.6';
|
|
17
17
|
const colorSpaces = exports.colorSpaces = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -26,7 +26,15 @@ const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
|
|
|
26
26
|
// 'worker-terminated', 'worker-failed' and 'invalid-handle'. When the error is about one argument, `argument` names it
|
|
27
27
|
// for programs (the message is for people): 'image', 'k', 'clustering', 'palette', 'options', or 'options.<key>' for
|
|
28
28
|
// one option.
|
|
29
|
+
// Every code `fail` gives, for programs that branch on them or forward them (a wrapper package, an IPC bridge).
|
|
29
30
|
exports.colorSpaceName = colorSpaceName;
|
|
31
|
+
const errorCodes = exports.errorCodes = Object.freeze(['invalid-argument', 'invalid-clustering', 'unsupported-version', 'out-of-memory', 'wasm-load-failed', 'worker-terminated', 'worker-failed', 'invalid-handle']);
|
|
32
|
+
|
|
33
|
+
// Whether `value` is one of this library's errors: an error (or, after crossing Electron's IPC or a postMessage, a plain
|
|
34
|
+
// object) with a string message and one of `errorCodes`. Checking `code` alone isn't enough: Node's own errors have a
|
|
35
|
+
// `code` too ('ENOENT'), and an abort rejects with the signal's reason, which has none.
|
|
36
|
+
const isCodedError = value => value !== null && typeof value === 'object' && typeof value.message === 'string' && typeof value.code === 'string' && errorCodes.includes(value.code);
|
|
37
|
+
exports.isCodedError = isCodedError;
|
|
30
38
|
const fail = (code, message, argument) => Object.assign(new Error(message), argument === undefined ? {
|
|
31
39
|
code
|
|
32
40
|
} : {
|
|
@@ -59,10 +67,27 @@ const isDetached = view => {
|
|
|
59
67
|
}
|
|
60
68
|
};
|
|
61
69
|
|
|
70
|
+
// An ImageData: checked by tag as well as `instanceof`, so one from another realm (an iframe's canvas) is recognised, and by
|
|
71
|
+
// its class's name with the shape of one, for implementations that have neither the tag nor the global (node-canvas under
|
|
72
|
+
// jsdom, skia-canvas, whose tag is plain [object Object]).
|
|
73
|
+
exports.isDetached = isDetached;
|
|
74
|
+
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
|
|
75
|
+
|
|
76
|
+
// ImageData can hold other pixel formats than 8-bit RGBA (Chromium's pixelFormat: 'rgba-float16', with a Float16Array of
|
|
77
|
+
// pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
|
|
78
|
+
exports.isImageData = isImageData;
|
|
79
|
+
const checkImageDataPixels = image => {
|
|
80
|
+
if (isUint8ClampedArray(image.data)) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
|
|
84
|
+
throw fail('invalid-argument', `Invalid image: this ImageData doesn't hold 8-bit RGBA pixels${format}, and the library reads only those. Ask for 8-bit pixels with getImageData(x, y, width, height, { pixelFormat: 'rgba-unorm8' }), or draw it to a canvas with the default format and take getImageData() from that.`, 'image');
|
|
85
|
+
};
|
|
86
|
+
|
|
62
87
|
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
63
88
|
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
64
89
|
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
65
|
-
exports.
|
|
90
|
+
exports.checkImageDataPixels = checkImageDataPixels;
|
|
66
91
|
const imageDataLike = (like, pixels) => {
|
|
67
92
|
const {
|
|
68
93
|
width,
|
|
@@ -334,7 +359,10 @@ const readHeader = clustering => {
|
|
|
334
359
|
if (version === 3 && length >= 13) {
|
|
335
360
|
const headerLength = clustering[2],
|
|
336
361
|
recordLength = clustering[3];
|
|
337
|
-
|
|
362
|
+
// Header lengths are 22 (every release) or 13 (the fixture from before 3.0.0-beta.1, kept readable by the format
|
|
363
|
+
// rules), or longer from a later release that adds fields. 14 to 20 was never written: it is a damaged length, which
|
|
364
|
+
// would also put the checksum field out of reach, so the checksum couldn't catch it.
|
|
365
|
+
if ((headerLength === 13 || headerLength >= checksumAt + 4) && recordLength >= 21 && headerLength <= length) {
|
|
338
366
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
339
367
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
340
368
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
@@ -343,8 +371,8 @@ const readHeader = clustering => {
|
|
|
343
371
|
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
344
372
|
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
345
373
|
if (padding < 9) {
|
|
346
|
-
//
|
|
347
|
-
//
|
|
374
|
+
// A 13-byte header (from before 3.0.0-beta.1) has no checksum field. A damaged header length of 13 skips this
|
|
375
|
+
// check, but then the records don't line up, which the replay reports.
|
|
348
376
|
if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
|
|
349
377
|
const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
|
|
350
378
|
if (stored !== 0 && stored !== crc32(clustering)) {
|