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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,14 +15,34 @@ Object.defineProperty(exports, "Palette", {
15
15
  return _shared.Palette;
16
16
  }
17
17
  });
18
- exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
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 () {
22
35
  return _shared.version;
23
36
  }
24
37
  });
25
- var _clustering = _interopRequireDefault(require("./clustering.js"));
38
+ var _clustering = _interopRequireDefault((() => {
39
+ try {
40
+ return require("./clustering.js");
41
+ } catch (error) {
42
+ // A module system that can't require() an ES module (Jest): the CommonJS copy of the glue.
43
+ return require("./clustering.cjs");
44
+ }
45
+ })());
26
46
  var _shared = require("./shared.cjs");
27
47
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
28
48
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
@@ -34,8 +54,6 @@ const formatVersion = exports.formatVersion = _shared.latestVersion;
34
54
  // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
35
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.
36
56
  const tagOf = value => Object.prototype.toString.call(value);
37
- // (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
38
- const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
39
57
  const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
40
58
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
41
59
  const codes = {
@@ -108,23 +126,54 @@ const hasSimd = () => {
108
126
  };
109
127
  // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
110
128
  // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
111
- const isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
129
+ const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
130
+ // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
131
+ const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
112
132
  const wasmLoadFailed = (cause, given) => {
113
133
  const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
114
- // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
115
- // and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
116
- let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
134
+ // Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
135
+ let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
117
136
  const aborted = /^Aborted\((.*)\)$/.exec(reason);
118
137
  if (aborted) {
119
138
  reason = aborted[1].replace(/\.+$/, '');
120
139
  }
140
+ // The cause keeps Emscripten's own message, without that advice.
141
+ if (cause && typeof cause.message === 'string' && assertionsAdvice.test(cause.message)) {
142
+ try {
143
+ cause.message = cause.message.replace(assertionsAdvice, '');
144
+ } catch (error) {/* read-only: leave it */}
145
+ }
146
+ // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
147
+ const where = typeof given === 'string' ? ` (${given})` : '';
121
148
  let advice;
122
- if (!hasSimd()) {
149
+ if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
150
+ // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
151
+ // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
152
+ // does that for a script from another origin, a content script's included) follows the page's.
153
+ 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.";
154
+ } else if (!hasSimd()) {
123
155
  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).";
156
+ } else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
157
+ // What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
158
+ if (given === true) {
159
+ reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
160
+ advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
161
+ } else {
162
+ 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`;
163
+ 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 }).";
164
+ }
165
+ } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
166
+ 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)';
167
+ 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).";
168
+ 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}`;
124
169
  } else if (given) {
125
- advice = "Check what init({ wasm }) was given: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).";
170
+ 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).`;
126
171
  } else if (isNodeLike) {
127
- advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
172
+ // The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
173
+ if (/Invalid URL/i.test(reason)) {
174
+ reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
175
+ }
176
+ 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.";
128
177
  } else {
129
178
  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 }).";
130
179
  }
@@ -186,10 +235,39 @@ const packagedWasm = async () => {
186
235
  const {
187
236
  readFile
188
237
  } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
189
- const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
238
+ const file = createRequire(`${globalThis.process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
190
239
  return readFile(file);
191
240
  };
192
241
 
242
+ // 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
243
+ // itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
244
+ // (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
245
+ // Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
246
+ const nodeWasmFile = async wasm => {
247
+ if (!isNodeLike) {
248
+ return null;
249
+ }
250
+ const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
251
+ if (text === null) {
252
+ return null;
253
+ }
254
+ const isFileUrl = /^file:/i.test(text);
255
+ // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
256
+ if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
257
+ return null;
258
+ }
259
+ const {
260
+ readFile
261
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
262
+ if (!isFileUrl) {
263
+ return readFile(text);
264
+ }
265
+ const {
266
+ fileURLToPath
267
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
268
+ return readFile(fileURLToPath(text));
269
+ };
270
+
193
271
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
194
272
  let loading = null;
195
273
 
@@ -218,14 +296,15 @@ const acquire = async options => {
218
296
  loading = (async () => {
219
297
  let instance;
220
298
  try {
221
- instance = await instantiate(wasm);
299
+ const file = await nodeWasmFile(wasm);
300
+ instance = await instantiate(file === null ? wasm : file);
222
301
  } catch (error) {
223
302
  // In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
224
303
  // build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
225
304
  // way Node resolves packages, from the working directory; if that fails too, the first error is reported.
226
305
  const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
227
306
  if (!fallback) {
228
- throw wasmLoadFailed(error, wasm !== undefined);
307
+ throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
229
308
  }
230
309
  instance = await instantiate(fallback).catch(() => {
231
310
  throw wasmLoadFailed(error, false);
@@ -345,20 +424,6 @@ const sniffImageFormat = bytes => {
345
424
  return null;
346
425
  };
347
426
 
348
- // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
349
- const isDetached = view => {
350
- const buffer = view.buffer;
351
- if (typeof buffer.detached === 'boolean') {
352
- return buffer.detached;
353
- }
354
- try {
355
- new Uint8Array(buffer, 0, 0);
356
- return false;
357
- } catch (error) {
358
- return true;
359
- }
360
- };
361
-
362
427
  // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
363
428
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
364
429
  // call returns; until then (the first call) a copy is kept for when it has loaded.
@@ -383,7 +448,7 @@ const load = image => {
383
448
  const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
384
449
  throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
385
450
  }
386
- if (ArrayBuffer.isView(image) && isDetached(image)) {
451
+ if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
387
452
  throw (0, _shared.fail)('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
388
453
  }
389
454
  if ((0, _shared.isUint8Array)(image)) {
@@ -399,8 +464,8 @@ const load = image => {
399
464
  format: 'rgba'
400
465
  };
401
466
  }
402
- if (isImageData(image)) {
403
- if (isDetached(image.data)) {
467
+ if ((0, _shared.isImageData)(image)) {
468
+ if ((0, _shared.isDetached)(image.data)) {
404
469
  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');
405
470
  }
406
471
  return {
@@ -418,7 +483,7 @@ const load = image => {
418
483
  if (!(0, _shared.isUint8Array)(image.data) && !(0, _shared.isUint8ClampedArray)(image.data)) {
419
484
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
420
485
  }
421
- if (isDetached(image.data)) {
486
+ if ((0, _shared.isDetached)(image.data)) {
422
487
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
423
488
  }
424
489
  if (!Object.keys(codes).includes(image.format)) {
@@ -441,16 +506,9 @@ const load = image => {
441
506
  };
442
507
  };
443
508
  const getWrapper = image => {
444
- if (isImageData(image)) {
445
- // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
446
- const {
447
- width,
448
- height,
449
- colorSpace
450
- } = image;
451
- return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
452
- colorSpace
453
- } : undefined);
509
+ if ((0, _shared.isImageData)(image)) {
510
+ // In the input's own class and colour space (see imageDataLike).
511
+ return output => (0, _shared.imageDataLike)(image, new Uint8ClampedArray(output.buffer));
454
512
  }
455
513
  if (!(0, _shared.isUint8Array)(image) && typeof image === 'object' && image && image.data && image.format) {
456
514
  const {
@@ -848,7 +906,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
848
906
  k = check(k);
849
907
  noOptions('getSwatchesFromClustering', extra);
850
908
  if (header.version < 3) {
851
- throw (0, _shared.fail)('unsupported-version', `Invalid clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
909
+ throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
852
910
  }
853
911
  clustering = held(clustering);
854
912
  const wasm = Module || (await acquire());
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 } 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 } 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 = {
@@ -85,23 +83,54 @@ const hasSimd = () => {
85
83
  };
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
- const isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
86
+ const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
87
+ // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
88
+ const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
89
89
  const wasmLoadFailed = (cause, given) => {
90
90
  const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
91
- // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
92
- // and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
93
- let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
91
+ // Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
92
+ let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
94
93
  const aborted = /^Aborted\((.*)\)$/.exec(reason);
95
94
  if (aborted) {
96
95
  reason = aborted[1].replace(/\.+$/, '');
97
96
  }
97
+ // The cause keeps Emscripten's own message, without that advice.
98
+ if (cause && typeof cause.message === 'string' && assertionsAdvice.test(cause.message)) {
99
+ try {
100
+ cause.message = cause.message.replace(assertionsAdvice, '');
101
+ } catch (error) {/* read-only: leave it */}
102
+ }
103
+ // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
104
+ const where = typeof given === 'string' ? ` (${given})` : '';
98
105
  let advice;
99
- if (!hasSimd()) {
106
+ if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
107
+ // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
108
+ // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
109
+ // does that for a script from another origin, a content script's included) follows the page's.
110
+ 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
+ } else if (!hasSimd()) {
100
112
  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).";
113
+ } else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
114
+ // What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
115
+ if (given === true) {
116
+ reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
117
+ advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
118
+ } else {
119
+ 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`;
120
+ 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 }).";
121
+ }
122
+ } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
123
+ 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)';
124
+ 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).";
125
+ 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}`;
101
126
  } else if (given) {
102
- advice = "Check what init({ wasm }) was given: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).";
127
+ 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).`;
103
128
  } else if (isNodeLike) {
104
- advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
129
+ // The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
130
+ if (/Invalid URL/i.test(reason)) {
131
+ reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
132
+ }
133
+ 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.";
105
134
  } else {
106
135
  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 }).";
107
136
  }
@@ -163,10 +192,39 @@ const packagedWasm = async () => {
163
192
  const {
164
193
  readFile
165
194
  } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
166
- const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
195
+ const file = createRequire(`${globalThis.process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
167
196
  return readFile(file);
168
197
  };
169
198
 
199
+ // 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
200
+ // itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
201
+ // (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
202
+ // Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
203
+ const nodeWasmFile = async wasm => {
204
+ if (!isNodeLike) {
205
+ return null;
206
+ }
207
+ const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
208
+ if (text === null) {
209
+ return null;
210
+ }
211
+ const isFileUrl = /^file:/i.test(text);
212
+ // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
213
+ if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
214
+ return null;
215
+ }
216
+ const {
217
+ readFile
218
+ } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
219
+ if (!isFileUrl) {
220
+ return readFile(text);
221
+ }
222
+ const {
223
+ fileURLToPath
224
+ } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
225
+ return readFile(fileURLToPath(text));
226
+ };
227
+
170
228
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
171
229
  let loading = null;
172
230
 
@@ -195,14 +253,15 @@ const acquire = async options => {
195
253
  loading = (async () => {
196
254
  let instance;
197
255
  try {
198
- instance = await instantiate(wasm);
256
+ const file = await nodeWasmFile(wasm);
257
+ instance = await instantiate(file === null ? wasm : file);
199
258
  } catch (error) {
200
259
  // In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
201
260
  // build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
202
261
  // way Node resolves packages, from the working directory; if that fails too, the first error is reported.
203
262
  const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
204
263
  if (!fallback) {
205
- throw wasmLoadFailed(error, wasm !== undefined);
264
+ throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
206
265
  }
207
266
  instance = await instantiate(fallback).catch(() => {
208
267
  throw wasmLoadFailed(error, false);
@@ -321,20 +380,6 @@ const sniffImageFormat = bytes => {
321
380
  return null;
322
381
  };
323
382
 
324
- // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
325
- const isDetached = view => {
326
- const buffer = view.buffer;
327
- if (typeof buffer.detached === 'boolean') {
328
- return buffer.detached;
329
- }
330
- try {
331
- new Uint8Array(buffer, 0, 0);
332
- return false;
333
- } catch (error) {
334
- return true;
335
- }
336
- };
337
-
338
383
  // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
339
384
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
340
385
  // call returns; until then (the first call) a copy is kept for when it has loaded.
@@ -418,15 +463,8 @@ const load = image => {
418
463
  };
419
464
  const getWrapper = image => {
420
465
  if (isImageData(image)) {
421
- // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
422
- const {
423
- width,
424
- height,
425
- colorSpace
426
- } = image;
427
- return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
428
- colorSpace
429
- } : undefined);
466
+ // In the input's own class and colour space (see imageDataLike).
467
+ return output => imageDataLike(image, new Uint8ClampedArray(output.buffer));
430
468
  }
431
469
  if (!isUint8Array(image) && typeof image === 'object' && image && image.data && image.format) {
432
470
  const {
@@ -821,7 +859,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
821
859
  k = check(k);
822
860
  noOptions('getSwatchesFromClustering', extra);
823
861
  if (header.version < 3) {
824
- throw fail('unsupported-version', `Invalid clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
862
+ throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
825
863
  }
826
864
  clustering = held(clustering);
827
865
  const wasm = Module || (await acquire());
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.isClustering = exports.isArrayBufferLike = exports.imageHint = 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 = 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.3';
16
+ const version = exports.version = '3.0.0-beta.5';
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
  } : {
@@ -44,8 +52,49 @@ const isUint8ClampedArray = value => ArrayBuffer.isView(value) && tag(value) ===
44
52
  exports.isUint8ClampedArray = isUint8ClampedArray;
45
53
  const isArrayBufferLike = value => tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
46
54
 
47
- // What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
55
+ // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
48
56
  exports.isArrayBufferLike = isArrayBufferLike;
57
+ const isDetached = view => {
58
+ const buffer = view.buffer;
59
+ if (typeof buffer.detached === 'boolean') {
60
+ return buffer.detached;
61
+ }
62
+ try {
63
+ new Uint8Array(buffer, 0, 0);
64
+ return false;
65
+ } catch (error) {
66
+ return true;
67
+ }
68
+ };
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
+ // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
77
+ // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
78
+ // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
79
+ exports.isImageData = isImageData;
80
+ const imageDataLike = (like, pixels) => {
81
+ const {
82
+ width,
83
+ height,
84
+ colorSpace
85
+ } = like;
86
+ const own = like.constructor;
87
+ const make = typeof own === 'function' && own.name === 'ImageData' ? own : typeof ImageData === 'function' ? ImageData : null;
88
+ if (!make) {
89
+ throw fail('invalid-argument', "Invalid image: an ImageData whose class can't be used to make the result. Pass { data, format: 'rgba', width } instead.", 'image');
90
+ }
91
+ return colorSpace ? new make(pixels, width, height, {
92
+ colorSpace
93
+ }) : new make(pixels, width, height);
94
+ };
95
+
96
+ // What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
97
+ exports.imageDataLike = imageDataLike;
49
98
  const imageHint = image => {
50
99
  const decode = " Decode it to pixels first, then pass them.";
51
100
  if (image === undefined || image === null) {
@@ -303,7 +352,7 @@ const readHeader = clustering => {
303
352
  // A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
304
353
  // doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
305
354
  if (clustering[4] > 1 || clustering[6] > 1) {
306
- throw fail('unsupported-version', "Invalid clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
355
+ throw fail('unsupported-version', "Unsupported clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
307
356
  }
308
357
  const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
309
358
  const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
@@ -330,7 +379,7 @@ const readHeader = clustering => {
330
379
  }
331
380
  }
332
381
  if (version > latestVersion) {
333
- throw fail('unsupported-version', `Invalid clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
382
+ throw fail('unsupported-version', `Unsupported clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
334
383
  }
335
384
  }
336
385
  throw notAClustering(clustering);
@@ -346,6 +395,9 @@ const checkPalette = palette => {
346
395
  if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
347
396
  throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
348
397
  }
398
+ if (Array.isArray(palette) && palette.some(value => Array.isArray(value) || ArrayBuffer.isView(value))) {
399
+ throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255, not an array of [r, g, b] colours. Flatten it first: colours.flat().", 'palette');
400
+ }
349
401
  if (palette.length % 3 !== 0) {
350
402
  throw fail('invalid-argument', "Invalid palette: length must be a multiple of 3 (flat RGB bytes).", 'palette');
351
403
  }