agglomerative-clustering 3.1.1 → 3.3.0

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 CHANGED
@@ -70,17 +70,17 @@ shares.forEach((share, i) => {
70
70
  **A colour-count slider:** cluster once, then cut and map as often as you like.
71
71
 
72
72
  ```js
73
- import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
73
+ import { getClustering, quantizeWithPalette } from 'agglomerative-clustering';
74
74
 
75
75
  const clustering = await getClustering(imageData); // the expensive step, done once
76
76
 
77
77
  slider.oninput = async () => {
78
- const palette = await getPaletteFromClustering(clustering, Number(slider.value)); // ~0.4 ms for any k
79
- ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
78
+ const palette = await clustering.getPalette(Number(slider.value)); // ~0.4 ms for any k
79
+ ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
80
80
  };
81
81
  ```
82
82
 
83
- Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba', width?, height? }`. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same functions from `agglomerative-clustering/worker` (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)).
83
+ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
84
84
 
85
85
  ## How it works
86
86
 
@@ -92,14 +92,19 @@ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `
92
92
 
93
93
  The one-shot functions (`getPalette`, `quantize`, …) do every step for you. To try many palette sizes, call `getClustering` once and cut it as often as you like.
94
94
 
95
- | You want | from the image | from a clustering you hold | with a palette you supply |
95
+ | You want | from the image | from a clustering you hold¹ | with a palette you supply |
96
96
  |---|---|---|---|
97
- | a palette (flat RGB) | `getPalette` | `getPaletteFromClustering` | |
98
- | a palette with each colour's share | `getSwatches` | `getSwatchesFromClustering` | |
99
- | the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
100
- | palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
97
+ | a palette (flat RGB) | `getPalette` | `clustering.getPalette(k)` (`getPaletteFromClustering`) | |
98
+ | a palette with each colour's share | `getSwatches` | `clustering.getSwatches(k)` (`getSwatchesFromClustering`) | |
99
+ | the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` (`quantizeFromClustering`) | `quantizeWithPalette` |
100
+ | palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` (`quantizeToIndicesFromClustering`) | `quantizeToIndicesWithPalette` |
101
+ | its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` (`getClusteringInfo`) | |
101
102
 
102
- **`…FromClustering`** takes the colours from a clustering you already hold, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `getClustering` builds a clustering, `getClusteringInfo` reads one (including its error curve, for choosing a palette size), and `init` loads the WebAssembly module (optional). Most code only needs the first column.
103
+ A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `getClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
104
+
105
+ **Methods or functions?** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **In a worker, use a handle** (`createWorker().cluster(image)`, below) or the worker entry's function forms: the methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
106
+
107
+ ¹ Each method has a function form, in brackets, that does the same. The cuts take the clustering first (`getPaletteFromClustering(clustering, k)`); the mapping functions take the image first and the clustering second (`quantizeFromClustering(image, clustering, k)`). See [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
103
108
 
104
109
  Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
105
110
 
@@ -1,3 +1,3 @@
1
1
  "use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
2
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
3
3
  ;return Module}module.exports=createWasmModule;
@@ -1,2 +1,2 @@
1
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
1
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
2
  ;return Module}export default createWasmModule;
Binary file
package/dist/index.cjs CHANGED
@@ -89,7 +89,31 @@ const isWasmModule = value => typeof value === 'object' && value !== null && (ty
89
89
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
90
90
  const codes = {
91
91
  'rgba': 0,
92
- 'rgb': 1
92
+ 'rgb': 1,
93
+ 'bgra': 2,
94
+ 'rgbx': 3,
95
+ 'bgrx': 4
96
+ };
97
+ // A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
98
+ // supported layout.
99
+ const formatHint = format => {
100
+ if (typeof format !== 'string') {
101
+ return '';
102
+ }
103
+ const lower = format.toLowerCase();
104
+ if (lower !== format && _shared.imageFormats.includes(lower)) {
105
+ return ` Format names are lower case: '${lower}'.`;
106
+ }
107
+ if (lower === 'xrgb' || lower === 'rgb24') {
108
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
109
+ }
110
+ if (lower === 'argb' || lower === 'argb32') {
111
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
112
+ }
113
+ if (lower === 'bgr' || lower === 'bgr24') {
114
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
115
+ }
116
+ return '';
93
117
  };
94
118
  const alphaModeCodes = {
95
119
  'ignore': 0,
@@ -205,6 +229,10 @@ const wasmLoadFailed = (cause, given) => {
205
229
  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`;
206
230
  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 }).";
207
231
  }
232
+ } else if (/dynamically imported module|node:module/i.test(text)) {
233
+ // The glue took its Node path somewhere that has Node's globals but not Node's module loader.
234
+ reason = `Node's module loader isn't available here, in a page or worker with Node's globals but not its loader (${reason})`;
235
+ advice = "Load the package where it can take its browser path, or report this environment as an issue.";
208
236
  } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
209
237
  // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
210
238
  reason = `the .wasm file could not be fetched${where}: ${reason}`;
@@ -530,7 +558,7 @@ const load = image => {
530
558
  throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
531
559
  }
532
560
  if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
533
- 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');
561
+ throw (0, _shared.detachedError)('bare');
534
562
  }
535
563
  if ((0, _shared.isUint8Array)(image)) {
536
564
  const encoded = sniffImageFormat(image);
@@ -547,7 +575,7 @@ const load = image => {
547
575
  }
548
576
  if ((0, _shared.isImageData)(image)) {
549
577
  if ((0, _shared.isDetached)(image.data)) {
550
- 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');
578
+ throw (0, _shared.detachedError)('imagedata');
551
579
  }
552
580
  (0, _shared.checkImageDataPixels)(image);
553
581
  return {
@@ -566,16 +594,16 @@ const load = image => {
566
594
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
567
595
  }
568
596
  if ((0, _shared.isDetached)(image.data)) {
569
- 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');
597
+ throw (0, _shared.detachedError)('data');
570
598
  }
571
- if (!Object.keys(codes).includes(image.format)) {
572
- throw (0, _shared.fail)('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
599
+ if (!_shared.imageFormats.includes(image.format)) {
600
+ throw (0, _shared.fail)('invalid-argument', `Invalid format: got ${(0, _shared.describe)(image.format)}; it must be ${_shared.formatNames}.${formatHint(image.format)}`, 'image');
573
601
  }
574
- const channels = image.format === 'rgb' ? 3 : 4;
575
- if (image.data.length % channels !== 0) {
576
- throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
602
+ const stride = (0, _shared.channels)(image.format);
603
+ if (image.data.length % stride !== 0) {
604
+ throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
577
605
  }
578
- const pixels = image.data.length / channels;
606
+ const pixels = image.data.length / stride;
579
607
  checkSize(pixels, image.width, 'image width', 'image');
580
608
  checkSize(pixels, image.height, 'image height', 'image');
581
609
  if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
@@ -712,15 +740,15 @@ const parseOptions = (options, allowed, image) => {
712
740
  throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
713
741
  }
714
742
  if (options.width !== undefined && image) {
715
- checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
743
+ checkSize(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
716
744
  }
717
745
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
718
746
  if (dither > 0) {
719
- const channels = image.format === 'rgb' ? 3 : 4;
747
+ const stride = (0, _shared.channels)(image.format);
720
748
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
721
749
  throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
722
750
  }
723
- if (image.data.length / channels % width !== 0) {
751
+ if (image.data.length / stride % width !== 0) {
724
752
  throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
725
753
  }
726
754
  }
@@ -776,8 +804,8 @@ const checkNotEmpty = (palette, image, cutoff) => {
776
804
  return;
777
805
  }
778
806
  const data = image.data;
779
- let visible = image.format === 'rgb' ? data.length > 0 : false;
780
- for (let i = 3; !visible && i < data.length; i += 4) {
807
+ let visible = (0, _shared.hasAlpha)(image.format) ? false : data.length > 0;
808
+ for (let i = 3; !visible && (0, _shared.hasAlpha)(image.format) && i < data.length; i += 4) {
781
809
  visible = data[i] >= cutoff;
782
810
  }
783
811
  if (visible) {
@@ -935,9 +963,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
935
963
 
936
964
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
937
965
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
966
+ // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
967
+ // the method form of mapping.
938
968
  const noOptions = (name, extra) => {
939
969
  if (extra.some(value => value !== undefined)) {
940
- throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use quantizeFromClustering.`, 'options');
970
+ const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
971
+ throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use ${alternative}.`, 'options');
941
972
  }
942
973
  };
943
974
 
@@ -973,15 +1004,18 @@ const getPalette = async (image, k, options) => {
973
1004
  }
974
1005
  return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), (0, _shared.colorSpaceName)(o.colorSpace));
975
1006
  };
1007
+
1008
+ // The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
976
1009
  exports.getPalette = getPalette;
977
- const getPaletteFromClustering = async (clustering, k, ...extra) => {
1010
+ const cutPalette = async (name, clustering, k, extra) => {
978
1011
  const header = (0, _shared.readHeader)(clustering);
979
1012
  k = check(k);
980
- noOptions('getPaletteFromClustering', extra);
1013
+ noOptions(name, extra);
981
1014
  clustering = held(clustering);
982
1015
  const wasm = Module || (await acquire());
983
1016
  return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
984
1017
  };
1018
+ const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
985
1019
 
986
1020
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
987
1021
  exports.getPaletteFromClustering = getPaletteFromClustering;
@@ -1004,10 +1038,10 @@ const needsWeights = header => {
1004
1038
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
1005
1039
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
1006
1040
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1007
- const getSwatchesFromClustering = async (clustering, k, ...extra) => {
1041
+ const cutSwatches = async (name, clustering, k, extra) => {
1008
1042
  const header = (0, _shared.readHeader)(clustering);
1009
1043
  k = check(k);
1010
- noOptions('getSwatchesFromClustering', extra);
1044
+ noOptions(name, extra);
1011
1045
  needsWeights(header);
1012
1046
  clustering = held(clustering);
1013
1047
  const wasm = Module || (await acquire());
@@ -1029,6 +1063,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
1029
1063
  shares
1030
1064
  };
1031
1065
  };
1066
+ const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
1032
1067
 
1033
1068
  // The same for an image: clusters it, then cuts, like getPalette.
1034
1069
  exports.getSwatchesFromClustering = getSwatchesFromClustering;
@@ -1043,9 +1078,9 @@ const getSwatches = async (image, k, options) => {
1043
1078
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
1044
1079
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
1045
1080
  exports.getSwatches = getSwatches;
1046
- const getClusteringInfo = async (clustering, ...extra) => {
1081
+ const readInfo = async (name, clustering, extra) => {
1047
1082
  const header = (0, _shared.readHeader)(clustering);
1048
- noOptions('getClusteringInfo', extra);
1083
+ noOptions(name, extra);
1049
1084
  needsWeights(header);
1050
1085
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
1051
1086
  const info = {
@@ -1086,6 +1121,7 @@ const getClusteringInfo = async (clustering, ...extra) => {
1086
1121
  }
1087
1122
  return info;
1088
1123
  };
1124
+ const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1089
1125
  exports.getClusteringInfo = getClusteringInfo;
1090
1126
  const quantize = async (image, k, options) => {
1091
1127
  const wrap = getWrapper(image);
@@ -1180,4 +1216,13 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1180
1216
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1181
1217
  return result;
1182
1218
  };
1183
- exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1219
+
1220
+ // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1221
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1222
+ (0, _shared.setEngine)({
1223
+ cut: cutPalette,
1224
+ cutSwatches,
1225
+ info: readInfo,
1226
+ quantizeFromClustering,
1227
+ quantizeToIndicesFromClustering
1228
+ });
package/dist/index.d.cts CHANGED
@@ -1,5 +1,15 @@
1
- /** How pixel bytes are laid out: `'rgb'` is 3 bytes per pixel, `'rgba'` is 4 (red, green, blue, alpha). */
2
- export type ImageFormat = 'rgb' | 'rgba';
1
+ /**
2
+ * How pixel bytes are laid out:
3
+ * - `'rgb'`: 3 bytes per pixel, red, green, blue.
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with straight (not premultiplied) alpha last. BGRA is the order of Windows bitmaps and
5
+ * Electron's `nativeImage`, whose `toBitmap()` is premultiplied: convert it first (see Input in docs/api.md).
6
+ * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
+ * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
+ *
9
+ * Mapped images come back in the input's format; palettes are RGB whatever it is. New formats can come in a minor release,
10
+ * so take the names from `imageFormats` rather than spelling them out.
11
+ */
12
+ export type ImageFormat = 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx';
3
13
 
4
14
  /**
5
15
  * What went wrong, on the `code` of every error this library throws (the message is for people and may change):
@@ -60,7 +70,7 @@ export const ditherSteps: readonly DitherSteps[];
60
70
  export function isCodedError(value: unknown): value is CodedError;
61
71
 
62
72
  /**
63
- * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
73
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
64
74
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
65
75
  */
66
76
  export interface RawImage {
@@ -121,6 +131,12 @@ export class Palette extends Uint8Array {
121
131
  * `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
122
132
  * `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
123
133
  * wants it) and checks they are a clustering.
134
+ *
135
+ * It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
136
+ * so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
137
+ * `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
138
+ * bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
139
+ * `new Clustering(bytes)`.
124
140
  */
125
141
  export class Clustering extends Uint8Array {
126
142
  /**
@@ -131,6 +147,16 @@ export class Clustering extends Uint8Array {
131
147
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
132
148
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
133
149
  readonly [clusteringBrand]: true;
150
+ /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
151
+ getPalette(this: Clustering, k: number): Promise<Palette>;
152
+ /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
+ getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
+ /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
+ getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
+ /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
157
+ quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
+ /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
159
+ quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
134
160
  }
135
161
 
136
162
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
@@ -188,12 +214,13 @@ export interface ClusteringOptions extends ProgressOptions {
188
214
  */
189
215
  precision?: number | undefined;
190
216
  /**
191
- * How RGBA pixels count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
192
- * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x.
217
+ * How pixels of an image with alpha (RGBA or BGRA) count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
218
+ * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x. Clustering only:
219
+ * mapping still treats alpha-0 pixels as transparent, so for bytes whose fourth byte isn't alpha use `'rgbx'`/`'bgrx'`.
193
220
  */
194
221
  alpha?: AlphaMode | undefined;
195
222
  /**
196
- * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for RGBA images: pixels with alpha
223
+ * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
197
224
  * below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
198
225
  * whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
199
226
  * PNG), and it gives the same palette everywhere: `getPalette(image, k, { transparent })` is the palette
@@ -260,11 +287,11 @@ export type QuantizeOptions = ClusteringOptions & MappingOptions;
260
287
  export interface IndexOptions {
261
288
  /**
262
289
  * `false` (default): every pixel gets the index of its nearest colour, whatever its alpha.
263
- * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image is RGBA and has pixels with alpha
290
+ * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image has alpha (RGBA or BGRA) and has pixels with alpha
264
291
  * below the cutoff, they get an extra entry appended after the palette (black, taking no part in matching), as
265
292
  * GIFs and palette PNGs expect; its index is the result's `transparentIndex`. Every other pixel is shown fully
266
293
  * opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
267
- * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is always kept. Where
294
+ * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
268
295
  * this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
269
296
  * `ClusteringOptions.transparent`), so its palette is `getPalette(image, k - 1, { transparent })`'s. With a palette
270
297
  * you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
@@ -479,7 +506,8 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
479
506
  *
480
507
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
481
508
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
482
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
509
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
510
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
483
511
  */
484
512
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
485
513
 
@@ -488,7 +516,8 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
488
516
  *
489
517
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
490
518
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
491
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
519
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
520
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
492
521
  */
493
522
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
494
523
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,15 @@
1
- /** How pixel bytes are laid out: `'rgb'` is 3 bytes per pixel, `'rgba'` is 4 (red, green, blue, alpha). */
2
- export type ImageFormat = 'rgb' | 'rgba';
1
+ /**
2
+ * How pixel bytes are laid out:
3
+ * - `'rgb'`: 3 bytes per pixel, red, green, blue.
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with straight (not premultiplied) alpha last. BGRA is the order of Windows bitmaps and
5
+ * Electron's `nativeImage`, whose `toBitmap()` is premultiplied: convert it first (see Input in docs/api.md).
6
+ * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
+ * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
+ *
9
+ * Mapped images come back in the input's format; palettes are RGB whatever it is. New formats can come in a minor release,
10
+ * so take the names from `imageFormats` rather than spelling them out.
11
+ */
12
+ export type ImageFormat = 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx';
3
13
 
4
14
  /**
5
15
  * What went wrong, on the `code` of every error this library throws (the message is for people and may change):
@@ -60,7 +70,7 @@ export const ditherSteps: readonly DitherSteps[];
60
70
  export function isCodedError(value: unknown): value is CodedError;
61
71
 
62
72
  /**
63
- * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
73
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
64
74
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
65
75
  */
66
76
  export interface RawImage {
@@ -121,6 +131,12 @@ export class Palette extends Uint8Array {
121
131
  * `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
122
132
  * `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
123
133
  * wants it) and checks they are a clustering.
134
+ *
135
+ * It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
136
+ * so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
137
+ * `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
138
+ * bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
139
+ * `new Clustering(bytes)`.
124
140
  */
125
141
  export class Clustering extends Uint8Array {
126
142
  /**
@@ -131,6 +147,16 @@ export class Clustering extends Uint8Array {
131
147
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
132
148
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
133
149
  readonly [clusteringBrand]: true;
150
+ /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
151
+ getPalette(this: Clustering, k: number): Promise<Palette>;
152
+ /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
+ getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
+ /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
+ getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
+ /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
157
+ quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
+ /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
159
+ quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
134
160
  }
135
161
 
136
162
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
@@ -188,12 +214,13 @@ export interface ClusteringOptions extends ProgressOptions {
188
214
  */
189
215
  precision?: number | undefined;
190
216
  /**
191
- * How RGBA pixels count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
192
- * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x.
217
+ * How pixels of an image with alpha (RGBA or BGRA) count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
218
+ * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x. Clustering only:
219
+ * mapping still treats alpha-0 pixels as transparent, so for bytes whose fourth byte isn't alpha use `'rgbx'`/`'bgrx'`.
193
220
  */
194
221
  alpha?: AlphaMode | undefined;
195
222
  /**
196
- * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for RGBA images: pixels with alpha
223
+ * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
197
224
  * below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
198
225
  * whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
199
226
  * PNG), and it gives the same palette everywhere: `getPalette(image, k, { transparent })` is the palette
@@ -260,11 +287,11 @@ export type QuantizeOptions = ClusteringOptions & MappingOptions;
260
287
  export interface IndexOptions {
261
288
  /**
262
289
  * `false` (default): every pixel gets the index of its nearest colour, whatever its alpha.
263
- * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image is RGBA and has pixels with alpha
290
+ * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image has alpha (RGBA or BGRA) and has pixels with alpha
264
291
  * below the cutoff, they get an extra entry appended after the palette (black, taking no part in matching), as
265
292
  * GIFs and palette PNGs expect; its index is the result's `transparentIndex`. Every other pixel is shown fully
266
293
  * opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
267
- * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is always kept. Where
294
+ * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
268
295
  * this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
269
296
  * `ClusteringOptions.transparent`), so its palette is `getPalette(image, k - 1, { transparent })`'s. With a palette
270
297
  * you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
@@ -479,7 +506,8 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
479
506
  *
480
507
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
481
508
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
482
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
509
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
510
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
483
511
  */
484
512
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
485
513
 
@@ -488,7 +516,8 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
488
516
  *
489
517
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
490
518
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
491
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
519
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
520
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
492
521
  */
493
522
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
494
523