agglomerative-clustering 3.8.0 → 4.0.0-beta.1

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
@@ -82,7 +82,7 @@ slider.oninput = async () => {
82
82
  };
83
83
  ```
84
84
 
85
- 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; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. 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.
85
+ 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, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. 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.
86
86
 
87
87
  ## How it works
88
88
 
@@ -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"&&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,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,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"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];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,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];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"&&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,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,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"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];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,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];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
@@ -96,27 +96,6 @@ const codes = {
96
96
  'rgbx': 3,
97
97
  'bgrx': 4
98
98
  };
99
- // 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
100
- // supported layout.
101
- const formatHint = format => {
102
- if (typeof format !== 'string') {
103
- return '';
104
- }
105
- const lower = format.toLowerCase();
106
- if (lower !== format && _shared.imageFormats.includes(lower)) {
107
- return ` Format names are lower case: '${lower}'.`;
108
- }
109
- if (lower === 'xrgb' || lower === 'rgb24') {
110
- return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
111
- }
112
- if (lower === 'argb' || lower === 'argb32') {
113
- 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).";
114
- }
115
- if (lower === 'bgr' || lower === 'bgr24') {
116
- return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
117
- }
118
- return '';
119
- };
120
99
  const alphaModeCodes = {
121
100
  'ignore': 0,
122
101
  'weight': 1
@@ -502,20 +481,6 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
502
481
  // call returns; until then (the first call) a copy is kept for when it has loaded.
503
482
  const held = data => Module ? data : data.slice();
504
483
 
505
- // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
506
- // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
507
- const checkSize = (pixels, size, name, argument) => {
508
- if (size === undefined) {
509
- return;
510
- }
511
- if (!Number.isInteger(size) || size < 0) {
512
- throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
513
- }
514
- if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
515
- throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
516
- }
517
- };
518
-
519
484
  // The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
520
485
  // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
521
486
  const noWarning = () => {};
@@ -547,7 +512,8 @@ const load = image => {
547
512
  }
548
513
  return {
549
514
  data: held(image),
550
- format: 'rgba'
515
+ format: 'rgba',
516
+ premultiplied: false
551
517
  };
552
518
  }
553
519
  if ((0, _shared.isImageData)(image)) {
@@ -558,7 +524,8 @@ const load = image => {
558
524
  return {
559
525
  data: held(bytes(image.data)),
560
526
  format: 'rgba',
561
- width: image.width
527
+ width: image.width,
528
+ premultiplied: false
562
529
  };
563
530
  }
564
531
  if (ArrayBuffer.isView(image)) {
@@ -573,23 +540,12 @@ const load = image => {
573
540
  if ((0, _shared.isDetached)(image.data)) {
574
541
  throw (0, _shared.detachedError)('data');
575
542
  }
576
- if (!_shared.imageFormats.includes(image.format)) {
577
- throw (0, _shared.fail)('invalid-argument', `Invalid format: got ${(0, _shared.describe)(image.format)}; it must be ${_shared.formatNames}.${formatHint(image.format)}`, 'image');
578
- }
579
- const stride = (0, _shared.channels)(image.format);
580
- if (image.data.length % stride !== 0) {
581
- throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
582
- }
583
- const pixels = image.data.length / stride;
584
- checkSize(pixels, image.width, 'image width', 'image');
585
- checkSize(pixels, image.height, 'image height', 'image');
586
- if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
587
- throw (0, _shared.fail)('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
588
- }
543
+ const premultiplied = (0, _shared.checkImageObject)(image);
589
544
  return {
590
545
  data: held(bytes(image.data)),
591
546
  format: image.format,
592
- width: image.width
547
+ width: image.width,
548
+ premultiplied
593
549
  };
594
550
  };
595
551
  const getWrapper = image => {
@@ -601,7 +557,8 @@ const getWrapper = image => {
601
557
  const {
602
558
  format,
603
559
  width,
604
- height
560
+ height,
561
+ premultiplied
605
562
  } = image;
606
563
  return output => {
607
564
  const result = {
@@ -614,6 +571,9 @@ const getWrapper = image => {
614
571
  if (height !== undefined) {
615
572
  result.height = height;
616
573
  }
574
+ if (premultiplied !== undefined) {
575
+ result.premultiplied = premultiplied;
576
+ }
617
577
  return result;
618
578
  };
619
579
  }
@@ -718,7 +678,7 @@ const parseOptions = (options, allowed, image) => {
718
678
  throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
719
679
  }
720
680
  if (options.width !== undefined && image) {
721
- checkSize(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
681
+ (0, _shared.checkSize)(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
722
682
  }
723
683
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
724
684
  if (dither > 0) {
@@ -806,7 +766,9 @@ const allocate = (wasm, length) => {
806
766
 
807
767
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
808
768
  // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
809
- const call = (wasm, buffers, fn, precision) => {
769
+ // `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
770
+ // the output payload (a mapped image, not indexed output) before it is unpacked.
771
+ const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
810
772
  const pointers = [];
811
773
  let outputPointer = 0;
812
774
  let aborted = false;
@@ -816,12 +778,18 @@ const call = (wasm, buffers, fn, precision) => {
816
778
  pointers.push(pointer);
817
779
  wasm.HEAPU8.set(buffer, pointer);
818
780
  }
781
+ if (premultiplied) {
782
+ wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
783
+ }
819
784
  outputPointer = fn(...pointers);
820
785
  // Only the functions that read a clustering return nothing: when its records don't fit together (see
821
786
  // _get_palette_from_clustering), which a clustering whose checksum matches never does.
822
787
  if (!outputPointer) {
823
788
  throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
824
789
  }
790
+ if (premultiplied && mapped) {
791
+ wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
792
+ }
825
793
  return unpack(wasm, outputPointer);
826
794
  } catch (error) {
827
795
  if (!isAbort(error)) {
@@ -892,6 +860,21 @@ const reporter = o => {
892
860
  }
893
861
  };
894
862
  };
863
+
864
+ // The conversion passes in slices of this many pixels, so a long one gives the signal and the event loop a turn like the rest.
865
+ const convertSlice = 65536;
866
+ const convertInSlices = async (convert, pointer, pixels, o) => {
867
+ let last = performance.now();
868
+ for (let start = 0; start < pixels; start += convertSlice) {
869
+ checkAborted(o.signal);
870
+ convert(pointer, start, Math.min(pixels, start + convertSlice));
871
+ // Yield only once a slice's worth of time has gone, so a short pass doesn't pay a turn of the event loop per chunk.
872
+ if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
873
+ await yieldNow();
874
+ last = performance.now();
875
+ }
876
+ }
877
+ };
895
878
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
896
879
 
897
880
  // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
@@ -916,6 +899,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
916
899
  let aborted = false;
917
900
  try {
918
901
  wasm.HEAPU8.set(image.data, imagePointer);
902
+ if (image.premultiplied) {
903
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
904
+ }
919
905
  job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
920
906
  report(0);
921
907
  while (true) {
@@ -966,6 +952,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
966
952
  sourcePointer = allocate(wasm, bytes.length);
967
953
  wasm.HEAPU8.set(image.data, imagePointer);
968
954
  wasm.HEAPU8.set(bytes, sourcePointer);
955
+ if (image.premultiplied) {
956
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
957
+ }
969
958
  const palette = source.palette ? sourcePointer : 0,
970
959
  clustering = source.clustering ? sourcePointer : 0;
971
960
  job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
@@ -987,6 +976,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
987
976
  }
988
977
  const pointer = wasm._mapping_job_result(job);
989
978
  try {
979
+ if (image.premultiplied && !indices) {
980
+ await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
981
+ }
990
982
  return unpack(wasm, pointer);
991
983
  } finally {
992
984
  wasm._free(pointer);
@@ -1039,7 +1031,7 @@ const buildClustering = async (image, options) => {
1039
1031
  report(1);
1040
1032
  return (0, _shared.markClustering)(clustering);
1041
1033
  }
1042
- return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
1034
+ return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied));
1043
1035
  };
1044
1036
  /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
1045
1037
  exports.buildClustering = buildClustering;
@@ -1059,7 +1051,7 @@ const buildPalette = async (image, k, options) => {
1059
1051
  report(1);
1060
1052
  return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
1061
1053
  }
1062
- 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));
1054
+ 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, image.premultiplied), (0, _shared.colorSpaceName)(o.colorSpace));
1063
1055
  };
1064
1056
  /** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
1065
1057
  exports.buildPalette = buildPalette;
@@ -1203,7 +1195,7 @@ const quantize = async (image, k, options) => {
1203
1195
  report(1);
1204
1196
  return mapped;
1205
1197
  }
1206
- return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
1198
+ return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied, true));
1207
1199
  };
1208
1200
  exports.quantize = quantize;
1209
1201
  const quantizeFromClustering = async (image, clustering, k, options) => {
@@ -1227,7 +1219,7 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1227
1219
  report(1);
1228
1220
  return mapped;
1229
1221
  }
1230
- const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1222
+ const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1231
1223
  return result;
1232
1224
  };
1233
1225
  exports.quantizeFromClustering = quantizeFromClustering;
@@ -1251,7 +1243,7 @@ const quantizeWithPalette = async (image, palette, options) => {
1251
1243
  report(1);
1252
1244
  return mapped;
1253
1245
  }
1254
- const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1246
+ const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1255
1247
  return result;
1256
1248
  };
1257
1249
  exports.quantizeWithPalette = quantizeWithPalette;
@@ -1274,7 +1266,7 @@ const quantizeToIndices = async (image, k, options) => {
1274
1266
  report(1);
1275
1267
  return indexed;
1276
1268
  }
1277
- return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, (0, _shared.colorSpaceName)(o.colorSpace));
1269
+ return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied), original, (0, _shared.colorSpaceName)(o.colorSpace));
1278
1270
  };
1279
1271
  exports.quantizeToIndices = quantizeToIndices;
1280
1272
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
@@ -1301,7 +1293,7 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1301
1293
  report(1);
1302
1294
  return indexed;
1303
1295
  }
1304
- const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, (0, _shared.colorSpaceName)(header.colorSpace));
1296
+ const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, (0, _shared.colorSpaceName)(header.colorSpace));
1305
1297
  return result;
1306
1298
  };
1307
1299
  exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
@@ -1326,7 +1318,7 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1326
1318
  report(1);
1327
1319
  return indexed;
1328
1320
  }
1329
- 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);
1321
+ 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), undefined, image.premultiplied), original, paletteSpace);
1330
1322
  return result;
1331
1323
  };
1332
1324
 
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * How pixel bytes are laid out:
3
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).
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with alpha last, straight unless the image object says `premultiplied: true` (canvas
5
+ * surfaces, Electron's `toBitmap()`). BGRA is the order of Windows bitmaps and Electron's `nativeImage`.
6
6
  * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
7
  * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
8
  *
@@ -70,28 +70,61 @@ export const ditherSteps: readonly DitherSteps[];
70
70
  export function isCodedError(value: unknown): value is CodedError;
71
71
 
72
72
  /**
73
- * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
74
- * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
73
+ * RGBA or BGRA bytes. `premultiplied: true` says the colours are multiplied by alpha (canvas, Electron, WebGL).
74
+ * Internal: name it through `RawImage<'rgba'>` or `RawImage<'bgra'>`.
75
+ */
76
+ interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
77
+ data: Uint8Array | Uint8ClampedArray;
78
+ format: F;
79
+ /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
+ width?: number | undefined;
81
+ /** Height in pixels. Optional; copied to `quantize*` results. */
82
+ height?: number | undefined;
83
+ /**
84
+ * The colours are multiplied by alpha (what a canvas surface, Electron's `toBitmap()`, WebGL and Cairo hold). They are
85
+ * read as straight colours (divided by alpha), and `quantize*` gives the mapped colours back multiplied, copied as
86
+ * given: the result has the same `premultiplied` as the input. For a straight destination (`ImageData`, PNG encoders),
87
+ * use `quantizeToIndices` and write palette colours with the input's alpha; un-premultiplying the output loses colour. The guides' "Straight pixels from a premultiplied source" has the loop.
88
+ */
89
+ premultiplied?: boolean | undefined;
90
+ }
91
+
92
+ /**
93
+ * Formats without alpha. `premultiplied: false` says nothing; `true` is rejected at run time (there is no alpha).
94
+ * Internal: name it through `RawImage<'rgb'>`, `RawImage<'rgbx'>` or `RawImage<'bgrx'>`.
75
95
  */
76
- export interface RawImage {
96
+ interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
77
97
  data: Uint8Array | Uint8ClampedArray;
78
- format: ImageFormat;
98
+ format: F;
79
99
  /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
100
  width?: number | undefined;
81
101
  /** Height in pixels. Optional; copied to `quantize*` results. */
82
102
  height?: number | undefined;
103
+ /** Accepted as `false` on any format and does nothing here; `true` is an `invalid-argument` error, since there is no alpha. */
104
+ premultiplied?: boolean | undefined;
83
105
  }
84
106
 
107
+ /**
108
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
109
+ * `ImageData`. `RawImage<'bgra'>` is one format. Functions that return an image give back an object with the input's own
110
+ * keys (`format`, and `width`, `height` and `premultiplied` when given) and a new `data`.
111
+ */
112
+ export type RawImage<F extends ImageFormat = ImageFormat> =
113
+ F extends 'rgba' | 'bgra' ? RawImageWithAlpha<F> : F extends 'rgb' | 'rgbx' | 'bgrx' ? RawImageWithoutAlpha<F> : never;
114
+
85
115
  /**
86
116
  * The platform's `ImageData` class where the global exists (the DOM lib, or typings for a canvas polyfill), and `never`
87
117
  * where it doesn't, so these declarations compile with or without the DOM lib, in browser and Node-only projects.
88
118
  */
89
119
  export type PlatformImageData = typeof globalThis extends { ImageData: { prototype: infer T } } ? T : never;
90
120
 
91
- /** What a function that returns an image gives back for the input it was given: the same kind of thing. */
121
+ /**
122
+ * What a function that returns an image gives back for the input it was given: the same kind of thing. For an image
123
+ * object, one with the input's own keys and a new `data: Uint8Array`.
124
+ */
92
125
  export type ImageResult<I extends ImageLike> =
93
126
  I extends Uint8Array ? Uint8Array
94
- : I extends RawImage ? RawImage
127
+ : I extends RawImage ? Omit<I, 'data'> & { data: Uint8Array }
95
128
  : I extends PlatformImageData ? PlatformImageData
96
129
  : never;
97
130
 
@@ -344,7 +377,8 @@ interface IndexedImageFields {
344
377
 
345
378
  /**
346
379
  * One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
347
- * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type.
380
+ * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type. The palette
381
+ * is straight even for a premultiplied input: indexed output has no partial alpha, so there is nothing to premultiply.
348
382
  */
349
383
  export type IndexedImage =
350
384
  | (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * How pixel bytes are laid out:
3
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).
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with alpha last, straight unless the image object says `premultiplied: true` (canvas
5
+ * surfaces, Electron's `toBitmap()`). BGRA is the order of Windows bitmaps and Electron's `nativeImage`.
6
6
  * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
7
  * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
8
  *
@@ -70,28 +70,61 @@ export const ditherSteps: readonly DitherSteps[];
70
70
  export function isCodedError(value: unknown): value is CodedError;
71
71
 
72
72
  /**
73
- * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
74
- * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
73
+ * RGBA or BGRA bytes. `premultiplied: true` says the colours are multiplied by alpha (canvas, Electron, WebGL).
74
+ * Internal: name it through `RawImage<'rgba'>` or `RawImage<'bgra'>`.
75
+ */
76
+ interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
77
+ data: Uint8Array | Uint8ClampedArray;
78
+ format: F;
79
+ /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
+ width?: number | undefined;
81
+ /** Height in pixels. Optional; copied to `quantize*` results. */
82
+ height?: number | undefined;
83
+ /**
84
+ * The colours are multiplied by alpha (what a canvas surface, Electron's `toBitmap()`, WebGL and Cairo hold). They are
85
+ * read as straight colours (divided by alpha), and `quantize*` gives the mapped colours back multiplied, copied as
86
+ * given: the result has the same `premultiplied` as the input. For a straight destination (`ImageData`, PNG encoders),
87
+ * use `quantizeToIndices` and write palette colours with the input's alpha; un-premultiplying the output loses colour. The guides' "Straight pixels from a premultiplied source" has the loop.
88
+ */
89
+ premultiplied?: boolean | undefined;
90
+ }
91
+
92
+ /**
93
+ * Formats without alpha. `premultiplied: false` says nothing; `true` is rejected at run time (there is no alpha).
94
+ * Internal: name it through `RawImage<'rgb'>`, `RawImage<'rgbx'>` or `RawImage<'bgrx'>`.
75
95
  */
76
- export interface RawImage {
96
+ interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
77
97
  data: Uint8Array | Uint8ClampedArray;
78
- format: ImageFormat;
98
+ format: F;
79
99
  /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
100
  width?: number | undefined;
81
101
  /** Height in pixels. Optional; copied to `quantize*` results. */
82
102
  height?: number | undefined;
103
+ /** Accepted as `false` on any format and does nothing here; `true` is an `invalid-argument` error, since there is no alpha. */
104
+ premultiplied?: boolean | undefined;
83
105
  }
84
106
 
107
+ /**
108
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
109
+ * `ImageData`. `RawImage<'bgra'>` is one format. Functions that return an image give back an object with the input's own
110
+ * keys (`format`, and `width`, `height` and `premultiplied` when given) and a new `data`.
111
+ */
112
+ export type RawImage<F extends ImageFormat = ImageFormat> =
113
+ F extends 'rgba' | 'bgra' ? RawImageWithAlpha<F> : F extends 'rgb' | 'rgbx' | 'bgrx' ? RawImageWithoutAlpha<F> : never;
114
+
85
115
  /**
86
116
  * The platform's `ImageData` class where the global exists (the DOM lib, or typings for a canvas polyfill), and `never`
87
117
  * where it doesn't, so these declarations compile with or without the DOM lib, in browser and Node-only projects.
88
118
  */
89
119
  export type PlatformImageData = typeof globalThis extends { ImageData: { prototype: infer T } } ? T : never;
90
120
 
91
- /** What a function that returns an image gives back for the input it was given: the same kind of thing. */
121
+ /**
122
+ * What a function that returns an image gives back for the input it was given: the same kind of thing. For an image
123
+ * object, one with the input's own keys and a new `data: Uint8Array`.
124
+ */
92
125
  export type ImageResult<I extends ImageLike> =
93
126
  I extends Uint8Array ? Uint8Array
94
- : I extends RawImage ? RawImage
127
+ : I extends RawImage ? Omit<I, 'data'> & { data: Uint8Array }
95
128
  : I extends PlatformImageData ? PlatformImageData
96
129
  : never;
97
130
 
@@ -344,7 +377,8 @@ interface IndexedImageFields {
344
377
 
345
378
  /**
346
379
  * One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
347
- * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type.
380
+ * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type. The palette
381
+ * is straight even for a premultiplied input: indexed output has no partial alpha, so there is nothing to premultiply.
348
382
  */
349
383
  export type IndexedImage =
350
384
  | (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import createWasmModule from './clustering.js';
2
2
  import { choose } from "./choose.mjs";
3
- import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge, sniffImageFormat, bareImageWarning, warnOnce } from "./shared.mjs";
3
+ import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge, sniffImageFormat, bareImageWarning, warnOnce, checkImageObject, checkSize, formatHint } from "./shared.mjs";
4
4
 
5
5
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
6
6
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -21,27 +21,6 @@ const codes = {
21
21
  'rgbx': 3,
22
22
  'bgrx': 4
23
23
  };
24
- // 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
25
- // supported layout.
26
- const formatHint = format => {
27
- if (typeof format !== 'string') {
28
- return '';
29
- }
30
- const lower = format.toLowerCase();
31
- if (lower !== format && imageFormats.includes(lower)) {
32
- return ` Format names are lower case: '${lower}'.`;
33
- }
34
- if (lower === 'xrgb' || lower === 'rgb24') {
35
- return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
36
- }
37
- if (lower === 'argb' || lower === 'argb32') {
38
- 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).";
39
- }
40
- if (lower === 'bgr' || lower === 'bgr24') {
41
- return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
42
- }
43
- return '';
44
- };
45
24
  const alphaModeCodes = {
46
25
  'ignore': 0,
47
26
  'weight': 1
@@ -426,20 +405,6 @@ const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, da
426
405
  // call returns; until then (the first call) a copy is kept for when it has loaded.
427
406
  const held = data => Module ? data : data.slice();
428
407
 
429
- // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
430
- // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
431
- const checkSize = (pixels, size, name, argument) => {
432
- if (size === undefined) {
433
- return;
434
- }
435
- if (!Number.isInteger(size) || size < 0) {
436
- throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
437
- }
438
- if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
439
- throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
440
- }
441
- };
442
-
443
408
  // The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
444
409
  // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
445
410
  const noWarning = () => {};
@@ -471,7 +436,8 @@ const load = image => {
471
436
  }
472
437
  return {
473
438
  data: held(image),
474
- format: 'rgba'
439
+ format: 'rgba',
440
+ premultiplied: false
475
441
  };
476
442
  }
477
443
  if (isImageData(image)) {
@@ -482,7 +448,8 @@ const load = image => {
482
448
  return {
483
449
  data: held(bytes(image.data)),
484
450
  format: 'rgba',
485
- width: image.width
451
+ width: image.width,
452
+ premultiplied: false
486
453
  };
487
454
  }
488
455
  if (ArrayBuffer.isView(image)) {
@@ -497,23 +464,12 @@ const load = image => {
497
464
  if (isDetached(image.data)) {
498
465
  throw detachedError('data');
499
466
  }
500
- if (!imageFormats.includes(image.format)) {
501
- throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
502
- }
503
- const stride = channels(image.format);
504
- if (image.data.length % stride !== 0) {
505
- throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
506
- }
507
- const pixels = image.data.length / stride;
508
- checkSize(pixels, image.width, 'image width', 'image');
509
- checkSize(pixels, image.height, 'image height', 'image');
510
- if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
511
- throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
512
- }
467
+ const premultiplied = checkImageObject(image);
513
468
  return {
514
469
  data: held(bytes(image.data)),
515
470
  format: image.format,
516
- width: image.width
471
+ width: image.width,
472
+ premultiplied
517
473
  };
518
474
  };
519
475
  const getWrapper = image => {
@@ -525,7 +481,8 @@ const getWrapper = image => {
525
481
  const {
526
482
  format,
527
483
  width,
528
- height
484
+ height,
485
+ premultiplied
529
486
  } = image;
530
487
  return output => {
531
488
  const result = {
@@ -538,6 +495,9 @@ const getWrapper = image => {
538
495
  if (height !== undefined) {
539
496
  result.height = height;
540
497
  }
498
+ if (premultiplied !== undefined) {
499
+ result.premultiplied = premultiplied;
500
+ }
541
501
  return result;
542
502
  };
543
503
  }
@@ -730,7 +690,9 @@ const allocate = (wasm, length) => {
730
690
 
731
691
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
732
692
  // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
733
- const call = (wasm, buffers, fn, precision) => {
693
+ // `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
694
+ // the output payload (a mapped image, not indexed output) before it is unpacked.
695
+ const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
734
696
  const pointers = [];
735
697
  let outputPointer = 0;
736
698
  let aborted = false;
@@ -740,12 +702,18 @@ const call = (wasm, buffers, fn, precision) => {
740
702
  pointers.push(pointer);
741
703
  wasm.HEAPU8.set(buffer, pointer);
742
704
  }
705
+ if (premultiplied) {
706
+ wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
707
+ }
743
708
  outputPointer = fn(...pointers);
744
709
  // Only the functions that read a clustering return nothing: when its records don't fit together (see
745
710
  // _get_palette_from_clustering), which a clustering whose checksum matches never does.
746
711
  if (!outputPointer) {
747
712
  throw fail('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
748
713
  }
714
+ if (premultiplied && mapped) {
715
+ wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
716
+ }
749
717
  return unpack(wasm, outputPointer);
750
718
  } catch (error) {
751
719
  if (!isAbort(error)) {
@@ -816,6 +784,21 @@ const reporter = o => {
816
784
  }
817
785
  };
818
786
  };
787
+
788
+ // The conversion passes in slices of this many pixels, so a long one gives the signal and the event loop a turn like the rest.
789
+ const convertSlice = 65536;
790
+ const convertInSlices = async (convert, pointer, pixels, o) => {
791
+ let last = performance.now();
792
+ for (let start = 0; start < pixels; start += convertSlice) {
793
+ checkAborted(o.signal);
794
+ convert(pointer, start, Math.min(pixels, start + convertSlice));
795
+ // Yield only once a slice's worth of time has gone, so a short pass doesn't pay a turn of the event loop per chunk.
796
+ if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
797
+ await yieldNow();
798
+ last = performance.now();
799
+ }
800
+ }
801
+ };
819
802
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
820
803
 
821
804
  // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
@@ -840,6 +823,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
840
823
  let aborted = false;
841
824
  try {
842
825
  wasm.HEAPU8.set(image.data, imagePointer);
826
+ if (image.premultiplied) {
827
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
828
+ }
843
829
  job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
844
830
  report(0);
845
831
  while (true) {
@@ -890,6 +876,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
890
876
  sourcePointer = allocate(wasm, bytes.length);
891
877
  wasm.HEAPU8.set(image.data, imagePointer);
892
878
  wasm.HEAPU8.set(bytes, sourcePointer);
879
+ if (image.premultiplied) {
880
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
881
+ }
893
882
  const palette = source.palette ? sourcePointer : 0,
894
883
  clustering = source.clustering ? sourcePointer : 0;
895
884
  job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
@@ -911,6 +900,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
911
900
  }
912
901
  const pointer = wasm._mapping_job_result(job);
913
902
  try {
903
+ if (image.premultiplied && !indices) {
904
+ await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
905
+ }
914
906
  return unpack(wasm, pointer);
915
907
  } finally {
916
908
  wasm._free(pointer);
@@ -963,7 +955,7 @@ export const buildClustering = async (image, options) => {
963
955
  report(1);
964
956
  return markClustering(clustering);
965
957
  }
966
- return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
958
+ return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied));
967
959
  };
968
960
  /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
969
961
  export const getClustering = buildClustering;
@@ -982,7 +974,7 @@ export const buildPalette = async (image, k, options) => {
982
974
  report(1);
983
975
  return markPalette(palette, colorSpaceName(o.colorSpace));
984
976
  }
985
- return 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), colorSpaceName(o.colorSpace));
977
+ return 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, image.premultiplied), colorSpaceName(o.colorSpace));
986
978
  };
987
979
  /** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
988
980
  export const getPalette = buildPalette;
@@ -1121,7 +1113,7 @@ export const quantize = async (image, k, options) => {
1121
1113
  report(1);
1122
1114
  return mapped;
1123
1115
  }
1124
- return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
1116
+ return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied, true));
1125
1117
  };
1126
1118
  export const quantizeFromClustering = async (image, clustering, k, options) => {
1127
1119
  const warn = warningFor(image);
@@ -1144,7 +1136,7 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
1144
1136
  report(1);
1145
1137
  return mapped;
1146
1138
  }
1147
- const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1139
+ const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1148
1140
  return result;
1149
1141
  };
1150
1142
  export const quantizeWithPalette = async (image, palette, options) => {
@@ -1167,7 +1159,7 @@ export const quantizeWithPalette = async (image, palette, options) => {
1167
1159
  report(1);
1168
1160
  return mapped;
1169
1161
  }
1170
- const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1162
+ const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1171
1163
  return result;
1172
1164
  };
1173
1165
  export const quantizeToIndices = async (image, k, options) => {
@@ -1189,7 +1181,7 @@ export const quantizeToIndices = async (image, k, options) => {
1189
1181
  report(1);
1190
1182
  return indexed;
1191
1183
  }
1192
- return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
1184
+ return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied), original, colorSpaceName(o.colorSpace));
1193
1185
  };
1194
1186
  export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1195
1187
  const warn = warningFor(image);
@@ -1215,7 +1207,7 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
1215
1207
  report(1);
1216
1208
  return indexed;
1217
1209
  }
1218
- const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, colorSpaceName(header.colorSpace));
1210
+ const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, colorSpaceName(header.colorSpace));
1219
1211
  return result;
1220
1212
  };
1221
1213
  export const quantizeToIndicesWithPalette = async (image, palette, options) => {
@@ -1239,7 +1231,7 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1239
1231
  report(1);
1240
1232
  return indexed;
1241
1233
  }
1242
- 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);
1234
+ 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), undefined, image.premultiplied), original, paletteSpace);
1243
1235
  return result;
1244
1236
  };
1245
1237
 
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.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = void 0;
9
+ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.formatHint = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkSize = exports.checkPalette = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = 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.8.0';
16
+ const version = exports.version = '4.0.0-beta.1';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -184,10 +184,126 @@ const imageHint = image => {
184
184
  return '';
185
185
  };
186
186
 
187
+ // An image object has only these keys; any other own enumerable key (a decoder's result spread in) is an error, with a hint where
188
+ // the mistake is a common one. Inherited keys are not checked.
189
+ exports.imageHint = imageHint;
190
+ const imageKeys = ['data', 'format', 'width', 'height', 'premultiplied'];
191
+ const withinOne = (a, b) => {
192
+ if (a === b) {
193
+ return true;
194
+ }
195
+ if (Math.abs(a.length - b.length) > 1) {
196
+ return false;
197
+ }
198
+ let i = 0;
199
+ while (i < a.length && i < b.length && a[i] === b[i]) {
200
+ i++;
201
+ }
202
+ if (a.length === b.length) {
203
+ // One substitution, or two neighbouring letters swapped (widht).
204
+ return a.slice(i + 1) === b.slice(i + 1) || a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2);
205
+ }
206
+ const [long, short] = a.length > b.length ? [a, b] : [b, a];
207
+ return long.slice(i + 1) === short.slice(i);
208
+ };
209
+ const checkImageKeys = image => {
210
+ for (const key of Object.keys(image)) {
211
+ if (imageKeys.includes(key)) {
212
+ continue;
213
+ }
214
+ let hint = '';
215
+ if (key === 'premultiply') {
216
+ hint = ' Did you mean premultiplied: true?';
217
+ } else if (key === 'channels' || key === 'size' || key === 'depth') {
218
+ hint = " Take only width and height from a decoder's result.";
219
+ } else {
220
+ const near = imageKeys.find(known => key.toLowerCase() === known || withinOne(key, known));
221
+ if (near) {
222
+ hint = ` Did you mean '${near}'?`;
223
+ }
224
+ }
225
+ throw fail('invalid-argument', `Invalid image: unknown key '${key}'. An image object has data, format, width, height and premultiplied: build it from those rather than spreading a decoder's result.${hint}`, 'image');
226
+ }
227
+ };
228
+
229
+ // 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
230
+ // supported layout.
231
+ exports.checkImageKeys = checkImageKeys;
232
+ const formatHint = format => {
233
+ if (typeof format !== 'string') {
234
+ return '';
235
+ }
236
+ const lower = format.toLowerCase();
237
+ if (lower !== format && imageFormats.includes(lower)) {
238
+ return ` Format names are lower case: '${lower}'.`;
239
+ }
240
+ if (lower === 'xrgb' || lower === 'rgb24') {
241
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
242
+ }
243
+ if (lower === 'argb' || lower === 'argb32') {
244
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: pass it as 'bgra' with premultiplied: true (see Input in the API docs).";
245
+ }
246
+ if (lower === 'bgr' || lower === 'bgr24') {
247
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
248
+ }
249
+ return '';
250
+ };
251
+ // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
252
+ // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
253
+ exports.formatHint = formatHint;
254
+ const checkSize = (pixels, size, name, argument) => {
255
+ if (size === undefined) {
256
+ return;
257
+ }
258
+ if (!Number.isInteger(size) || size < 0) {
259
+ throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
260
+ }
261
+ if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
262
+ throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
263
+ }
264
+ };
265
+
266
+ // `premultiplied` on an image object: true only for 'rgba' and 'bgra' (the formats with alpha); false is accepted on any format.
267
+ exports.checkSize = checkSize;
268
+ const checkPremultiplied = image => {
269
+ const value = image.premultiplied;
270
+ if (value === undefined || value === false) {
271
+ return false;
272
+ }
273
+ if (value !== true) {
274
+ throw fail('invalid-argument', `Invalid image: premultiplied must be true or false, got ${describe(value)}.`, 'image');
275
+ }
276
+ if (image.format !== 'rgba' && image.format !== 'bgra') {
277
+ throw fail('invalid-argument', `Invalid image: premultiplied is for 'rgba' and 'bgra'; '${image.format}' has no alpha, so remove it.`, 'image');
278
+ }
279
+ return true;
280
+ };
281
+
282
+ // Everything checked about an image object whose data is a Uint8Array or Uint8ClampedArray, in this order: format, data length,
283
+ // width and height, unknown keys, premultiplied. The main entry and the worker entry (before it posts) both run it, so their errors
284
+ // are identical. Returns the premultiplied flag.
285
+ const checkImageObject = image => {
286
+ if (!imageFormats.includes(image.format)) {
287
+ throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
288
+ }
289
+ const stride = channels(image.format);
290
+ if (image.data.length % stride !== 0) {
291
+ throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
292
+ }
293
+ const pixels = image.data.length / stride;
294
+ checkSize(pixels, image.width, 'image width', 'image');
295
+ checkSize(pixels, image.height, 'image height', 'image');
296
+ if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
297
+ throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
298
+ }
299
+ checkImageKeys(image);
300
+ return checkPremultiplied(image);
301
+ };
302
+
187
303
  // An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
188
304
  // `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
189
305
  // (an iframe, a test sandbox) are fine.
190
- exports.imageHint = imageHint;
306
+ exports.checkImageObject = checkImageObject;
191
307
  const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
192
308
 
193
309
  // One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.8.0';
7
+ export const version = '4.0.0-beta.1';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -160,6 +160,118 @@ export const imageHint = image => {
160
160
  return '';
161
161
  };
162
162
 
163
+ // An image object has only these keys; any other own enumerable key (a decoder's result spread in) is an error, with a hint where
164
+ // the mistake is a common one. Inherited keys are not checked.
165
+ const imageKeys = ['data', 'format', 'width', 'height', 'premultiplied'];
166
+ const withinOne = (a, b) => {
167
+ if (a === b) {
168
+ return true;
169
+ }
170
+ if (Math.abs(a.length - b.length) > 1) {
171
+ return false;
172
+ }
173
+ let i = 0;
174
+ while (i < a.length && i < b.length && a[i] === b[i]) {
175
+ i++;
176
+ }
177
+ if (a.length === b.length) {
178
+ // One substitution, or two neighbouring letters swapped (widht).
179
+ return a.slice(i + 1) === b.slice(i + 1) || a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2);
180
+ }
181
+ const [long, short] = a.length > b.length ? [a, b] : [b, a];
182
+ return long.slice(i + 1) === short.slice(i);
183
+ };
184
+ export const checkImageKeys = image => {
185
+ for (const key of Object.keys(image)) {
186
+ if (imageKeys.includes(key)) {
187
+ continue;
188
+ }
189
+ let hint = '';
190
+ if (key === 'premultiply') {
191
+ hint = ' Did you mean premultiplied: true?';
192
+ } else if (key === 'channels' || key === 'size' || key === 'depth') {
193
+ hint = " Take only width and height from a decoder's result.";
194
+ } else {
195
+ const near = imageKeys.find(known => key.toLowerCase() === known || withinOne(key, known));
196
+ if (near) {
197
+ hint = ` Did you mean '${near}'?`;
198
+ }
199
+ }
200
+ throw fail('invalid-argument', `Invalid image: unknown key '${key}'. An image object has data, format, width, height and premultiplied: build it from those rather than spreading a decoder's result.${hint}`, 'image');
201
+ }
202
+ };
203
+
204
+ // 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
205
+ // supported layout.
206
+ export const formatHint = format => {
207
+ if (typeof format !== 'string') {
208
+ return '';
209
+ }
210
+ const lower = format.toLowerCase();
211
+ if (lower !== format && imageFormats.includes(lower)) {
212
+ return ` Format names are lower case: '${lower}'.`;
213
+ }
214
+ if (lower === 'xrgb' || lower === 'rgb24') {
215
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
216
+ }
217
+ if (lower === 'argb' || lower === 'argb32') {
218
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: pass it as 'bgra' with premultiplied: true (see Input in the API docs).";
219
+ }
220
+ if (lower === 'bgr' || lower === 'bgr24') {
221
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
222
+ }
223
+ return '';
224
+ };
225
+ // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
226
+ // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
227
+ export const checkSize = (pixels, size, name, argument) => {
228
+ if (size === undefined) {
229
+ return;
230
+ }
231
+ if (!Number.isInteger(size) || size < 0) {
232
+ throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
233
+ }
234
+ if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
235
+ throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
236
+ }
237
+ };
238
+
239
+ // `premultiplied` on an image object: true only for 'rgba' and 'bgra' (the formats with alpha); false is accepted on any format.
240
+ const checkPremultiplied = image => {
241
+ const value = image.premultiplied;
242
+ if (value === undefined || value === false) {
243
+ return false;
244
+ }
245
+ if (value !== true) {
246
+ throw fail('invalid-argument', `Invalid image: premultiplied must be true or false, got ${describe(value)}.`, 'image');
247
+ }
248
+ if (image.format !== 'rgba' && image.format !== 'bgra') {
249
+ throw fail('invalid-argument', `Invalid image: premultiplied is for 'rgba' and 'bgra'; '${image.format}' has no alpha, so remove it.`, 'image');
250
+ }
251
+ return true;
252
+ };
253
+
254
+ // Everything checked about an image object whose data is a Uint8Array or Uint8ClampedArray, in this order: format, data length,
255
+ // width and height, unknown keys, premultiplied. The main entry and the worker entry (before it posts) both run it, so their errors
256
+ // are identical. Returns the premultiplied flag.
257
+ export const checkImageObject = image => {
258
+ if (!imageFormats.includes(image.format)) {
259
+ throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
260
+ }
261
+ const stride = channels(image.format);
262
+ if (image.data.length % stride !== 0) {
263
+ throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
264
+ }
265
+ const pixels = image.data.length / stride;
266
+ checkSize(pixels, image.width, 'image width', 'image');
267
+ checkSize(pixels, image.height, 'image height', 'image');
268
+ if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
269
+ throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
270
+ }
271
+ checkImageKeys(image);
272
+ return checkPremultiplied(image);
273
+ };
274
+
163
275
  // An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
164
276
  // `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
165
277
  // (an iframe, a test sandbox) are fine.
package/dist/worker.cjs CHANGED
@@ -344,10 +344,20 @@ const send = image => {
344
344
  };
345
345
  }
346
346
  if (image && typeof image === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
347
+ // The main entry's checks (shape, unknown keys, premultiplied) run here, in its order, before anything is posted. Data of another
348
+ // type, or no format, goes on as it is for the worker's own error.
347
349
  const sent = {
348
350
  data: image.data,
349
351
  format: image.format
350
352
  };
353
+ if (image.format && ((0, _shared.isUint8Array)(image.data) || (0, _shared.isUint8ClampedArray)(image.data))) {
354
+ const premultiplied = (0, _shared.checkImageObject)(image);
355
+ if (image.premultiplied !== undefined) {
356
+ sent.premultiplied = premultiplied;
357
+ }
358
+ } else if (image.premultiplied !== undefined) {
359
+ sent.premultiplied = image.premultiplied;
360
+ }
351
361
  if (image.width !== undefined) {
352
362
  sent.width = image.width;
353
363
  }
package/dist/worker.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
5
5
  // worker, started on first use.
6
6
 
7
- import { fail, isCodedError, detachedError, isOptionsObject, isUint8Array, isUint8ClampedArray, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce, readHeader } from "./shared.mjs";
7
+ import { fail, isCodedError, detachedError, isOptionsObject, isUint8Array, isUint8ClampedArray, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce, readHeader, checkImageObject } from "./shared.mjs";
8
8
 
9
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
10
10
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -275,10 +275,20 @@ const send = image => {
275
275
  };
276
276
  }
277
277
  if (image && typeof image === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
278
+ // The main entry's checks (shape, unknown keys, premultiplied) run here, in its order, before anything is posted. Data of another
279
+ // type, or no format, goes on as it is for the worker's own error.
278
280
  const sent = {
279
281
  data: image.data,
280
282
  format: image.format
281
283
  };
284
+ if (image.format && (isUint8Array(image.data) || isUint8ClampedArray(image.data))) {
285
+ const premultiplied = checkImageObject(image);
286
+ if (image.premultiplied !== undefined) {
287
+ sent.premultiplied = premultiplied;
288
+ }
289
+ } else if (image.premultiplied !== undefined) {
290
+ sent.premultiplied = image.premultiplied;
291
+ }
282
292
  if (image.width !== undefined) {
283
293
  sent.width = image.width;
284
294
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.8.0",
3
+ "version": "4.0.0-beta.1",
4
4
  "description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
5
5
  "license": "MIT",
6
6
  "author": "Rohan Fredriksson",
@@ -81,7 +81,7 @@
81
81
  "README.md"
82
82
  ],
83
83
  "scripts": {
84
- "build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_mapping_job_start','_mapping_job_step','_mapping_job_result','_mapping_job_free','_get_palette','_get_palette_from_clustering','_get_palette_weights','_quantize','_quantize_with_clustering','_quantize_with_palette','_quantize_indices','_quantize_indices_with_clustering','_quantize_indices_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
84
+ "build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_unpremultiply','_premultiply','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_mapping_job_start','_mapping_job_step','_mapping_job_result','_mapping_job_free','_get_palette','_get_palette_from_clustering','_get_palette_weights','_quantize','_quantize_with_clustering','_quantize_with_palette','_quantize_indices','_quantize_indices_with_clustering','_quantize_indices_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
85
85
  "build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker-thread.js\" --out-file-extension .cjs && node scripts/patch-cjs.mjs",
86
86
  "build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
87
87
  "build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts'); fs.writeFileSync('dist/worker.d.cts', fs.readFileSync('src/worker.d.ts', 'utf8').replaceAll(\\\"'./index.js'\\\", \\\"'./index.cjs'\\\"));\"",