@squoosh-kit/core 0.1.11 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-245sw6kx.js +3 -0
- package/dist/{chunk-3rt7m395.js.map → chunk-245sw6kx.js.map} +3 -3
- package/dist/chunk-5d1w8na7.js +3 -0
- package/dist/{chunk-yv042k8x.js.map → chunk-5d1w8na7.js.map} +3 -3
- package/dist/chunk-6qtap428.js +4 -0
- package/dist/chunk-6qtap428.js.map +12 -0
- package/dist/chunk-74bcayvr.js +3 -0
- package/dist/chunk-74bcayvr.js.map +13 -0
- package/dist/chunk-8r69sf95.js +5 -0
- package/dist/chunk-8r69sf95.js.map +12 -0
- package/dist/chunk-cfpkr9nw.js +5 -0
- package/dist/{chunk-02ytt443.js.map → chunk-cfpkr9nw.js.map} +5 -4
- package/dist/chunk-d3fxpzrq.js +4 -0
- package/dist/{chunk-mm6wmg56.js.map → chunk-d3fxpzrq.js.map} +5 -4
- package/dist/chunk-f8hc5gnf.js +4 -0
- package/dist/chunk-f8hc5gnf.js.map +12 -0
- package/dist/chunk-fks9mwgb.js +3 -0
- package/dist/chunk-fks9mwgb.js.map +13 -0
- package/dist/{chunk-69d55ymx.js → chunk-kjhvs4qe.js} +2 -2
- package/dist/{chunk-69d55ymx.js.map → chunk-kjhvs4qe.js.map} +3 -3
- package/dist/{chunk-374tq8cw.js → chunk-kqn499ka.js} +2 -2
- package/dist/chunk-kqn499ka.js.map +13 -0
- package/dist/chunk-rta7shf1.js +4 -0
- package/dist/{chunk-p24n653d.js.map → chunk-rta7shf1.js.map} +5 -4
- package/dist/chunk-sycf5j9m.js +4 -0
- package/dist/{chunk-yd1vfk89.js.map → chunk-sycf5j9m.js.map} +3 -3
- package/dist/chunk-t4jk8xn4.js +3 -0
- package/dist/chunk-t4jk8xn4.js.map +12 -0
- package/dist/chunk-vk3k7qxb.js +3 -0
- package/dist/{chunk-6d2104pn.js.map → chunk-vk3k7qxb.js.map} +5 -4
- package/dist/chunk-wvd3rsja.js +4 -0
- package/dist/chunk-wvd3rsja.js.map +13 -0
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +3 -4
- package/dist/index.bun.js +2 -2
- package/dist/index.bun.js.map +3 -4
- package/dist/index.node.cjs +2 -2
- package/dist/index.node.cjs.map +3 -4
- package/dist/index.node.mjs +2 -2
- package/dist/index.node.mjs.map +3 -4
- package/package.json +3 -3
- package/dist/chunk-02ytt443.js +0 -5
- package/dist/chunk-14jg2dxs.js +0 -5
- package/dist/chunk-14jg2dxs.js.map +0 -10
- package/dist/chunk-374tq8cw.js.map +0 -13
- package/dist/chunk-3rt7m395.js +0 -3
- package/dist/chunk-5ap8cyw0.js +0 -4
- package/dist/chunk-5ap8cyw0.js.map +0 -13
- package/dist/chunk-6d2104pn.js +0 -3
- package/dist/chunk-btz1s2ws.js +0 -3
- package/dist/chunk-btz1s2ws.js.map +0 -10
- package/dist/chunk-h7zpk6jq.js +0 -4
- package/dist/chunk-h7zpk6jq.js.map +0 -10
- package/dist/chunk-mm6wmg56.js +0 -4
- package/dist/chunk-p24n653d.js +0 -4
- package/dist/chunk-rht1286y.js +0 -3
- package/dist/chunk-rht1286y.js.map +0 -13
- package/dist/chunk-vt6b43b9.js +0 -3
- package/dist/chunk-vt6b43b9.js.map +0 -13
- package/dist/chunk-yd1vfk89.js +0 -4
- package/dist/chunk-yv042k8x.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as v,b as z,c as A}from"./chunk-6qtap428.js";import{h as P}from"./chunk-rta7shf1.js";function D(f){if(typeof f!=="object"||f===null)throw TypeError("options must be an object");let b=f;if(b.width!==void 0){if(typeof b.width!=="number"||!Number.isInteger(b.width)||b.width<=0)throw RangeError(`options.width must be a positive integer, got ${b.width}`)}if(b.height!==void 0){if(typeof b.height!=="number"||!Number.isInteger(b.height)||b.height<=0)throw RangeError(`options.height must be a positive integer, got ${b.height}`)}if(b.method!==void 0){let $=["triangular","catrom","mitchell","lanczos3"];if(!$.includes(b.method))throw TypeError(`options.method must be one of: ${$.join(", ")}, got ${b.method}`)}if(b.premultiply!==void 0&&typeof b.premultiply!=="boolean")throw TypeError(`options.premultiply must be boolean, got ${typeof b.premultiply}`);if(b.linearRGB!==void 0&&typeof b.linearRGB!=="boolean")throw TypeError(`options.linearRGB must be boolean, got ${typeof b.linearRGB}`)}var K,X=null;function H(){if(X===null||X.buffer!==K.memory.buffer)X=new Uint8Array(K.memory.buffer);return X}var O=0;function C(f,b){let $=b(f.length*1);return H().set(f,$/1),O=f.length,$}var Y=null;function L(){if(Y===null||Y.buffer!==K.memory.buffer)Y=new Int32Array(K.memory.buffer);return Y}var Z=null;function U(){if(Z===null||Z.buffer!==K.memory.buffer)Z=new Uint8ClampedArray(K.memory.buffer);return Z}function W(f,b){return U().subarray(f/1,f/1+b)}function V(f,b,$,j,J,G,N,Q){try{let B=K.__wbindgen_add_to_stack_pointer(-16);var T=C(f,K.__wbindgen_malloc),I=O;K.resize(B,T,I,b,$,j,J,G,N,Q);var q=L()[B/4+0],x=L()[B/4+1],w=W(q,x).slice();return K.__wbindgen_free(q,x*1),w}finally{K.__wbindgen_add_to_stack_pointer(16)}}async function h(f,b){if(typeof Response==="function"&&f instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function")try{return await WebAssembly.instantiateStreaming(f,b)}catch(j){if(f.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",j);else throw j}let $=await f.arrayBuffer();return await WebAssembly.instantiate($,b)}else{let $=await WebAssembly.instantiate(f,b);if($ instanceof WebAssembly.Instance)return{instance:$,module:f};else return $}}async function S(f){if(typeof f>"u")f=new URL("squoosh_resize_bg.wasm",import.meta.url);let b={};if(typeof f==="string"||typeof Request==="function"&&f instanceof Request||typeof URL==="function"&&f instanceof URL)f=fetch(f);let{instance:$,module:j}=await h(await f,b);return K=$.exports,S.__wbindgen_wasm_module=j,K}var F=S;var k=null,R=null;async function y(){if(k)return;if(R)return R;return R=(async()=>{try{let f=new URL(".",import.meta.url),b=["./wasm/squoosh_resize_bg.wasm","../wasm/squoosh_resize_bg.wasm"],$=null,j=null;for(let J of b)try{$=await v(J,f);break}catch(G){j=G instanceof Error?G:Error(String(G))}if(!$)throw j||Error("Could not load WASM binary from any path");try{await F($)}catch(J){if(J instanceof Error&&(J.message.includes("SharedArrayBuffer")||J.message.includes("first argument must be"))){if(typeof SharedArrayBuffer>"u")globalThis.SharedArrayBuffer=ArrayBuffer;try{await F($)}catch(G){throw Error(`WASM module initialization failed even with polyfill: ${G instanceof Error?G.message:String(G)}`)}}else throw J}k=V}catch(f){throw R=null,Error(`Failed to initialize resize WASM module: ${f instanceof Error?f.message:String(f)}`)}})(),R}async function E(f,b){if(P(f),D(b),await y(),!k)throw Error("Resize module not initialized");let{data:$,width:j,height:J}=f,G=b.width??j,N=b.height??J;if(b.width&&!b.height)N=Math.max(1,Math.round(J*b.width/j));else if(b.height&&!b.width)G=Math.max(1,Math.round(j*b.height/J));if(G<1||N<1)throw RangeError(`Output dimensions must be at least 1x1, got ${G}x${N}`);let Q=$ instanceof Uint8ClampedArray?new Uint8Array($.buffer,$.byteOffset,$.length):new Uint8Array($.buffer,$.byteOffset,$.length);return{data:k(Q,j,J,G,N,l(b),b.premultiply??!0,b.linearRGB??!0),width:G,height:N}}async function d(f,b,$){if($?.aborted)throw new DOMException("Aborted","AbortError");return E(f,b)}function l(f){return{triangular:0,catrom:1,mitchell:2,lanczos3:3}[f?.method??"lanczos3"]??3}if(typeof self<"u")self.onmessage=async(f)=>{let b=f.data;if(b?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let{id:$,type:j,payload:J}=b;try{if(j!=="resize:run")throw Error(`Unknown message type: ${j}`);let G=await E(J.image,J.options),N=new Uint8ClampedArray(G.data),Q={...G,data:N};z($,Q,[N.buffer])}catch(G){A($,G)}};export{d as resizeClient};
|
|
2
|
+
|
|
3
|
+
//# debugId=A0B09BBA455ABB1F64756E2164756E21
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"export function validateResizeOptions(options: unknown): asserts options is {\n width?: number;\n height?: number;\n method?: 'triangular' | 'catrom' | 'mitchell' | 'lanczos3';\n premultiply?: boolean;\n linearRGB?: boolean;\n} {\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('options must be an object');\n }\n\n const opts = options as Record<string, unknown>;\n\n if (opts.width !== undefined) {\n if (\n typeof opts.width !== 'number' ||\n !Number.isInteger(opts.width) ||\n opts.width <= 0\n ) {\n throw new RangeError(\n `options.width must be a positive integer, got ${opts.width}`\n );\n }\n }\n\n if (opts.height !== undefined) {\n if (\n typeof opts.height !== 'number' ||\n !Number.isInteger(opts.height) ||\n opts.height <= 0\n ) {\n throw new RangeError(\n `options.height must be a positive integer, got ${opts.height}`\n );\n }\n }\n\n if (opts.method !== undefined) {\n const validMethods = ['triangular', 'catrom', 'mitchell', 'lanczos3'];\n if (!validMethods.includes(opts.method as string)) {\n throw new TypeError(\n `options.method must be one of: ${validMethods.join(', ')}, got ${opts.method}`\n );\n }\n }\n\n if (opts.premultiply !== undefined && typeof opts.premultiply !== 'boolean') {\n throw new TypeError(\n `options.premultiply must be boolean, got ${typeof opts.premultiply}`\n );\n }\n\n if (opts.linearRGB !== undefined && typeof opts.linearRGB !== 'boolean') {\n throw new TypeError(\n `options.linearRGB must be boolean, got ${typeof opts.linearRGB}`\n );\n }\n}\n",
|
|
6
6
|
"\nlet wasm;\n\nlet cachegetUint8Memory0 = null;\nfunction getUint8Memory0() {\n if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {\n cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachegetUint8Memory0;\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1);\n getUint8Memory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nlet cachegetInt32Memory0 = null;\nfunction getInt32Memory0() {\n if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {\n cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);\n }\n return cachegetInt32Memory0;\n}\n\nlet cachegetUint8ClampedMemory0 = null;\nfunction getUint8ClampedMemory0() {\n if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {\n cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);\n }\n return cachegetUint8ClampedMemory0;\n}\n\nfunction getClampedArrayU8FromWasm0(ptr, len) {\n return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n/**\n* @param {Uint8Array} input_image\n* @param {number} input_width\n* @param {number} input_height\n* @param {number} output_width\n* @param {number} output_height\n* @param {number} typ_idx\n* @param {boolean} premultiply\n* @param {boolean} color_space_conversion\n* @returns {Uint8ClampedArray}\n*/\nexport function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);\n var len0 = WASM_VECTOR_LEN;\n wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);\n var r0 = getInt32Memory0()[retptr / 4 + 0];\n var r1 = getInt32Memory0()[retptr / 4 + 1];\n var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\nasync function load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nasync function init(input) {\n if (typeof input === 'undefined') {\n input = new URL('squoosh_resize_bg.wasm', import.meta.url);\n }\n const imports = {};\n\n\n if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {\n input = fetch(input);\n }\n\n\n\n const { instance, module } = await load(await input, imports);\n\n wasm = instance.exports;\n init.__wbindgen_wasm_module = module;\n\n return wasm;\n}\n\nexport default init;\n\n",
|
|
7
|
-
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type
|
|
7
|
+
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type ImageInput,\n loadWasmBinary,\n validateImageInput,\n respondSuccess,\n respondError,\n} from '@squoosh-kit/runtime';\nimport { validateResizeOptions } from './validators';\nimport type { ResizeOptions } from './types';\nimport * as squoosh_resize_module from '../wasm/squoosh_resize';\n\n// Define the type locally to avoid module resolution issues with the linter\ntype SquooshWasmResize = (\n input_image: Uint8Array,\n input_width: number,\n input_height: number,\n output_width: number,\n output_height: number,\n typ_idx: number,\n premultiply: boolean,\n color_space_conversion: boolean\n) => Uint8ClampedArray;\n\nlet wasmResize: SquooshWasmResize | null = null;\nlet initPromise: Promise<void> | null = null;\n\nasync function init(): Promise<void> {\n if (wasmResize) {\n return;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n try {\n // Use the worker's own import.meta.url as the base for resolving WASM paths\n const workerBaseUrl = new URL('.', import.meta.url);\n const wasmPathsToTry = [\n './wasm/squoosh_resize_bg.wasm',\n '../wasm/squoosh_resize_bg.wasm',\n ];\n\n let wasmBuffer: ArrayBuffer | null = null;\n let lastError: Error | null = null;\n for (const path of wasmPathsToTry) {\n try {\n wasmBuffer = await loadWasmBinary(path, workerBaseUrl);\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n if (!wasmBuffer) {\n throw (\n lastError || new Error('Could not load WASM binary from any path')\n );\n }\n\n // Initialize WASM module with the binary buffer\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (initError: unknown) {\n // If initialization fails due to SharedArrayBuffer issues, try with polyfill\n if (\n initError instanceof Error &&\n (initError.message.includes('SharedArrayBuffer') ||\n initError.message.includes('first argument must be'))\n ) {\n // Apply polyfill and retry\n if (typeof SharedArrayBuffer === 'undefined') {\n (\n globalThis as unknown as Record<string, typeof ArrayBuffer>\n ).SharedArrayBuffer = ArrayBuffer;\n }\n // Reload the module with polyfill in place\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (retryError) {\n throw new Error(\n `WASM module initialization failed even with polyfill: ${retryError instanceof Error ? retryError.message : String(retryError)}`\n );\n }\n } else {\n throw initError;\n }\n }\n // After initialization, the module's exported resize function is ready to use\n wasmResize = squoosh_resize_module.resize as unknown as SquooshWasmResize;\n } catch (error) {\n initPromise = null;\n throw new Error(\n `Failed to initialize resize WASM module: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n })();\n\n return initPromise;\n}\n\nasync function _resizeCore(\n image: ImageInput,\n options: ResizeOptions\n): Promise<ImageInput> {\n validateImageInput(image);\n validateResizeOptions(options);\n\n await init();\n if (!wasmResize) {\n throw new Error('Resize module not initialized');\n }\n\n const { data, width: inputWidth, height: inputHeight } = image;\n\n let outputWidth = options.width ?? inputWidth;\n let outputHeight = options.height ?? inputHeight;\n\n if (options.width && !options.height) {\n outputHeight = Math.max(\n 1,\n Math.round((inputHeight * options.width) / inputWidth)\n );\n } else if (options.height && !options.width) {\n outputWidth = Math.max(\n 1,\n Math.round((inputWidth * options.height) / inputHeight)\n );\n }\n\n if (outputWidth < 1 || outputHeight < 1) {\n throw new RangeError(\n `Output dimensions must be at least 1x1, got ${outputWidth}x${outputHeight}`\n );\n }\n\n // Create a zero-copy Uint8Array view if needed\n // (don't copy the buffer - just create a view on the same memory)\n const dataArray =\n data instanceof Uint8ClampedArray\n ? new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.length)\n : new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.length\n );\n\n const result = wasmResize(\n dataArray,\n inputWidth,\n inputHeight,\n outputWidth,\n outputHeight,\n getResizeMethod(options),\n options.premultiply ?? true,\n options.linearRGB ?? true\n );\n\n return {\n data: result,\n width: outputWidth,\n height: outputHeight,\n };\n}\n\nexport async function resizeClient(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n return _resizeCore(image, options);\n}\n\n/**\n * Map ResizeOptions method to WASM typ_idx parameter\n * typ_idx values (from Squoosh):\n * 0: Triangular - fastest, lowest quality\n * 1: Catrom - medium quality and speed\n * 2: Mitchell - good balance (default)\n * 3: Lanczos3 - highest quality, slowest\n */\nfunction getResizeMethod(options?: ResizeOptions): number {\n const methodMap: Record<string, number> = {\n triangular: 0,\n catrom: 1,\n mitchell: 2,\n lanczos3: 3,\n };\n return methodMap[options?.method ?? 'lanczos3'] ?? 3;\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const { id, type, payload } = data as WorkerRequest<{\n image: ImageInput;\n options: ResizeOptions;\n }>;\n\n try {\n if (type !== 'resize:run') {\n throw new Error(`Unknown message type: ${type}`);\n }\n\n const resultImage = await _resizeCore(payload.image, payload.options);\n\n // Create clean buffer\n const outputData = new Uint8ClampedArray(resultImage.data);\n const finalResult = { ...resultImage, data: outputData };\n\n respondSuccess(id, finalResult, [outputData.buffer]);\n } catch (error) {\n respondError(id, error);\n }\n };\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": "
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": "oGAAO,GAAS,CAAqB,CAAC,EAMpC,CACA,GAAI,OAAO,IAAY,UAAY,IAAY,KAC7C,MAAU,UAAU,2BAA2B,EAGjD,IAAM,EAAO,EAEb,GAAI,EAAK,QAAU,QACjB,GACE,OAAO,EAAK,QAAU,UACtB,CAAC,OAAO,UAAU,EAAK,KAAK,GAC5B,EAAK,OAAS,EAEd,MAAU,WACR,iDAAiD,EAAK,OACxD,EAIJ,GAAI,EAAK,SAAW,QAClB,GACE,OAAO,EAAK,SAAW,UACvB,CAAC,OAAO,UAAU,EAAK,MAAM,GAC7B,EAAK,QAAU,EAEf,MAAU,WACR,kDAAkD,EAAK,QACzD,EAIJ,GAAI,EAAK,SAAW,OAAW,CAC7B,IAAM,EAAe,CAAC,aAAc,SAAU,WAAY,UAAU,EACpE,GAAI,CAAC,EAAa,SAAS,EAAK,MAAgB,EAC9C,MAAU,UACR,kCAAkC,EAAa,KAAK,IAAI,UAAU,EAAK,QACzE,EAIJ,GAAI,EAAK,cAAgB,QAAa,OAAO,EAAK,cAAgB,UAChE,MAAU,UACR,4CAA4C,OAAO,EAAK,aAC1D,EAGF,GAAI,EAAK,YAAc,QAAa,OAAO,EAAK,YAAc,UAC5D,MAAU,UACR,0CAA0C,OAAO,EAAK,WACxD,ECtDJ,IAAI,EAEA,EAAuB,KAC3B,SAAS,CAAe,EAAG,CACvB,GAAI,IAAyB,MAAQ,EAAqB,SAAW,EAAK,OAAO,OAC7E,EAAuB,IAAI,WAAW,EAAK,OAAO,MAAM,EAE5D,OAAO,EAGX,IAAI,EAAkB,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,EAAO,CAAO,EAWnC,SAAS,CAAe,CAAC,EAAiC,CAOxD,MAN0C,CACxC,WAAY,EACZ,OAAQ,EACR,SAAU,EACV,SAAU,CACZ,EACiB,GAAS,QAAU,aAAe,EAMrD,GAAI,OAAO,KAAS,IAClB,KAAK,UAAY,MAAO,IAAwB,CAC9C,IAAM,EAAO,EAAM,KAGnB,GAAI,GAAM,OAAS,cAAe,CAChC,KAAK,YAAY,CAAE,KAAM,cAAe,CAAC,EACzC,OAGF,IAAQ,KAAI,OAAM,WAAY,EAK9B,GAAI,CACF,GAAI,IAAS,aACX,MAAU,MAAM,yBAAyB,GAAM,EAGjD,IAAM,EAAc,MAAM,EAAY,EAAQ,MAAO,EAAQ,OAAO,EAG9D,EAAa,IAAI,kBAAkB,EAAY,IAAI,EACnD,EAAc,IAAK,EAAa,KAAM,CAAW,EAEvD,EAAe,EAAI,EAAa,CAAC,EAAW,MAAM,CAAC,EACnD,MAAO,EAAO,CACd,EAAa,EAAI,CAAK",
|
|
10
|
+
"debugId": "A0B09BBA455ABB1F64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as v,b as z,c as A}from"./chunk-f8hc5gnf.js";import{h as P}from"./chunk-d3fxpzrq.js";function D(f){if(typeof f!=="object"||f===null)throw TypeError("options must be an object");let b=f;if(b.width!==void 0){if(typeof b.width!=="number"||!Number.isInteger(b.width)||b.width<=0)throw RangeError(`options.width must be a positive integer, got ${b.width}`)}if(b.height!==void 0){if(typeof b.height!=="number"||!Number.isInteger(b.height)||b.height<=0)throw RangeError(`options.height must be a positive integer, got ${b.height}`)}if(b.method!==void 0){let $=["triangular","catrom","mitchell","lanczos3"];if(!$.includes(b.method))throw TypeError(`options.method must be one of: ${$.join(", ")}, got ${b.method}`)}if(b.premultiply!==void 0&&typeof b.premultiply!=="boolean")throw TypeError(`options.premultiply must be boolean, got ${typeof b.premultiply}`);if(b.linearRGB!==void 0&&typeof b.linearRGB!=="boolean")throw TypeError(`options.linearRGB must be boolean, got ${typeof b.linearRGB}`)}var K,X=null;function H(){if(X===null||X.buffer!==K.memory.buffer)X=new Uint8Array(K.memory.buffer);return X}var O=0;function C(f,b){let $=b(f.length*1);return H().set(f,$/1),O=f.length,$}var Y=null;function L(){if(Y===null||Y.buffer!==K.memory.buffer)Y=new Int32Array(K.memory.buffer);return Y}var Z=null;function U(){if(Z===null||Z.buffer!==K.memory.buffer)Z=new Uint8ClampedArray(K.memory.buffer);return Z}function W(f,b){return U().subarray(f/1,f/1+b)}function V(f,b,$,j,J,G,N,Q){try{let B=K.__wbindgen_add_to_stack_pointer(-16);var T=C(f,K.__wbindgen_malloc),I=O;K.resize(B,T,I,b,$,j,J,G,N,Q);var q=L()[B/4+0],x=L()[B/4+1],w=W(q,x).slice();return K.__wbindgen_free(q,x*1),w}finally{K.__wbindgen_add_to_stack_pointer(16)}}async function h(f,b){if(typeof Response==="function"&&f instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function")try{return await WebAssembly.instantiateStreaming(f,b)}catch(j){if(f.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",j);else throw j}let $=await f.arrayBuffer();return await WebAssembly.instantiate($,b)}else{let $=await WebAssembly.instantiate(f,b);if($ instanceof WebAssembly.Instance)return{instance:$,module:f};else return $}}async function S(f){if(typeof f>"u")f=new URL("squoosh_resize_bg.wasm",import.meta.url);let b={};if(typeof f==="string"||typeof Request==="function"&&f instanceof Request||typeof URL==="function"&&f instanceof URL)f=fetch(f);let{instance:$,module:j}=await h(await f,b);return K=$.exports,S.__wbindgen_wasm_module=j,K}var F=S;var k=null,R=null;async function y(){if(k)return;if(R)return R;return R=(async()=>{try{let f=new URL(".",import.meta.url),b=["./wasm/squoosh_resize_bg.wasm","../wasm/squoosh_resize_bg.wasm"],$=null,j=null;for(let J of b)try{$=await v(J,f);break}catch(G){j=G instanceof Error?G:Error(String(G))}if(!$)throw j||Error("Could not load WASM binary from any path");try{await F($)}catch(J){if(J instanceof Error&&(J.message.includes("SharedArrayBuffer")||J.message.includes("first argument must be"))){if(typeof SharedArrayBuffer>"u")globalThis.SharedArrayBuffer=ArrayBuffer;try{await F($)}catch(G){throw Error(`WASM module initialization failed even with polyfill: ${G instanceof Error?G.message:String(G)}`)}}else throw J}k=V}catch(f){throw R=null,Error(`Failed to initialize resize WASM module: ${f instanceof Error?f.message:String(f)}`)}})(),R}async function E(f,b){if(P(f),D(b),await y(),!k)throw Error("Resize module not initialized");let{data:$,width:j,height:J}=f,G=b.width??j,N=b.height??J;if(b.width&&!b.height)N=Math.max(1,Math.round(J*b.width/j));else if(b.height&&!b.width)G=Math.max(1,Math.round(j*b.height/J));if(G<1||N<1)throw RangeError(`Output dimensions must be at least 1x1, got ${G}x${N}`);let Q=$ instanceof Uint8ClampedArray?new Uint8Array($.buffer,$.byteOffset,$.length):new Uint8Array($.buffer,$.byteOffset,$.length);return{data:k(Q,j,J,G,N,l(b),b.premultiply??!0,b.linearRGB??!0),width:G,height:N}}async function d(f,b,$){if($?.aborted)throw new DOMException("Aborted","AbortError");return E(f,b)}function l(f){return{triangular:0,catrom:1,mitchell:2,lanczos3:3}[f?.method??"lanczos3"]??3}if(typeof self<"u")self.onmessage=async(f)=>{let b=f.data;if(b?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let{id:$,type:j,payload:J}=b;try{if(j!=="resize:run")throw Error(`Unknown message type: ${j}`);let G=await E(J.image,J.options),N=new Uint8ClampedArray(G.data),Q={...G,data:N};z($,Q,[N.buffer])}catch(G){A($,G)}};export{d as resizeClient};
|
|
2
|
+
|
|
3
|
+
//# debugId=A0B09BBA455ABB1F64756E2164756E21
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"export function validateResizeOptions(options: unknown): asserts options is {\n width?: number;\n height?: number;\n method?: 'triangular' | 'catrom' | 'mitchell' | 'lanczos3';\n premultiply?: boolean;\n linearRGB?: boolean;\n} {\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('options must be an object');\n }\n\n const opts = options as Record<string, unknown>;\n\n if (opts.width !== undefined) {\n if (\n typeof opts.width !== 'number' ||\n !Number.isInteger(opts.width) ||\n opts.width <= 0\n ) {\n throw new RangeError(\n `options.width must be a positive integer, got ${opts.width}`\n );\n }\n }\n\n if (opts.height !== undefined) {\n if (\n typeof opts.height !== 'number' ||\n !Number.isInteger(opts.height) ||\n opts.height <= 0\n ) {\n throw new RangeError(\n `options.height must be a positive integer, got ${opts.height}`\n );\n }\n }\n\n if (opts.method !== undefined) {\n const validMethods = ['triangular', 'catrom', 'mitchell', 'lanczos3'];\n if (!validMethods.includes(opts.method as string)) {\n throw new TypeError(\n `options.method must be one of: ${validMethods.join(', ')}, got ${opts.method}`\n );\n }\n }\n\n if (opts.premultiply !== undefined && typeof opts.premultiply !== 'boolean') {\n throw new TypeError(\n `options.premultiply must be boolean, got ${typeof opts.premultiply}`\n );\n }\n\n if (opts.linearRGB !== undefined && typeof opts.linearRGB !== 'boolean') {\n throw new TypeError(\n `options.linearRGB must be boolean, got ${typeof opts.linearRGB}`\n );\n }\n}\n",
|
|
6
6
|
"\nlet wasm;\n\nlet cachegetUint8Memory0 = null;\nfunction getUint8Memory0() {\n if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {\n cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachegetUint8Memory0;\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1);\n getUint8Memory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nlet cachegetInt32Memory0 = null;\nfunction getInt32Memory0() {\n if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {\n cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);\n }\n return cachegetInt32Memory0;\n}\n\nlet cachegetUint8ClampedMemory0 = null;\nfunction getUint8ClampedMemory0() {\n if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {\n cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);\n }\n return cachegetUint8ClampedMemory0;\n}\n\nfunction getClampedArrayU8FromWasm0(ptr, len) {\n return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n/**\n* @param {Uint8Array} input_image\n* @param {number} input_width\n* @param {number} input_height\n* @param {number} output_width\n* @param {number} output_height\n* @param {number} typ_idx\n* @param {boolean} premultiply\n* @param {boolean} color_space_conversion\n* @returns {Uint8ClampedArray}\n*/\nexport function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);\n var len0 = WASM_VECTOR_LEN;\n wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);\n var r0 = getInt32Memory0()[retptr / 4 + 0];\n var r1 = getInt32Memory0()[retptr / 4 + 1];\n var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\nasync function load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nasync function init(input) {\n if (typeof input === 'undefined') {\n input = new URL('squoosh_resize_bg.wasm', import.meta.url);\n }\n const imports = {};\n\n\n if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {\n input = fetch(input);\n }\n\n\n\n const { instance, module } = await load(await input, imports);\n\n wasm = instance.exports;\n init.__wbindgen_wasm_module = module;\n\n return wasm;\n}\n\nexport default init;\n\n",
|
|
7
|
-
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type
|
|
7
|
+
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type ImageInput,\n loadWasmBinary,\n validateImageInput,\n respondSuccess,\n respondError,\n} from '@squoosh-kit/runtime';\nimport { validateResizeOptions } from './validators';\nimport type { ResizeOptions } from './types';\nimport * as squoosh_resize_module from '../wasm/squoosh_resize';\n\n// Define the type locally to avoid module resolution issues with the linter\ntype SquooshWasmResize = (\n input_image: Uint8Array,\n input_width: number,\n input_height: number,\n output_width: number,\n output_height: number,\n typ_idx: number,\n premultiply: boolean,\n color_space_conversion: boolean\n) => Uint8ClampedArray;\n\nlet wasmResize: SquooshWasmResize | null = null;\nlet initPromise: Promise<void> | null = null;\n\nasync function init(): Promise<void> {\n if (wasmResize) {\n return;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n try {\n // Use the worker's own import.meta.url as the base for resolving WASM paths\n const workerBaseUrl = new URL('.', import.meta.url);\n const wasmPathsToTry = [\n './wasm/squoosh_resize_bg.wasm',\n '../wasm/squoosh_resize_bg.wasm',\n ];\n\n let wasmBuffer: ArrayBuffer | null = null;\n let lastError: Error | null = null;\n for (const path of wasmPathsToTry) {\n try {\n wasmBuffer = await loadWasmBinary(path, workerBaseUrl);\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n if (!wasmBuffer) {\n throw (\n lastError || new Error('Could not load WASM binary from any path')\n );\n }\n\n // Initialize WASM module with the binary buffer\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (initError: unknown) {\n // If initialization fails due to SharedArrayBuffer issues, try with polyfill\n if (\n initError instanceof Error &&\n (initError.message.includes('SharedArrayBuffer') ||\n initError.message.includes('first argument must be'))\n ) {\n // Apply polyfill and retry\n if (typeof SharedArrayBuffer === 'undefined') {\n (\n globalThis as unknown as Record<string, typeof ArrayBuffer>\n ).SharedArrayBuffer = ArrayBuffer;\n }\n // Reload the module with polyfill in place\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (retryError) {\n throw new Error(\n `WASM module initialization failed even with polyfill: ${retryError instanceof Error ? retryError.message : String(retryError)}`\n );\n }\n } else {\n throw initError;\n }\n }\n // After initialization, the module's exported resize function is ready to use\n wasmResize = squoosh_resize_module.resize as unknown as SquooshWasmResize;\n } catch (error) {\n initPromise = null;\n throw new Error(\n `Failed to initialize resize WASM module: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n })();\n\n return initPromise;\n}\n\nasync function _resizeCore(\n image: ImageInput,\n options: ResizeOptions\n): Promise<ImageInput> {\n validateImageInput(image);\n validateResizeOptions(options);\n\n await init();\n if (!wasmResize) {\n throw new Error('Resize module not initialized');\n }\n\n const { data, width: inputWidth, height: inputHeight } = image;\n\n let outputWidth = options.width ?? inputWidth;\n let outputHeight = options.height ?? inputHeight;\n\n if (options.width && !options.height) {\n outputHeight = Math.max(\n 1,\n Math.round((inputHeight * options.width) / inputWidth)\n );\n } else if (options.height && !options.width) {\n outputWidth = Math.max(\n 1,\n Math.round((inputWidth * options.height) / inputHeight)\n );\n }\n\n if (outputWidth < 1 || outputHeight < 1) {\n throw new RangeError(\n `Output dimensions must be at least 1x1, got ${outputWidth}x${outputHeight}`\n );\n }\n\n // Create a zero-copy Uint8Array view if needed\n // (don't copy the buffer - just create a view on the same memory)\n const dataArray =\n data instanceof Uint8ClampedArray\n ? new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.length)\n : new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.length\n );\n\n const result = wasmResize(\n dataArray,\n inputWidth,\n inputHeight,\n outputWidth,\n outputHeight,\n getResizeMethod(options),\n options.premultiply ?? true,\n options.linearRGB ?? true\n );\n\n return {\n data: result,\n width: outputWidth,\n height: outputHeight,\n };\n}\n\nexport async function resizeClient(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n return _resizeCore(image, options);\n}\n\n/**\n * Map ResizeOptions method to WASM typ_idx parameter\n * typ_idx values (from Squoosh):\n * 0: Triangular - fastest, lowest quality\n * 1: Catrom - medium quality and speed\n * 2: Mitchell - good balance (default)\n * 3: Lanczos3 - highest quality, slowest\n */\nfunction getResizeMethod(options?: ResizeOptions): number {\n const methodMap: Record<string, number> = {\n triangular: 0,\n catrom: 1,\n mitchell: 2,\n lanczos3: 3,\n };\n return methodMap[options?.method ?? 'lanczos3'] ?? 3;\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const { id, type, payload } = data as WorkerRequest<{\n image: ImageInput;\n options: ResizeOptions;\n }>;\n\n try {\n if (type !== 'resize:run') {\n throw new Error(`Unknown message type: ${type}`);\n }\n\n const resultImage = await _resizeCore(payload.image, payload.options);\n\n // Create clean buffer\n const outputData = new Uint8ClampedArray(resultImage.data);\n const finalResult = { ...resultImage, data: outputData };\n\n respondSuccess(id, finalResult, [outputData.buffer]);\n } catch (error) {\n respondError(id, error);\n }\n };\n}\n"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B,CAC9C,IAAM,EAAO,EAAM,KAGnB,GAAI,GAAM,OAAS,cAAe,CAChC,KAAK,YAAY,CAAE,KAAM,cAAe,CAAC,EACzC,OAGF,IAAQ,KAAI,OAAM,WAAY,EAK9B,GAAI,CACF,GAAI,IAAS,aACX,MAAU,MAAM,yBAAyB,GAAM,EAGjD,IAAM,EAAc,MAAM,EAAY,EAAQ,MAAO,EAAQ,OAAO,EAG9D,EAAa,IAAI,kBAAkB,EAAY,IAAI,EACnD,EAAc,IAAK,EAAa,KAAM,CAAW,EAEvD,EAAe,EAAI,EAAa,CAAC,EAAW,MAAM,CAAC,EACnD,MAAO,EAAO,CACd,EAAa,EAAI,CAAK",
|
|
10
|
+
"debugId": "A0B09BBA455ABB1F64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{d as J,e as K,f as G,g as H}from"./chunk-rta7shf1.js";async function I(z){let j=z.toString();if(H()&&!G()&&(j.startsWith("file:")||!j.includes("://")))try{let q=await import("fs/promises"),D=z instanceof URL?z:j;return(await q.readFile(D)).buffer}catch(q){console.warn("[io] fs read failed, falling back to fetch",q)}let C=await fetch(j);if(!C.ok)throw Error(`Failed to fetch ${j}: ${C.statusText}`);return C.arrayBuffer()}async function R(z,j){let C=j?typeof j==="string"?new URL(".",j):new URL(".",j.href):new URL(".",import.meta.url),q=new URL(z,C);console.log(`[WasmLoader] Loading WASM from relative path: ${z}`),console.log(`[WasmLoader] Base URL (import.meta.url): ${C.href}`),console.log(`[WasmLoader] Constructed full URL: ${q.href}`);try{return await I(q)}catch(D){throw console.error(`[WasmLoader] CRITICAL: Fetching WASM binary from ${q.href} failed.`,D),D}}function W(z,j,C=[]){let q={id:z,ok:!0,data:j},D=C.filter((E)=>!(E instanceof SharedArrayBuffer));self.postMessage(q,D)}function X(z,j){let C=j instanceof Error?j.message:String(j),q={id:z,ok:!1,error:C};self.postMessage(q)}
|
|
2
|
+
export{R as a,W as b,X as c};
|
|
3
|
+
|
|
4
|
+
//# debugId=B06AB8414FB50F3F64756E2164756E21
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/src/io.ts", "../../runtime/src/wasm-loader.ts", "../../runtime/src/worker-utils.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { isNode, isBun } from './env';\n\n/**\n * Reads a file as an ArrayBuffer, handling platform differences.\n * - Node.js: Uses fs/promises for file:// URLs (prevents fetch errors)\n * - Browser/Bun: Uses standard fetch\n */\nexport async function readFileAsBuffer(\n url: URL | string\n): Promise<ArrayBuffer> {\n const urlStr = url.toString();\n\n // Node.js (non-Bun) file:// handling\n if (\n isNode() &&\n !isBun() &&\n (urlStr.startsWith('file:') || !urlStr.includes('://'))\n ) {\n try {\n // Dynamic import prevents bundling 'fs' in browser builds\n const fs = await import('fs/promises');\n const path = url instanceof URL ? url : urlStr;\n const buffer = await fs.readFile(path);\n return buffer.buffer as ArrayBuffer;\n } catch (e) {\n console.warn('[io] fs read failed, falling back to fetch', e);\n }\n }\n\n // Standard fetch (Browser, Bun, Node http)\n const res = await fetch(urlStr);\n if (!res.ok) throw new Error(`Failed to fetch ${urlStr}: ${res.statusText}`);\n return res.arrayBuffer();\n}\n",
|
|
6
|
+
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nimport { readFileAsBuffer } from './io';\n\nexport async function loadWasmBinary(\n relativePath: string,\n baseUrlOverride?: string | URL\n): Promise<ArrayBuffer> {\n // Get the base URL depending on the environment (worker or main thread)\n // If a base URL is provided, use it; otherwise use import.meta.url from this module\n // In a worker, import.meta.url is the worker's own URL.\n // In the main thread, it's the URL of the current module.\n const baseUrl = baseUrlOverride\n ? typeof baseUrlOverride === 'string'\n ? new URL('.', baseUrlOverride)\n : new URL('.', baseUrlOverride.href)\n : new URL('.', import.meta.url);\n const fullUrl = new URL(relativePath, baseUrl);\n\n console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);\n console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);\n console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);\n\n try {\n return await readFileAsBuffer(fullUrl);\n } catch (error) {\n console.error(\n `[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(/* @vite-ignore */ modulePath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n\n return await import(/* @vite-ignore */ resolvedPath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(/* @vite-ignore */ modulePath, import.meta.url);\n\n return await import(/* @vite-ignore */ url.href);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`\n );\n }\n}\n",
|
|
7
|
+
"import type { WorkerResponse } from './worker-call';\n\n/**\n * Defines the subset of DedicatedWorkerGlobalScope needed for posting messages.\n * Used to cast 'self' to resolve TypeScript overload conflicts between\n * DOM types and Bun types (which define Transferable differently).\n */\ninterface WorkerScope {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\n/**\n * Safely sends a success response from a worker, handling Transferables automatically.\n * Filters out SharedArrayBuffers which cannot be transferred.\n */\nexport function respondSuccess<T>(\n id: number,\n data: T,\n transfer: Transferable[] = []\n) {\n const response: WorkerResponse<T> = { id, ok: true, data };\n\n // Safety check: SharedArrayBuffer cannot be in the transfer list\n const safeTransfer = transfer.filter(\n (t) => !(t instanceof SharedArrayBuffer)\n );\n\n // Cast self to WorkerScope to avoid TypeScript errors where it confuses\n // the worker global scope with the window scope (expecting targetOrigin),\n // or conflicts between DOM Transferable and Bun.Transferable types.\n (self as unknown as WorkerScope).postMessage(response, safeTransfer);\n}\n\n/**\n * Sends an error response from a worker.\n */\nexport function respondError(id: number, error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n const response: WorkerResponse<never> = { id, ok: false, error: msg };\n self.postMessage(response);\n}\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": "6DAOA,eAAsB,CAAgB,CACpC,EACsB,CACtB,IAAM,EAAS,EAAI,SAAS,EAG5B,GACE,EAAO,GACP,CAAC,EAAM,IACN,EAAO,WAAW,OAAO,GAAK,CAAC,EAAO,SAAS,KAAK,GAErD,GAAI,CAEF,IAAM,EAAK,KAAa,uBAClB,EAAO,aAAe,IAAM,EAAM,EAExC,OADe,MAAM,EAAG,SAAS,CAAI,GACvB,OACd,MAAO,EAAG,CACV,QAAQ,KAAK,6CAA8C,CAAC,EAKhE,IAAM,EAAM,MAAM,MAAM,CAAM,EAC9B,GAAI,CAAC,EAAI,GAAI,MAAU,MAAM,mBAAmB,MAAW,EAAI,YAAY,EAC3E,OAAO,EAAI,YAAY,ECtBzB,eAAsB,CAAc,CAClC,EACA,EACsB,CAKtB,IAAM,EAAU,EACZ,OAAO,IAAoB,SACzB,IAAI,IAAI,IAAK,CAAe,EAC5B,IAAI,IAAI,IAAK,EAAgB,IAAI,EACnC,IAAI,IAAI,IAAK,YAAY,GAAG,EAC1B,EAAU,IAAI,IAAI,EAAc,CAAO,EAE7C,QAAQ,IAAI,iDAAiD,GAAc,EAC3E,QAAQ,IAAI,4CAA4C,EAAQ,MAAM,EACtE,QAAQ,IAAI,sCAAsC,EAAQ,MAAM,EAEhE,GAAI,CACF,OAAO,MAAM,EAAiB,CAAO,EACrC,MAAO,EAAO,CAKd,MAJA,QAAQ,MACN,oDAAoD,EAAQ,eAC5D,CACF,EACM,GCrBH,SAAS,CAAiB,CAC/B,EACA,EACA,EAA2B,CAAC,EAC5B,CACA,IAAM,EAA8B,CAAE,KAAI,GAAI,GAAM,MAAK,EAGnD,EAAe,EAAS,OAC5B,CAAC,IAAM,EAAE,aAAa,kBACxB,EAKC,KAAgC,YAAY,EAAU,CAAY,EAM9D,SAAS,CAAY,CAAC,EAAY,EAAgB,CACvD,IAAM,EAAM,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAC3D,EAAkC,CAAE,KAAI,GAAI,GAAO,MAAO,CAAI,EACpE,KAAK,YAAY,CAAQ",
|
|
10
|
+
"debugId": "B06AB8414FB50F3F64756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as G,b as X,c as C}from"./chunk-f8hc5gnf.js";import{h as Q}from"./chunk-d3fxpzrq.js";var N=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]));var B=null,u=null;async function R(){if(B!==null)return B;if(u)return u;return u=(async()=>{try{return B=await N(),B}catch(A){return B=!1,console.warn("SIMD detection failed, falling back to standard WASM modules:",A),!1}})(),u}function E(A){if(A===void 0)return;if(typeof A!=="object"||A===null)throw TypeError("options must be an object or undefined");let y=A;if("quality"in y&&y.quality!==void 0){let n=y.quality;if(Number.isNaN(n))throw RangeError("quality must be a valid number in the range 0-100, got NaN");if(typeof n!=="number")throw TypeError("quality must be a number");if(!Number.isInteger(n))throw RangeError("quality must be an integer in the range 0-100, got floating point");if(n<0||n>100)throw RangeError(`quality must be in the range 0-100, got ${n}`)}}var W=null;async function j(){if(W)return W;let A=await R(),y=A?"webp/webp_enc_simd.js":"webp/webp_enc.js";try{console.log("[WebP Worker] Initializing. SIMD support:",A),console.log(`[WebP Worker] Attempting to import module from path: ${y}`);let n=typeof self<"u"?self:globalThis;if(!n.location)n.location={href:import.meta.url};if(typeof self>"u"&&typeof globalThis<"u")globalThis.self=globalThis;let r,f=["./wasm/"+y,"../wasm/"+y],e=null;for(let a of f)try{r=(await import(a)).default,console.log(`[WebP Worker] Successfully loaded module from: ${a}`);break}catch(b){e=b instanceof Error?b:Error(String(b)),console.warn(`[WebP Worker] Failed to load from ${a}, trying next path...`)}if(!r)throw e||Error("Could not load WebP module from any path");console.log("[WebP Worker] Module factory loaded successfully.");let l=A?["./wasm/webp/webp_enc_simd.wasm","../wasm/webp/webp_enc_simd.wasm"]:["./wasm/webp/webp_enc.wasm","../wasm/webp/webp_enc.wasm"];return console.log(`[WebP Worker] Preparing to load WASM binary. Will try paths: ${l.join(", ")}`),W=await(async(a,b)=>{let v=new URL(".",import.meta.url),g=null;for(let c of b)try{console.log(`[WebP Worker] Calling loadWasmBinary with path: ${c}`);let w=await G(c,v);console.log(`[WebP Worker] Successfully fetched WASM binary from ${c}. Size: ${w.byteLength} bytes.`);let x=typeof self<"u"?self:globalThis;if(!x.location)x.location={href:import.meta.url};if(typeof self>"u"&&typeof globalThis<"u")globalThis.self=globalThis;return await a({noInitialRun:!0,wasmBinary:w})}catch(w){g=w instanceof Error?w:Error(String(w)),console.warn(`[WebP Worker] Failed to load WASM from ${c}, trying next path...`)}throw g||Error("Could not load WASM binary from any of the attempted paths")})(r,l),console.log("[WebP Worker] WebP module initialized successfully."),W}catch(n){throw console.error(`[WebP Worker] CRITICAL: Failed to load WebP module from path: ${y}`,n),n}}function I(A){return{quality:A?.quality??75,target_size:0,target_PSNR:0,method:A?.method??4,sns_strength:A?.sns_strength??50,filter_strength:A?.filter_strength??60,filter_sharpness:A?.filter_sharpness??0,filter_type:A?.filter_type??1,partitions:A?.partitions??0,segments:A?.segments??4,pass:A?.pass??1,show_compressed:0,preprocessing:A?.preprocessing??0,autofilter:A?.autofilter??0,partition_limit:0,alpha_compression:A?.alpha_compression??1,alpha_filtering:A?.alpha_filtering??1,alpha_quality:A?.alpha_quality??A?.quality??75,lossless:A?.lossless?1:0,exact:A?.exact??0,image_hint:A?.image_hint??0,emulate_jpeg_size:0,thread_level:0,low_memory:0,near_lossless:A?.near_lossless??A?.quality??75,use_delta_palette:0,use_sharp_yuv:A?.use_sharp_yuv??0}}async function z(A,y,n){if(Q(A),E(y),n?.aborted)throw new DOMException("Aborted","AbortError");let{width:r,height:f,data:e}=A;if(!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw Error("Image data must be Uint8Array or Uint8ClampedArray");let l=performance.now(),U=await j(),a=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] module loading took ${(a-l).toFixed(2)}ms`),console.log(`[WebP] Module type: ${W&&"encode"in W?"Ready":"Unknown"}`);if(n?.aborted)throw new DOMException("Aborted","AbortError");let b=I(y),v=e instanceof Uint8ClampedArray?new Uint8Array(e.buffer,e.byteOffset,e.length):new Uint8Array(e.buffer,e.byteOffset,e.length);if(typeof console<"u"&&console.log)console.log("[WebP] encode options:",b);let g=performance.now(),c=U.encode(v,r,f,b),w=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] actual encoding took ${(w-g).toFixed(2)}ms`);if(n?.aborted)throw new DOMException("Aborted","AbortError");if(!c)throw Error("WebP encoding failed");return c}if(typeof self<"u")self.onmessage=async(A)=>{let y=A.data;if(y?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let n=y;try{if(n.type==="webp:encode"){let{image:r,options:f}=n.payload,e=performance.now(),l=new AbortController,U=await z(r,f,l.signal),a=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP Worker] encode took ${(a-e).toFixed(2)}ms`);let b=new Uint8Array(U);X(n.id,b,[b.buffer])}else C(n.id,`Unknown message type: ${n.type}`)}catch(r){C(n.id,r)}};export{z as webpEncodeClient};
|
|
2
|
+
|
|
3
|
+
//# debugId=E34C30C32159311B64756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../node_modules/.bun/wasm-feature-detect@1.8.0/node_modules/wasm-feature-detect/dist/esm/index.js", "../../runtime/src/simd-detector.ts", "../../webp/src/validators.ts", "../../webp/src/webp.worker.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"export const bigInt=()=>(async e=>{try{return(await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0))===BigInt(0)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,126,1,126,3,2,1,0,7,5,1,1,98,0,0,10,6,1,4,0,32,0,11])),bulkMemory=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),exceptions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),exceptionsFinal=()=>(async()=>{try{return new WebAssembly.Module(Uint8Array.from(atob(\"AGFzbQEAAAABBAFgAAADAgEAChABDgACaR9AAQMAAAsACxoL\"),(e=>e.codePointAt(0)))),!0}catch(e){return!1}})(),extendedConst=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,0,1,11,9,1,0,65,1,65,2,106,11,0])),gc=()=>(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,95,1,120,0])))(),jsStringBuiltins=()=>(async()=>{try{return await WebAssembly.instantiate(Uint8Array.from(atob(\"AGFzbQEAAAABBgFgAW8BfwIXAQ53YXNtOmpzLXN0cmluZwR0ZXN0AAA=\"),(e=>e.codePointAt(0))),{},{builtins:[\"js-string\"]}),!0}catch(e){return!1}})(),jspi=()=>(async()=>\"Suspending\"in WebAssembly)(),memory64=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,4,1])),multiMemory=()=>(async()=>{try{return new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,5,5,2,0,0,0,0])),!0}catch(e){return!1}})(),multiValue=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,0,2,127,127,3,2,1,0,10,8,1,6,0,65,0,65,0,11])),mutableGlobals=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,2,8,1,1,97,1,98,3,127,1,6,6,1,127,1,65,0,11,7,5,1,1,97,3,1])),referenceTypes=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,208,112,26,11])),relaxedSimd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11])),saturatedFloatToInt=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])),signExtensions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])),simd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),streamingCompilation=()=>(async()=>\"compileStreaming\"in WebAssembly)(),tailCall=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,6,1,4,0,18,0,11])),threads=()=>(async e=>{try{return\"undefined\"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),typeReflection=()=>(async()=>\"Function\"in WebAssembly)(),typedFunctionReferences=()=>(async()=>{try{return new WebAssembly.Module(Uint8Array.from(atob(\"AGFzbQEAAAABEANgAX8Bf2ABZAABf2AAAX8DBAMBAAIJBQEDAAEBChwDCwBBCkEqIAAUAGoLBwAgAEEBagsGANIBEAAL\"),(e=>e.codePointAt(0)))),!0}catch(e){return!1}})();\n",
|
|
6
|
+
"/**\n * SIMD (Single Instruction Multiple Data) detection for WebAssembly\n *\n * SIMD support allows WebAssembly modules to perform vectorized operations,\n * significantly improving performance for operations like image encoding.\n * Some browsers and runtimes don't support SIMD yet, so we need to detect it.\n */\n\nimport { simd } from 'wasm-feature-detect';\n\nlet simdSupported: boolean | null = null;\nlet simdDetectionPromise: Promise<boolean> | null = null;\n\n/**\n * Detects if WebAssembly SIMD is supported in the current environment\n * @returns Promise<boolean> - true if SIMD is supported, false otherwise\n */\nexport async function detectSimd(): Promise<boolean> {\n // Return cached result if already detected\n if (simdSupported !== null) {\n return simdSupported;\n }\n\n // Return existing detection promise if detection is in progress\n if (simdDetectionPromise) {\n return simdDetectionPromise;\n }\n\n // Perform SIMD detection\n simdDetectionPromise = (async () => {\n try {\n simdSupported = await simd();\n return simdSupported;\n } catch (error) {\n // If detection fails, assume SIMD is not supported\n simdSupported = false;\n console.warn(\n 'SIMD detection failed, falling back to standard WASM modules:',\n error\n );\n return false;\n }\n })();\n\n return simdDetectionPromise;\n}\n\n/**\n * Reset SIMD detection cache (useful for testing)\n */\nexport function resetSimdCache(): void {\n simdSupported = null;\n simdDetectionPromise = null;\n}\n",
|
|
7
|
+
"export function validateWebpOptions(\n options: unknown\n): asserts options is Record<string, unknown> | undefined {\n if (options === undefined) {\n return;\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('options must be an object or undefined');\n }\n\n const opts = options as Record<string, unknown>;\n\n if ('quality' in opts && opts.quality !== undefined) {\n const quality = opts.quality;\n\n if (Number.isNaN(quality)) {\n throw new RangeError(\n 'quality must be a valid number in the range 0-100, got NaN'\n );\n }\n\n if (typeof quality !== 'number') {\n throw new TypeError('quality must be a number');\n }\n\n if (!Number.isInteger(quality)) {\n throw new RangeError(\n 'quality must be an integer in the range 0-100, got floating point'\n );\n }\n\n if (quality < 0 || quality > 100) {\n throw new RangeError(\n `quality must be in the range 0-100, got ${quality}`\n );\n }\n }\n}\n",
|
|
8
|
+
"/**\n * WebP encoder - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type ImageInput,\n loadWasmBinary,\n validateImageInput,\n detectSimd,\n respondSuccess,\n respondError,\n} from '@squoosh-kit/runtime';\nimport { validateWebpOptions } from './validators';\nimport { type WebPModule } from '../wasm/webp/webp_enc';\nimport type { EncodeInputOptions, EncodeOptions } from './types';\n\nlet cachedModule: WebPModule | null = null;\n\nasync function loadWebPModule(): Promise<WebPModule> {\n if (cachedModule) {\n return cachedModule;\n }\n\n const simdSupported = await detectSimd();\n const modulePath = simdSupported\n ? 'webp/webp_enc_simd.js'\n : 'webp/webp_enc.js';\n\n try {\n console.log('[WebP Worker] Initializing. SIMD support:', simdSupported);\n console.log(\n `[WebP Worker] Attempting to import module from path: ${modulePath}`\n );\n\n // Mock self.location for test environments where it doesn't exist\n // Emscripten code tries to access self.location.href during initialization\n // We set it to import.meta.url so _scriptDir will be used instead\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n // Also ensure self exists if it doesn't (for Emscripten code that checks ENVIRONMENT_IS_WORKER)\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n // Use a standard dynamic import instead of require, and tell Vite to ignore it\n // Using string concatenation to avoid bundler issues with template literals\n // Try both paths: './wasm/' for browser/dist and '../wasm/' for tests/source\n let moduleFactory;\n const pathsToTry = ['./wasm/' + modulePath, '../wasm/' + modulePath];\n\n let lastError: Error | null = null;\n for (const importPath of pathsToTry) {\n try {\n moduleFactory = (await import(/* @vite-ignore */ importPath)).default;\n console.log(\n `[WebP Worker] Successfully loaded module from: ${importPath}`\n );\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n console.warn(\n `[WebP Worker] Failed to load from ${importPath}, trying next path...`\n );\n }\n }\n\n if (!moduleFactory) {\n throw lastError || new Error('Could not load WebP module from any path');\n }\n\n console.log('[WebP Worker] Module factory loaded successfully.');\n\n // Try both paths for WASM binary as well\n const wasmPathsToTry = simdSupported\n ? ['./wasm/webp/webp_enc_simd.wasm', '../wasm/webp/webp_enc_simd.wasm']\n : ['./wasm/webp/webp_enc.wasm', '../wasm/webp/webp_enc.wasm'];\n\n console.log(\n `[WebP Worker] Preparing to load WASM binary. Will try paths: ${wasmPathsToTry.join(', ')}`\n );\n\n const initModuleWithBinary = async (\n moduleFactory: (config: {\n noInitialRun: boolean;\n wasmBinary?: ArrayBuffer;\n }) => Promise<WebPModule>,\n wasmPaths: string[]\n ): Promise<WebPModule> => {\n // Use the worker's own import.meta.url as the base for resolving WASM paths\n const workerBaseUrl = new URL('.', import.meta.url);\n let lastError: Error | null = null;\n for (const wasmPath of wasmPaths) {\n try {\n console.log(\n `[WebP Worker] Calling loadWasmBinary with path: ${wasmPath}`\n );\n const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);\n console.log(\n `[WebP Worker] Successfully fetched WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`\n );\n\n // Ensure self.location exists right before calling moduleFactory\n // Emscripten code accesses self.location.href when the factory is executed\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (\n typeof self === 'undefined' &&\n typeof globalThis !== 'undefined'\n ) {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n return await moduleFactory({\n noInitialRun: true,\n wasmBinary,\n });\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n console.warn(\n `[WebP Worker] Failed to load WASM from ${wasmPath}, trying next path...`\n );\n }\n }\n throw (\n lastError ||\n new Error('Could not load WASM binary from any of the attempted paths')\n );\n };\n\n cachedModule = await initModuleWithBinary(moduleFactory, wasmPathsToTry);\n console.log('[WebP Worker] WebP module initialized successfully.');\n return cachedModule;\n } catch (err) {\n console.error(\n `[WebP Worker] CRITICAL: Failed to load WebP module from path: ${modulePath}`,\n err\n );\n throw err;\n }\n}\n\n/**\n * Convert our simplified options to full EncodeOptions\n * Uses Squoosh defaults for optimal performance and file size\n */\nfunction createEncodeOptions(options?: EncodeInputOptions): EncodeOptions {\n // Squoosh defaults from their defaultOptions in meta.ts\n return {\n quality: options?.quality ?? 75,\n target_size: 0,\n target_PSNR: 0,\n method: options?.method ?? 4,\n sns_strength: options?.sns_strength ?? 50,\n filter_strength: options?.filter_strength ?? 60,\n filter_sharpness: options?.filter_sharpness ?? 0,\n filter_type: options?.filter_type ?? 1,\n partitions: options?.partitions ?? 0,\n segments: options?.segments ?? 4,\n pass: options?.pass ?? 1,\n show_compressed: 0,\n preprocessing: options?.preprocessing ?? 0,\n autofilter: options?.autofilter ?? 0,\n partition_limit: 0,\n alpha_compression: options?.alpha_compression ?? 1,\n alpha_filtering: options?.alpha_filtering ?? 1,\n alpha_quality: options?.alpha_quality ?? options?.quality ?? 75,\n lossless: options?.lossless ? 1 : 0,\n exact: options?.exact ?? 0,\n image_hint: options?.image_hint ?? 0,\n emulate_jpeg_size: 0,\n thread_level: 0,\n low_memory: 0,\n near_lossless: options?.near_lossless ?? options?.quality ?? 75,\n use_delta_palette: 0,\n use_sharp_yuv: options?.use_sharp_yuv ?? 0,\n };\n}\n\n/**\n * Client-mode WebP encoder (exported for direct use)\n */\nexport async function webpEncodeClient(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Validate inputs before starting\n validateImageInput(image);\n validateWebpOptions(options);\n\n // Check abort before starting\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n // Normalize image input\n const width = image.width;\n const height = image.height;\n const data = image.data;\n\n if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {\n throw new Error('Image data must be Uint8Array or Uint8ClampedArray');\n }\n\n const t0 = performance.now();\n const module = await loadWebPModule();\n const t1 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] module loading took ${(t1 - t0).toFixed(2)}ms`);\n console.log(\n `[WebP] Module type: ${cachedModule && 'encode' in cachedModule ? 'Ready' : 'Unknown'}`\n );\n }\n\n // Check abort after async operation\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const encodeOptions = createEncodeOptions(options);\n\n // Call the encode function with optimized data handling\n // Create a zero-copy Uint8Array view if needed (don't copy the buffer)\n const dataArray =\n data instanceof Uint8ClampedArray\n ? new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.length)\n : new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.length\n );\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] encode options:`, encodeOptions);\n }\n\n const t2 = performance.now();\n const result = module.encode(dataArray, width, height, encodeOptions);\n const t3 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] actual encoding took ${(t3 - t2).toFixed(2)}ms`);\n }\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n if (!result) {\n throw new Error('WebP encoding failed');\n }\n\n return result;\n}\n\n/**\n * Worker message handler\n * Register the handler regardless of environment (for both worker context and tests)\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const request = data as WorkerRequest<{\n image: ImageInput;\n options?: EncodeInputOptions;\n }>;\n\n try {\n if (request.type === 'webp:encode') {\n const { image, options } = request.payload;\n\n const t0 = performance.now();\n const controller = new AbortController();\n const result = await webpEncodeClient(\n image,\n options,\n controller.signal\n );\n const t1 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP Worker] encode took ${(t1 - t0).toFixed(2)}ms`);\n }\n\n // Create a clean buffer for transfer (zero-copy logic handled here)\n const outputData = new Uint8Array(result);\n\n // ONE LINE response with transfer!\n respondSuccess(request.id, outputData, [outputData.buffer]);\n } else {\n respondError(request.id, `Unknown message type: ${request.type}`);\n }\n } catch (error) {\n respondError(request.id, error);\n }\n };\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "oGAAO,FAA4uE,EAAK,SAAS,YAAY,SAAS,IAAI,WAAW,CAAC,EAAE,GAAG,IAAI,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,GAAG,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC,ECUv3E,IAAI,EAAgC,KAChC,EAAgD,KAMpD,eAAsB,CAAU,EAAqB,CAEnD,GAAI,IAAkB,KACpB,OAAO,EAIT,GAAI,EACF,OAAO,EAmBT,OAfA,GAAwB,SAAY,CAClC,GAAI,CAEF,OADA,EAAgB,MAAM,EAAK,EACpB,EACP,MAAO,EAAO,CAOd,OALA,EAAgB,GAChB,QAAQ,KACN,gEACA,CACF,EACO,MAER,EAEI,EC5CF,SAAS,CAAmB,CACjC,EACwD,CACxD,GAAI,IAAY,OACd,OAGF,GAAI,OAAO,IAAY,UAAY,IAAY,KAC7C,MAAU,UAAU,wCAAwC,EAG9D,IAAM,EAAO,EAEb,GAAI,YAAa,GAAQ,EAAK,UAAY,OAAW,CACnD,IAAM,EAAU,EAAK,QAErB,GAAI,OAAO,MAAM,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KAAK,YAAY,CAAE,KAAM,cAAe,CAAC,EACzC,OAGF,IAAM,EAAU,EAKhB,GAAI,CACF,GAAI,EAAQ,OAAS,cAAe,CAClC,IAAQ,QAAO,WAAY,EAAQ,QAE7B,EAAK,YAAY,IAAI,EACrB,EAAa,IAAI,gBACjB,EAAS,MAAM,EACnB,EACA,EACA,EAAW,MACb,EACM,EAAK,YAAY,IAAI,EAE3B,GAAI,OAAO,QAAY,KAAe,QAAQ,IAC5C,QAAQ,IAAI,8BAA8B,EAAK,GAAI,QAAQ,CAAC,KAAK,EAInE,IAAM,EAAa,IAAI,WAAW,CAAM,EAGxC,EAAe,EAAQ,GAAI,EAAY,CAAC,EAAW,MAAM,CAAC,EAE1D,OAAa,EAAQ,GAAI,yBAAyB,EAAQ,MAAM,EAElE,MAAO,EAAO,CACd,EAAa,EAAQ,GAAI,CAAK",
|
|
11
|
+
"debugId": "E34C30C32159311B64756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{d as J,e as K,f as G,g as H}from"./chunk-cfpkr9nw.js";async function I(z){let j=z.toString();if(H()&&!G()&&(j.startsWith("file:")||!j.includes("://")))try{let q=await import("fs/promises"),D=z instanceof URL?z:j;return(await q.readFile(D)).buffer}catch(q){console.warn("[io] fs read failed, falling back to fetch",q)}let C=await fetch(j);if(!C.ok)throw Error(`Failed to fetch ${j}: ${C.statusText}`);return C.arrayBuffer()}async function R(z,j){let C=j?typeof j==="string"?new URL(".",j):new URL(".",j.href):new URL(".",import.meta.url),q=new URL(z,C);console.log(`[WasmLoader] Loading WASM from relative path: ${z}`),console.log(`[WasmLoader] Base URL (import.meta.url): ${C.href}`),console.log(`[WasmLoader] Constructed full URL: ${q.href}`);try{return await I(q)}catch(D){throw console.error(`[WasmLoader] CRITICAL: Fetching WASM binary from ${q.href} failed.`,D),D}}function W(z,j,C=[]){let q={id:z,ok:!0,data:j},D=C.filter((E)=>!(E instanceof SharedArrayBuffer));self.postMessage(q,D)}function X(z,j){let C=j instanceof Error?j.message:String(j),q={id:z,ok:!1,error:C};self.postMessage(q)}
|
|
3
|
+
export{R as a,W as b,X as c};
|
|
4
|
+
|
|
5
|
+
//# debugId=B2399131776F594564756E2164756E21
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/src/io.ts", "../../runtime/src/wasm-loader.ts", "../../runtime/src/worker-utils.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { isNode, isBun } from './env';\n\n/**\n * Reads a file as an ArrayBuffer, handling platform differences.\n * - Node.js: Uses fs/promises for file:// URLs (prevents fetch errors)\n * - Browser/Bun: Uses standard fetch\n */\nexport async function readFileAsBuffer(\n url: URL | string\n): Promise<ArrayBuffer> {\n const urlStr = url.toString();\n\n // Node.js (non-Bun) file:// handling\n if (\n isNode() &&\n !isBun() &&\n (urlStr.startsWith('file:') || !urlStr.includes('://'))\n ) {\n try {\n // Dynamic import prevents bundling 'fs' in browser builds\n const fs = await import('fs/promises');\n const path = url instanceof URL ? url : urlStr;\n const buffer = await fs.readFile(path);\n return buffer.buffer as ArrayBuffer;\n } catch (e) {\n console.warn('[io] fs read failed, falling back to fetch', e);\n }\n }\n\n // Standard fetch (Browser, Bun, Node http)\n const res = await fetch(urlStr);\n if (!res.ok) throw new Error(`Failed to fetch ${urlStr}: ${res.statusText}`);\n return res.arrayBuffer();\n}\n",
|
|
6
|
+
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nimport { readFileAsBuffer } from './io';\n\nexport async function loadWasmBinary(\n relativePath: string,\n baseUrlOverride?: string | URL\n): Promise<ArrayBuffer> {\n // Get the base URL depending on the environment (worker or main thread)\n // If a base URL is provided, use it; otherwise use import.meta.url from this module\n // In a worker, import.meta.url is the worker's own URL.\n // In the main thread, it's the URL of the current module.\n const baseUrl = baseUrlOverride\n ? typeof baseUrlOverride === 'string'\n ? new URL('.', baseUrlOverride)\n : new URL('.', baseUrlOverride.href)\n : new URL('.', import.meta.url);\n const fullUrl = new URL(relativePath, baseUrl);\n\n console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);\n console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);\n console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);\n\n try {\n return await readFileAsBuffer(fullUrl);\n } catch (error) {\n console.error(\n `[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(/* @vite-ignore */ modulePath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n\n return await import(/* @vite-ignore */ resolvedPath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(/* @vite-ignore */ modulePath, import.meta.url);\n\n return await import(/* @vite-ignore */ url.href);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`\n );\n }\n}\n",
|
|
7
|
+
"import type { WorkerResponse } from './worker-call';\n\n/**\n * Defines the subset of DedicatedWorkerGlobalScope needed for posting messages.\n * Used to cast 'self' to resolve TypeScript overload conflicts between\n * DOM types and Bun types (which define Transferable differently).\n */\ninterface WorkerScope {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\n/**\n * Safely sends a success response from a worker, handling Transferables automatically.\n * Filters out SharedArrayBuffers which cannot be transferred.\n */\nexport function respondSuccess<T>(\n id: number,\n data: T,\n transfer: Transferable[] = []\n) {\n const response: WorkerResponse<T> = { id, ok: true, data };\n\n // Safety check: SharedArrayBuffer cannot be in the transfer list\n const safeTransfer = transfer.filter(\n (t) => !(t instanceof SharedArrayBuffer)\n );\n\n // Cast self to WorkerScope to avoid TypeScript errors where it confuses\n // the worker global scope with the window scope (expecting targetOrigin),\n // or conflicts between DOM Transferable and Bun.Transferable types.\n (self as unknown as WorkerScope).postMessage(response, safeTransfer);\n}\n\n/**\n * Sends an error response from a worker.\n */\nexport function respondError(id: number, error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n const response: WorkerResponse<never> = { id, ok: false, error: msg };\n self.postMessage(response);\n}\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": ";6DAOA,eAAsB,CAAgB,CACpC,EACsB,CACtB,IAAM,EAAS,EAAI,SAAS,EAG5B,GACE,EAAO,GACP,CAAC,EAAM,IACN,EAAO,WAAW,OAAO,GAAK,CAAC,EAAO,SAAS,KAAK,GAErD,GAAI,CAEF,IAAM,EAAK,KAAa,uBAClB,EAAO,aAAe,IAAM,EAAM,EAExC,OADe,MAAM,EAAG,SAAS,CAAI,GACvB,OACd,MAAO,EAAG,CACV,QAAQ,KAAK,6CAA8C,CAAC,EAKhE,IAAM,EAAM,MAAM,MAAM,CAAM,EAC9B,GAAI,CAAC,EAAI,GAAI,MAAU,MAAM,mBAAmB,MAAW,EAAI,YAAY,EAC3E,OAAO,EAAI,YAAY,ECtBzB,eAAsB,CAAc,CAClC,EACA,EACsB,CAKtB,IAAM,EAAU,EACZ,OAAO,IAAoB,SACzB,IAAI,IAAI,IAAK,CAAe,EAC5B,IAAI,IAAI,IAAK,EAAgB,IAAI,EACnC,IAAI,IAAI,IAAK,YAAY,GAAG,EAC1B,EAAU,IAAI,IAAI,EAAc,CAAO,EAE7C,QAAQ,IAAI,iDAAiD,GAAc,EAC3E,QAAQ,IAAI,4CAA4C,EAAQ,MAAM,EACtE,QAAQ,IAAI,sCAAsC,EAAQ,MAAM,EAEhE,GAAI,CACF,OAAO,MAAM,EAAiB,CAAO,EACrC,MAAO,EAAO,CAKd,MAJA,QAAQ,MACN,oDAAoD,EAAQ,eAC5D,CACF,EACM,GCrBH,SAAS,CAAiB,CAC/B,EACA,EACA,EAA2B,CAAC,EAC5B,CACA,IAAM,EAA8B,CAAE,KAAI,GAAI,GAAM,MAAK,EAGnD,EAAe,EAAS,OAC5B,CAAC,IAAM,EAAE,aAAa,kBACxB,EAKC,KAAgC,YAAY,EAAU,CAAY,EAM9D,SAAS,CAAY,CAAC,EAAY,EAAgB,CACvD,IAAM,EAAM,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAC3D,EAAkC,CAAE,KAAI,GAAI,GAAO,MAAO,CAAI,EACpE,KAAK,YAAY,CAAQ",
|
|
10
|
+
"debugId": "B2399131776F594564756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var L=Object.create;var{getPrototypeOf:M,defineProperty:K,getOwnPropertyNames:N}=Object;var P=Object.prototype.hasOwnProperty;var Q=(q,H,G)=>{G=q!=null?L(M(q)):{};let E=H||!q||!q.__esModule?K(G,"default",{value:q,enumerable:!0}):G;for(let F of N(q))if(!P.call(E,F))K(E,F,{get:()=>q[F],enumerable:!0});return E};var R=import.meta.require;function U(q){if(!q||typeof q!=="object")throw TypeError("image must be an object");let H=q;if(!("data"in H))throw TypeError("image.data is required");let{data:G}=H;if(!(G instanceof Uint8Array||G instanceof Uint8ClampedArray))throw TypeError("image.data must be Uint8Array or Uint8ClampedArray");if(!("width"in H)||!("height"in H))throw TypeError("image.width and image.height are required");let{width:E,height:F}=H;if(typeof E!=="number"||!Number.isInteger(E)||E<=0)throw RangeError(`image.width must be a positive integer, got ${E}`);if(typeof F!=="number"||!Number.isInteger(F)||F<=0)throw RangeError(`image.height must be a positive integer, got ${F}`);let J=E*F*4;if(G.length<J)throw RangeError(`image.data too small: ${G.length} bytes, expected at least ${J} bytes for ${E}x${F} RGBA image`)}function W(){return typeof Bun<"u"}function X(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}
|
|
3
|
+
export{Q as d,R as e,W as f,X as g,U as h};
|
|
4
|
+
|
|
5
|
+
//# debugId=F6A10E3C2FBA9E4D64756E2164756E21
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/validators.ts"],
|
|
3
|
+
"sources": ["../../runtime/src/validators.ts", "../../runtime/src/env.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { ImageInput } from './types.js';\n\nexport function validateArrayBuffer(\n buffer: unknown\n): asserts buffer is ArrayBuffer {\n // Check if SharedArrayBuffer is defined in the current environment before using it\n if (\n typeof SharedArrayBuffer !== 'undefined' &&\n buffer instanceof SharedArrayBuffer\n ) {\n throw new Error(\n 'SharedArrayBuffer is not supported. ' +\n 'Use regular ArrayBuffer or Uint8Array instead.'\n );\n }\n\n if (!(buffer instanceof ArrayBuffer)) {\n throw new TypeError('image.data.buffer must be an ArrayBuffer');\n }\n}\n\nexport function validateImageInput(\n image: unknown\n): asserts image is ImageInput {\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageObj = image as Record<string, unknown>;\n\n if (!('data' in imageObj)) {\n throw new TypeError('image.data is required');\n }\n\n const { data } = imageObj;\n if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {\n throw new TypeError('image.data must be Uint8Array or Uint8ClampedArray');\n }\n\n if (!('width' in imageObj) || !('height' in imageObj)) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const { width, height } = imageObj;\n\n if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {\n throw new RangeError(\n `image.width must be a positive integer, got ${width}`\n );\n }\n\n if (typeof height !== 'number' || !Number.isInteger(height) || height <= 0) {\n throw new RangeError(\n `image.height must be a positive integer, got ${height}`\n );\n }\n\n const expectedSize = width * height * 4;\n if (data.length < expectedSize) {\n throw new RangeError(\n `image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`\n );\n }\n}\n"
|
|
5
|
+
"import type { ImageInput } from './types.js';\n\nexport function validateArrayBuffer(\n buffer: unknown\n): asserts buffer is ArrayBuffer {\n // Check if SharedArrayBuffer is defined in the current environment before using it\n if (\n typeof SharedArrayBuffer !== 'undefined' &&\n buffer instanceof SharedArrayBuffer\n ) {\n throw new Error(\n 'SharedArrayBuffer is not supported. ' +\n 'Use regular ArrayBuffer or Uint8Array instead.'\n );\n }\n\n if (!(buffer instanceof ArrayBuffer)) {\n throw new TypeError('image.data.buffer must be an ArrayBuffer');\n }\n}\n\nexport function validateImageInput(\n image: unknown\n): asserts image is ImageInput {\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageObj = image as Record<string, unknown>;\n\n if (!('data' in imageObj)) {\n throw new TypeError('image.data is required');\n }\n\n const { data } = imageObj;\n if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {\n throw new TypeError('image.data must be Uint8Array or Uint8ClampedArray');\n }\n\n if (!('width' in imageObj) || !('height' in imageObj)) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const { width, height } = imageObj;\n\n if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {\n throw new RangeError(\n `image.width must be a positive integer, got ${width}`\n );\n }\n\n if (typeof height !== 'number' || !Number.isInteger(height) || height <= 0) {\n throw new RangeError(\n `image.height must be a positive integer, got ${height}`\n );\n }\n\n const expectedSize = width * height * 4;\n if (data.length < expectedSize) {\n throw new RangeError(\n `image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`\n );\n }\n}\n",
|
|
6
|
+
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n"
|
|
6
7
|
],
|
|
7
|
-
"mappings": ";iVAqBO,SAAS,CAAkB,CAChC,EAC6B,CAC7B,GAAI,CAAC,GAAS,OAAO,IAAU,SAC7B,MAAU,UAAU,yBAAyB,EAG/C,IAAM,EAAW,EAEjB,GAAI,EAAE,SAAU,GACd,MAAU,UAAU,wBAAwB,EAG9C,IAAQ,QAAS,EACjB,GAAI,EAAE,aAAgB,YAAc,aAAgB,mBAClD,MAAU,UAAU,oDAAoD,EAG1E,GAAI,EAAE,UAAW,IAAa,EAAE,WAAY,GAC1C,MAAU,UAAU,2CAA2C,EAGjE,IAAQ,QAAO,UAAW,EAE1B,GAAI,OAAO,IAAU,UAAY,CAAC,OAAO,UAAU,CAAK,GAAK,GAAS,EACpE,MAAU,WACR,+CAA+C,GACjD,EAGF,GAAI,OAAO,IAAW,UAAY,CAAC,OAAO,UAAU,CAAM,GAAK,GAAU,EACvE,MAAU,WACR,gDAAgD,GAClD,EAGF,IAAM,EAAe,EAAQ,EAAS,EACtC,GAAI,EAAK,OAAS,EAChB,MAAU,WACR,yBAAyB,EAAK,mCAAmC,eAA0B,KAAS,cACtG",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"mappings": ";iVAqBO,SAAS,CAAkB,CAChC,EAC6B,CAC7B,GAAI,CAAC,GAAS,OAAO,IAAU,SAC7B,MAAU,UAAU,yBAAyB,EAG/C,IAAM,EAAW,EAEjB,GAAI,EAAE,SAAU,GACd,MAAU,UAAU,wBAAwB,EAG9C,IAAQ,QAAS,EACjB,GAAI,EAAE,aAAgB,YAAc,aAAgB,mBAClD,MAAU,UAAU,oDAAoD,EAG1E,GAAI,EAAE,UAAW,IAAa,EAAE,WAAY,GAC1C,MAAU,UAAU,2CAA2C,EAGjE,IAAQ,QAAO,UAAW,EAE1B,GAAI,OAAO,IAAU,UAAY,CAAC,OAAO,UAAU,CAAK,GAAK,GAAS,EACpE,MAAU,WACR,+CAA+C,GACjD,EAGF,GAAI,OAAO,IAAW,UAAY,CAAC,OAAO,UAAU,CAAM,GAAK,GAAU,EACvE,MAAU,WACR,gDAAgD,GAClD,EAGF,IAAM,EAAe,EAAQ,EAAS,EACtC,GAAI,EAAK,OAAS,EAChB,MAAU,WACR,yBAAyB,EAAK,mCAAmC,eAA0B,KAAS,cACtG,ECpCG,SAAS,CAAK,EAAY,CAC/B,OAAO,OAAO,IAAQ,IAMjB,SAAS,CAAM,EAAY,CAChC,OACE,OAAO,QAAY,KACnB,QAAQ,UAAY,MACpB,QAAQ,SAAS,MAAQ",
|
|
9
|
+
"debugId": "F6A10E3C2FBA9E4D64756E2164756E21",
|
|
9
10
|
"names": []
|
|
10
11
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createRequire as Q}from"node:module";var L=Object.create;var{getPrototypeOf:M,defineProperty:K,getOwnPropertyNames:N}=Object;var P=Object.prototype.hasOwnProperty;var R=(q,H,G)=>{G=q!=null?L(M(q)):{};let E=H||!q||!q.__esModule?K(G,"default",{value:q,enumerable:!0}):G;for(let F of N(q))if(!P.call(E,F))K(E,F,{get:()=>q[F],enumerable:!0});return E};var U=Q(import.meta.url);function W(q){if(!q||typeof q!=="object")throw TypeError("image must be an object");let H=q;if(!("data"in H))throw TypeError("image.data is required");let{data:G}=H;if(!(G instanceof Uint8Array||G instanceof Uint8ClampedArray))throw TypeError("image.data must be Uint8Array or Uint8ClampedArray");if(!("width"in H)||!("height"in H))throw TypeError("image.width and image.height are required");let{width:E,height:F}=H;if(typeof E!=="number"||!Number.isInteger(E)||E<=0)throw RangeError(`image.width must be a positive integer, got ${E}`);if(typeof F!=="number"||!Number.isInteger(F)||F<=0)throw RangeError(`image.height must be a positive integer, got ${F}`);let J=E*F*4;if(G.length<J)throw RangeError(`image.data too small: ${G.length} bytes, expected at least ${J} bytes for ${E}x${F} RGBA image`)}function Y(){return typeof Bun<"u"}function Z(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}
|
|
2
|
+
export{R as d,U as e,Y as f,Z as g,W as h};
|
|
3
|
+
|
|
4
|
+
//# debugId=4D5A204214220AB364756E2164756E21
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/validators.ts"],
|
|
3
|
+
"sources": ["../../runtime/src/validators.ts", "../../runtime/src/env.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { ImageInput } from './types.js';\n\nexport function validateArrayBuffer(\n buffer: unknown\n): asserts buffer is ArrayBuffer {\n // Check if SharedArrayBuffer is defined in the current environment before using it\n if (\n typeof SharedArrayBuffer !== 'undefined' &&\n buffer instanceof SharedArrayBuffer\n ) {\n throw new Error(\n 'SharedArrayBuffer is not supported. ' +\n 'Use regular ArrayBuffer or Uint8Array instead.'\n );\n }\n\n if (!(buffer instanceof ArrayBuffer)) {\n throw new TypeError('image.data.buffer must be an ArrayBuffer');\n }\n}\n\nexport function validateImageInput(\n image: unknown\n): asserts image is ImageInput {\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageObj = image as Record<string, unknown>;\n\n if (!('data' in imageObj)) {\n throw new TypeError('image.data is required');\n }\n\n const { data } = imageObj;\n if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {\n throw new TypeError('image.data must be Uint8Array or Uint8ClampedArray');\n }\n\n if (!('width' in imageObj) || !('height' in imageObj)) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const { width, height } = imageObj;\n\n if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {\n throw new RangeError(\n `image.width must be a positive integer, got ${width}`\n );\n }\n\n if (typeof height !== 'number' || !Number.isInteger(height) || height <= 0) {\n throw new RangeError(\n `image.height must be a positive integer, got ${height}`\n );\n }\n\n const expectedSize = width * height * 4;\n if (data.length < expectedSize) {\n throw new RangeError(\n `image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`\n );\n }\n}\n"
|
|
5
|
+
"import type { ImageInput } from './types.js';\n\nexport function validateArrayBuffer(\n buffer: unknown\n): asserts buffer is ArrayBuffer {\n // Check if SharedArrayBuffer is defined in the current environment before using it\n if (\n typeof SharedArrayBuffer !== 'undefined' &&\n buffer instanceof SharedArrayBuffer\n ) {\n throw new Error(\n 'SharedArrayBuffer is not supported. ' +\n 'Use regular ArrayBuffer or Uint8Array instead.'\n );\n }\n\n if (!(buffer instanceof ArrayBuffer)) {\n throw new TypeError('image.data.buffer must be an ArrayBuffer');\n }\n}\n\nexport function validateImageInput(\n image: unknown\n): asserts image is ImageInput {\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageObj = image as Record<string, unknown>;\n\n if (!('data' in imageObj)) {\n throw new TypeError('image.data is required');\n }\n\n const { data } = imageObj;\n if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {\n throw new TypeError('image.data must be Uint8Array or Uint8ClampedArray');\n }\n\n if (!('width' in imageObj) || !('height' in imageObj)) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const { width, height } = imageObj;\n\n if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {\n throw new RangeError(\n `image.width must be a positive integer, got ${width}`\n );\n }\n\n if (typeof height !== 'number' || !Number.isInteger(height) || height <= 0) {\n throw new RangeError(\n `image.height must be a positive integer, got ${height}`\n );\n }\n\n const expectedSize = width * height * 4;\n if (data.length < expectedSize) {\n throw new RangeError(\n `image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`\n );\n }\n}\n",
|
|
6
|
+
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n"
|
|
6
7
|
],
|
|
7
|
-
"mappings": "4XAqBO,SAAS,CAAkB,CAChC,EAC6B,CAC7B,GAAI,CAAC,GAAS,OAAO,IAAU,SAC7B,MAAU,UAAU,yBAAyB,EAG/C,IAAM,EAAW,EAEjB,GAAI,EAAE,SAAU,GACd,MAAU,UAAU,wBAAwB,EAG9C,IAAQ,QAAS,EACjB,GAAI,EAAE,aAAgB,YAAc,aAAgB,mBAClD,MAAU,UAAU,oDAAoD,EAG1E,GAAI,EAAE,UAAW,IAAa,EAAE,WAAY,GAC1C,MAAU,UAAU,2CAA2C,EAGjE,IAAQ,QAAO,UAAW,EAE1B,GAAI,OAAO,IAAU,UAAY,CAAC,OAAO,UAAU,CAAK,G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as G,g as H}from"./chunk-d3fxpzrq.js";async function I(z){let j=z.toString();if(H()&&!G()&&(j.startsWith("file:")||!j.includes("://")))try{let q=await import("fs/promises"),D=z instanceof URL?z:j;return(await q.readFile(D)).buffer}catch(q){console.warn("[io] fs read failed, falling back to fetch",q)}let C=await fetch(j);if(!C.ok)throw Error(`Failed to fetch ${j}: ${C.statusText}`);return C.arrayBuffer()}async function R(z,j){let C=j?typeof j==="string"?new URL(".",j):new URL(".",j.href):new URL(".",import.meta.url),q=new URL(z,C);console.log(`[WasmLoader] Loading WASM from relative path: ${z}`),console.log(`[WasmLoader] Base URL (import.meta.url): ${C.href}`),console.log(`[WasmLoader] Constructed full URL: ${q.href}`);try{return await I(q)}catch(D){throw console.error(`[WasmLoader] CRITICAL: Fetching WASM binary from ${q.href} failed.`,D),D}}function W(z,j,C=[]){let q={id:z,ok:!0,data:j},D=C.filter((E)=>!(E instanceof SharedArrayBuffer));self.postMessage(q,D)}function X(z,j){let C=j instanceof Error?j.message:String(j),q={id:z,ok:!1,error:C};self.postMessage(q)}
|
|
2
|
+
export{R as a,W as b,X as c};
|
|
3
|
+
|
|
4
|
+
//# debugId=B06AB8414FB50F3F64756E2164756E21
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/src/io.ts", "../../runtime/src/wasm-loader.ts", "../../runtime/src/worker-utils.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { isNode, isBun } from './env';\n\n/**\n * Reads a file as an ArrayBuffer, handling platform differences.\n * - Node.js: Uses fs/promises for file:// URLs (prevents fetch errors)\n * - Browser/Bun: Uses standard fetch\n */\nexport async function readFileAsBuffer(\n url: URL | string\n): Promise<ArrayBuffer> {\n const urlStr = url.toString();\n\n // Node.js (non-Bun) file:// handling\n if (\n isNode() &&\n !isBun() &&\n (urlStr.startsWith('file:') || !urlStr.includes('://'))\n ) {\n try {\n // Dynamic import prevents bundling 'fs' in browser builds\n const fs = await import('fs/promises');\n const path = url instanceof URL ? url : urlStr;\n const buffer = await fs.readFile(path);\n return buffer.buffer as ArrayBuffer;\n } catch (e) {\n console.warn('[io] fs read failed, falling back to fetch', e);\n }\n }\n\n // Standard fetch (Browser, Bun, Node http)\n const res = await fetch(urlStr);\n if (!res.ok) throw new Error(`Failed to fetch ${urlStr}: ${res.statusText}`);\n return res.arrayBuffer();\n}\n",
|
|
6
|
+
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nimport { readFileAsBuffer } from './io';\n\nexport async function loadWasmBinary(\n relativePath: string,\n baseUrlOverride?: string | URL\n): Promise<ArrayBuffer> {\n // Get the base URL depending on the environment (worker or main thread)\n // If a base URL is provided, use it; otherwise use import.meta.url from this module\n // In a worker, import.meta.url is the worker's own URL.\n // In the main thread, it's the URL of the current module.\n const baseUrl = baseUrlOverride\n ? typeof baseUrlOverride === 'string'\n ? new URL('.', baseUrlOverride)\n : new URL('.', baseUrlOverride.href)\n : new URL('.', import.meta.url);\n const fullUrl = new URL(relativePath, baseUrl);\n\n console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);\n console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);\n console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);\n\n try {\n return await readFileAsBuffer(fullUrl);\n } catch (error) {\n console.error(\n `[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(/* @vite-ignore */ modulePath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n\n return await import(/* @vite-ignore */ resolvedPath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(/* @vite-ignore */ modulePath, import.meta.url);\n\n return await import(/* @vite-ignore */ url.href);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`\n );\n }\n}\n",
|
|
7
|
+
"import type { WorkerResponse } from './worker-call';\n\n/**\n * Defines the subset of DedicatedWorkerGlobalScope needed for posting messages.\n * Used to cast 'self' to resolve TypeScript overload conflicts between\n * DOM types and Bun types (which define Transferable differently).\n */\ninterface WorkerScope {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\n/**\n * Safely sends a success response from a worker, handling Transferables automatically.\n * Filters out SharedArrayBuffers which cannot be transferred.\n */\nexport function respondSuccess<T>(\n id: number,\n data: T,\n transfer: Transferable[] = []\n) {\n const response: WorkerResponse<T> = { id, ok: true, data };\n\n // Safety check: SharedArrayBuffer cannot be in the transfer list\n const safeTransfer = transfer.filter(\n (t) => !(t instanceof SharedArrayBuffer)\n );\n\n // Cast self to WorkerScope to avoid TypeScript errors where it confuses\n // the worker global scope with the window scope (expecting targetOrigin),\n // or conflicts between DOM Transferable and Bun.Transferable types.\n (self as unknown as WorkerScope).postMessage(response, safeTransfer);\n}\n\n/**\n * Sends an error response from a worker.\n */\nexport function respondError(id: number, error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n const response: WorkerResponse<never> = { id, ok: false, error: msg };\n self.postMessage(response);\n}\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": "6DAOA,eAAsB,CAAgB,CACpC,EACsB,CACtB,IAAM,E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Id": "B06AB8414FB50F3F64756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as G,b as X,c as C}from"./chunk-6qtap428.js";import{h as Q}from"./chunk-rta7shf1.js";var N=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]));var B=null,u=null;async function R(){if(B!==null)return B;if(u)return u;return u=(async()=>{try{return B=await N(),B}catch(A){return B=!1,console.warn("SIMD detection failed, falling back to standard WASM modules:",A),!1}})(),u}function E(A){if(A===void 0)return;if(typeof A!=="object"||A===null)throw TypeError("options must be an object or undefined");let y=A;if("quality"in y&&y.quality!==void 0){let n=y.quality;if(Number.isNaN(n))throw RangeError("quality must be a valid number in the range 0-100, got NaN");if(typeof n!=="number")throw TypeError("quality must be a number");if(!Number.isInteger(n))throw RangeError("quality must be an integer in the range 0-100, got floating point");if(n<0||n>100)throw RangeError(`quality must be in the range 0-100, got ${n}`)}}var W=null;async function j(){if(W)return W;let A=await R(),y=A?"webp/webp_enc_simd.js":"webp/webp_enc.js";try{console.log("[WebP Worker] Initializing. SIMD support:",A),console.log(`[WebP Worker] Attempting to import module from path: ${y}`);let n=typeof self<"u"?self:globalThis;if(!n.location)n.location={href:import.meta.url};if(typeof self>"u"&&typeof globalThis<"u")globalThis.self=globalThis;let r,f=["./wasm/"+y,"../wasm/"+y],e=null;for(let a of f)try{r=(await import(a)).default,console.log(`[WebP Worker] Successfully loaded module from: ${a}`);break}catch(b){e=b instanceof Error?b:Error(String(b)),console.warn(`[WebP Worker] Failed to load from ${a}, trying next path...`)}if(!r)throw e||Error("Could not load WebP module from any path");console.log("[WebP Worker] Module factory loaded successfully.");let l=A?["./wasm/webp/webp_enc_simd.wasm","../wasm/webp/webp_enc_simd.wasm"]:["./wasm/webp/webp_enc.wasm","../wasm/webp/webp_enc.wasm"];return console.log(`[WebP Worker] Preparing to load WASM binary. Will try paths: ${l.join(", ")}`),W=await(async(a,b)=>{let v=new URL(".",import.meta.url),g=null;for(let c of b)try{console.log(`[WebP Worker] Calling loadWasmBinary with path: ${c}`);let w=await G(c,v);console.log(`[WebP Worker] Successfully fetched WASM binary from ${c}. Size: ${w.byteLength} bytes.`);let x=typeof self<"u"?self:globalThis;if(!x.location)x.location={href:import.meta.url};if(typeof self>"u"&&typeof globalThis<"u")globalThis.self=globalThis;return await a({noInitialRun:!0,wasmBinary:w})}catch(w){g=w instanceof Error?w:Error(String(w)),console.warn(`[WebP Worker] Failed to load WASM from ${c}, trying next path...`)}throw g||Error("Could not load WASM binary from any of the attempted paths")})(r,l),console.log("[WebP Worker] WebP module initialized successfully."),W}catch(n){throw console.error(`[WebP Worker] CRITICAL: Failed to load WebP module from path: ${y}`,n),n}}function I(A){return{quality:A?.quality??75,target_size:0,target_PSNR:0,method:A?.method??4,sns_strength:A?.sns_strength??50,filter_strength:A?.filter_strength??60,filter_sharpness:A?.filter_sharpness??0,filter_type:A?.filter_type??1,partitions:A?.partitions??0,segments:A?.segments??4,pass:A?.pass??1,show_compressed:0,preprocessing:A?.preprocessing??0,autofilter:A?.autofilter??0,partition_limit:0,alpha_compression:A?.alpha_compression??1,alpha_filtering:A?.alpha_filtering??1,alpha_quality:A?.alpha_quality??A?.quality??75,lossless:A?.lossless?1:0,exact:A?.exact??0,image_hint:A?.image_hint??0,emulate_jpeg_size:0,thread_level:0,low_memory:0,near_lossless:A?.near_lossless??A?.quality??75,use_delta_palette:0,use_sharp_yuv:A?.use_sharp_yuv??0}}async function z(A,y,n){if(Q(A),E(y),n?.aborted)throw new DOMException("Aborted","AbortError");let{width:r,height:f,data:e}=A;if(!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw Error("Image data must be Uint8Array or Uint8ClampedArray");let l=performance.now(),U=await j(),a=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] module loading took ${(a-l).toFixed(2)}ms`),console.log(`[WebP] Module type: ${W&&"encode"in W?"Ready":"Unknown"}`);if(n?.aborted)throw new DOMException("Aborted","AbortError");let b=I(y),v=e instanceof Uint8ClampedArray?new Uint8Array(e.buffer,e.byteOffset,e.length):new Uint8Array(e.buffer,e.byteOffset,e.length);if(typeof console<"u"&&console.log)console.log("[WebP] encode options:",b);let g=performance.now(),c=U.encode(v,r,f,b),w=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] actual encoding took ${(w-g).toFixed(2)}ms`);if(n?.aborted)throw new DOMException("Aborted","AbortError");if(!c)throw Error("WebP encoding failed");return c}if(typeof self<"u")self.onmessage=async(A)=>{let y=A.data;if(y?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let n=y;try{if(n.type==="webp:encode"){let{image:r,options:f}=n.payload,e=performance.now(),l=new AbortController,U=await z(r,f,l.signal),a=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP Worker] encode took ${(a-e).toFixed(2)}ms`);let b=new Uint8Array(U);X(n.id,b,[b.buffer])}else C(n.id,`Unknown message type: ${n.type}`)}catch(r){C(n.id,r)}};export{z as webpEncodeClient};
|
|
2
|
+
|
|
3
|
+
//# debugId=E34C30C32159311B64756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../node_modules/.bun/wasm-feature-detect@1.8.0/node_modules/wasm-feature-detect/dist/esm/index.js", "../../runtime/src/simd-detector.ts", "../../webp/src/validators.ts", "../../webp/src/webp.worker.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"export const bigInt=()=>(async e=>{try{return(await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0))===BigInt(0)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,126,1,126,3,2,1,0,7,5,1,1,98,0,0,10,6,1,4,0,32,0,11])),bulkMemory=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),exceptions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),exceptionsFinal=()=>(async()=>{try{return new WebAssembly.Module(Uint8Array.from(atob(\"AGFzbQEAAAABBAFgAAADAgEAChABDgACaR9AAQMAAAsACxoL\"),(e=>e.codePointAt(0)))),!0}catch(e){return!1}})(),extendedConst=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,0,1,11,9,1,0,65,1,65,2,106,11,0])),gc=()=>(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,95,1,120,0])))(),jsStringBuiltins=()=>(async()=>{try{return await WebAssembly.instantiate(Uint8Array.from(atob(\"AGFzbQEAAAABBgFgAW8BfwIXAQ53YXNtOmpzLXN0cmluZwR0ZXN0AAA=\"),(e=>e.codePointAt(0))),{},{builtins:[\"js-string\"]}),!0}catch(e){return!1}})(),jspi=()=>(async()=>\"Suspending\"in WebAssembly)(),memory64=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,4,1])),multiMemory=()=>(async()=>{try{return new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,5,5,2,0,0,0,0])),!0}catch(e){return!1}})(),multiValue=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,0,2,127,127,3,2,1,0,10,8,1,6,0,65,0,65,0,11])),mutableGlobals=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,2,8,1,1,97,1,98,3,127,1,6,6,1,127,1,65,0,11,7,5,1,1,97,3,1])),referenceTypes=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,208,112,26,11])),relaxedSimd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11])),saturatedFloatToInt=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])),signExtensions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])),simd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),streamingCompilation=()=>(async()=>\"compileStreaming\"in WebAssembly)(),tailCall=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,6,1,4,0,18,0,11])),threads=()=>(async e=>{try{return\"undefined\"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),typeReflection=()=>(async()=>\"Function\"in WebAssembly)(),typedFunctionReferences=()=>(async()=>{try{return new WebAssembly.Module(Uint8Array.from(atob(\"AGFzbQEAAAABEANgAX8Bf2ABZAABf2AAAX8DBAMBAAIJBQEDAAEBChwDCwBBCkEqIAAUAGoLBwAgAEEBagsGANIBEAAL\"),(e=>e.codePointAt(0)))),!0}catch(e){return!1}})();\n",
|
|
6
|
+
"/**\n * SIMD (Single Instruction Multiple Data) detection for WebAssembly\n *\n * SIMD support allows WebAssembly modules to perform vectorized operations,\n * significantly improving performance for operations like image encoding.\n * Some browsers and runtimes don't support SIMD yet, so we need to detect it.\n */\n\nimport { simd } from 'wasm-feature-detect';\n\nlet simdSupported: boolean | null = null;\nlet simdDetectionPromise: Promise<boolean> | null = null;\n\n/**\n * Detects if WebAssembly SIMD is supported in the current environment\n * @returns Promise<boolean> - true if SIMD is supported, false otherwise\n */\nexport async function detectSimd(): Promise<boolean> {\n // Return cached result if already detected\n if (simdSupported !== null) {\n return simdSupported;\n }\n\n // Return existing detection promise if detection is in progress\n if (simdDetectionPromise) {\n return simdDetectionPromise;\n }\n\n // Perform SIMD detection\n simdDetectionPromise = (async () => {\n try {\n simdSupported = await simd();\n return simdSupported;\n } catch (error) {\n // If detection fails, assume SIMD is not supported\n simdSupported = false;\n console.warn(\n 'SIMD detection failed, falling back to standard WASM modules:',\n error\n );\n return false;\n }\n })();\n\n return simdDetectionPromise;\n}\n\n/**\n * Reset SIMD detection cache (useful for testing)\n */\nexport function resetSimdCache(): void {\n simdSupported = null;\n simdDetectionPromise = null;\n}\n",
|
|
7
|
+
"export function validateWebpOptions(\n options: unknown\n): asserts options is Record<string, unknown> | undefined {\n if (options === undefined) {\n return;\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('options must be an object or undefined');\n }\n\n const opts = options as Record<string, unknown>;\n\n if ('quality' in opts && opts.quality !== undefined) {\n const quality = opts.quality;\n\n if (Number.isNaN(quality)) {\n throw new RangeError(\n 'quality must be a valid number in the range 0-100, got NaN'\n );\n }\n\n if (typeof quality !== 'number') {\n throw new TypeError('quality must be a number');\n }\n\n if (!Number.isInteger(quality)) {\n throw new RangeError(\n 'quality must be an integer in the range 0-100, got floating point'\n );\n }\n\n if (quality < 0 || quality > 100) {\n throw new RangeError(\n `quality must be in the range 0-100, got ${quality}`\n );\n }\n }\n}\n",
|
|
8
|
+
"/**\n * WebP encoder - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type ImageInput,\n loadWasmBinary,\n validateImageInput,\n detectSimd,\n respondSuccess,\n respondError,\n} from '@squoosh-kit/runtime';\nimport { validateWebpOptions } from './validators';\nimport { type WebPModule } from '../wasm/webp/webp_enc';\nimport type { EncodeInputOptions, EncodeOptions } from './types';\n\nlet cachedModule: WebPModule | null = null;\n\nasync function loadWebPModule(): Promise<WebPModule> {\n if (cachedModule) {\n return cachedModule;\n }\n\n const simdSupported = await detectSimd();\n const modulePath = simdSupported\n ? 'webp/webp_enc_simd.js'\n : 'webp/webp_enc.js';\n\n try {\n console.log('[WebP Worker] Initializing. SIMD support:', simdSupported);\n console.log(\n `[WebP Worker] Attempting to import module from path: ${modulePath}`\n );\n\n // Mock self.location for test environments where it doesn't exist\n // Emscripten code tries to access self.location.href during initialization\n // We set it to import.meta.url so _scriptDir will be used instead\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n // Also ensure self exists if it doesn't (for Emscripten code that checks ENVIRONMENT_IS_WORKER)\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n // Use a standard dynamic import instead of require, and tell Vite to ignore it\n // Using string concatenation to avoid bundler issues with template literals\n // Try both paths: './wasm/' for browser/dist and '../wasm/' for tests/source\n let moduleFactory;\n const pathsToTry = ['./wasm/' + modulePath, '../wasm/' + modulePath];\n\n let lastError: Error | null = null;\n for (const importPath of pathsToTry) {\n try {\n moduleFactory = (await import(/* @vite-ignore */ importPath)).default;\n console.log(\n `[WebP Worker] Successfully loaded module from: ${importPath}`\n );\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n console.warn(\n `[WebP Worker] Failed to load from ${importPath}, trying next path...`\n );\n }\n }\n\n if (!moduleFactory) {\n throw lastError || new Error('Could not load WebP module from any path');\n }\n\n console.log('[WebP Worker] Module factory loaded successfully.');\n\n // Try both paths for WASM binary as well\n const wasmPathsToTry = simdSupported\n ? ['./wasm/webp/webp_enc_simd.wasm', '../wasm/webp/webp_enc_simd.wasm']\n : ['./wasm/webp/webp_enc.wasm', '../wasm/webp/webp_enc.wasm'];\n\n console.log(\n `[WebP Worker] Preparing to load WASM binary. Will try paths: ${wasmPathsToTry.join(', ')}`\n );\n\n const initModuleWithBinary = async (\n moduleFactory: (config: {\n noInitialRun: boolean;\n wasmBinary?: ArrayBuffer;\n }) => Promise<WebPModule>,\n wasmPaths: string[]\n ): Promise<WebPModule> => {\n // Use the worker's own import.meta.url as the base for resolving WASM paths\n const workerBaseUrl = new URL('.', import.meta.url);\n let lastError: Error | null = null;\n for (const wasmPath of wasmPaths) {\n try {\n console.log(\n `[WebP Worker] Calling loadWasmBinary with path: ${wasmPath}`\n );\n const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);\n console.log(\n `[WebP Worker] Successfully fetched WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`\n );\n\n // Ensure self.location exists right before calling moduleFactory\n // Emscripten code accesses self.location.href when the factory is executed\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (\n typeof self === 'undefined' &&\n typeof globalThis !== 'undefined'\n ) {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n return await moduleFactory({\n noInitialRun: true,\n wasmBinary,\n });\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n console.warn(\n `[WebP Worker] Failed to load WASM from ${wasmPath}, trying next path...`\n );\n }\n }\n throw (\n lastError ||\n new Error('Could not load WASM binary from any of the attempted paths')\n );\n };\n\n cachedModule = await initModuleWithBinary(moduleFactory, wasmPathsToTry);\n console.log('[WebP Worker] WebP module initialized successfully.');\n return cachedModule;\n } catch (err) {\n console.error(\n `[WebP Worker] CRITICAL: Failed to load WebP module from path: ${modulePath}`,\n err\n );\n throw err;\n }\n}\n\n/**\n * Convert our simplified options to full EncodeOptions\n * Uses Squoosh defaults for optimal performance and file size\n */\nfunction createEncodeOptions(options?: EncodeInputOptions): EncodeOptions {\n // Squoosh defaults from their defaultOptions in meta.ts\n return {\n quality: options?.quality ?? 75,\n target_size: 0,\n target_PSNR: 0,\n method: options?.method ?? 4,\n sns_strength: options?.sns_strength ?? 50,\n filter_strength: options?.filter_strength ?? 60,\n filter_sharpness: options?.filter_sharpness ?? 0,\n filter_type: options?.filter_type ?? 1,\n partitions: options?.partitions ?? 0,\n segments: options?.segments ?? 4,\n pass: options?.pass ?? 1,\n show_compressed: 0,\n preprocessing: options?.preprocessing ?? 0,\n autofilter: options?.autofilter ?? 0,\n partition_limit: 0,\n alpha_compression: options?.alpha_compression ?? 1,\n alpha_filtering: options?.alpha_filtering ?? 1,\n alpha_quality: options?.alpha_quality ?? options?.quality ?? 75,\n lossless: options?.lossless ? 1 : 0,\n exact: options?.exact ?? 0,\n image_hint: options?.image_hint ?? 0,\n emulate_jpeg_size: 0,\n thread_level: 0,\n low_memory: 0,\n near_lossless: options?.near_lossless ?? options?.quality ?? 75,\n use_delta_palette: 0,\n use_sharp_yuv: options?.use_sharp_yuv ?? 0,\n };\n}\n\n/**\n * Client-mode WebP encoder (exported for direct use)\n */\nexport async function webpEncodeClient(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Validate inputs before starting\n validateImageInput(image);\n validateWebpOptions(options);\n\n // Check abort before starting\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n // Normalize image input\n const width = image.width;\n const height = image.height;\n const data = image.data;\n\n if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {\n throw new Error('Image data must be Uint8Array or Uint8ClampedArray');\n }\n\n const t0 = performance.now();\n const module = await loadWebPModule();\n const t1 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] module loading took ${(t1 - t0).toFixed(2)}ms`);\n console.log(\n `[WebP] Module type: ${cachedModule && 'encode' in cachedModule ? 'Ready' : 'Unknown'}`\n );\n }\n\n // Check abort after async operation\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const encodeOptions = createEncodeOptions(options);\n\n // Call the encode function with optimized data handling\n // Create a zero-copy Uint8Array view if needed (don't copy the buffer)\n const dataArray =\n data instanceof Uint8ClampedArray\n ? new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.length)\n : new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.length\n );\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] encode options:`, encodeOptions);\n }\n\n const t2 = performance.now();\n const result = module.encode(dataArray, width, height, encodeOptions);\n const t3 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP] actual encoding took ${(t3 - t2).toFixed(2)}ms`);\n }\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n if (!result) {\n throw new Error('WebP encoding failed');\n }\n\n return result;\n}\n\n/**\n * Worker message handler\n * Register the handler regardless of environment (for both worker context and tests)\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const request = data as WorkerRequest<{\n image: ImageInput;\n options?: EncodeInputOptions;\n }>;\n\n try {\n if (request.type === 'webp:encode') {\n const { image, options } = request.payload;\n\n const t0 = performance.now();\n const controller = new AbortController();\n const result = await webpEncodeClient(\n image,\n options,\n controller.signal\n );\n const t1 = performance.now();\n\n if (typeof console !== 'undefined' && console.log) {\n console.log(`[WebP Worker] encode took ${(t1 - t0).toFixed(2)}ms`);\n }\n\n // Create a clean buffer for transfer (zero-copy logic handled here)\n const outputData = new Uint8Array(result);\n\n // ONE LINE response with transfer!\n respondSuccess(request.id, outputData, [outputData.buffer]);\n } else {\n respondError(request.id, `Unknown message type: ${request.type}`);\n }\n } catch (error) {\n respondError(request.id, error);\n }\n };\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "oGAAO,FAA4uE,EAAK,SAAS,YAAY,SAAS,IAAI,WAAW,CAAC,EAAE,GAAG,IAAI,IAAI,EAA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30C32159311B64756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function
|
|
1
|
+
function D(f){if(typeof f!=="object"||f===null)throw TypeError("options must be an object");let b=f;if(b.width!==void 0){if(typeof b.width!=="number"||!Number.isInteger(b.width)||b.width<=0)throw RangeError(`options.width must be a positive integer, got ${b.width}`)}if(b.height!==void 0){if(typeof b.height!=="number"||!Number.isInteger(b.height)||b.height<=0)throw RangeError(`options.height must be a positive integer, got ${b.height}`)}if(b.method!==void 0){let $=["triangular","catrom","mitchell","lanczos3"];if(!$.includes(b.method))throw TypeError(`options.method must be one of: ${$.join(", ")}, got ${b.method}`)}if(b.premultiply!==void 0&&typeof b.premultiply!=="boolean")throw TypeError(`options.premultiply must be boolean, got ${typeof b.premultiply}`);if(b.linearRGB!==void 0&&typeof b.linearRGB!=="boolean")throw TypeError(`options.linearRGB must be boolean, got ${typeof b.linearRGB}`)}var K,X=null;function H(){if(X===null||X.buffer!==K.memory.buffer)X=new Uint8Array(K.memory.buffer);return X}var O=0;function C(f,b){let $=b(f.length*1);return H().set(f,$/1),O=f.length,$}var Y=null;function L(){if(Y===null||Y.buffer!==K.memory.buffer)Y=new Int32Array(K.memory.buffer);return Y}var Z=null;function U(){if(Z===null||Z.buffer!==K.memory.buffer)Z=new Uint8ClampedArray(K.memory.buffer);return Z}function W(f,b){return U().subarray(f/1,f/1+b)}function V(f,b,$,j,J,G,N,Q){try{let B=K.__wbindgen_add_to_stack_pointer(-16);var T=C(f,K.__wbindgen_malloc),I=O;K.resize(B,T,I,b,$,j,J,G,N,Q);var q=L()[B/4+0],x=L()[B/4+1],w=W(q,x).slice();return K.__wbindgen_free(q,x*1),w}finally{K.__wbindgen_add_to_stack_pointer(16)}}async function h(f,b){if(typeof Response==="function"&&f instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function")try{return await WebAssembly.instantiateStreaming(f,b)}catch(j){if(f.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",j);else throw j}let $=await f.arrayBuffer();return await WebAssembly.instantiate($,b)}else{let $=await WebAssembly.instantiate(f,b);if($ instanceof WebAssembly.Instance)return{instance:$,module:f};else return $}}async function S(f){if(typeof f>"u")f=new URL("squoosh_resize_bg.wasm","file:///home/bnowak/repos/squoosh-kit/packages/resize/wasm/squoosh_resize.js");let b={};if(typeof f==="string"||typeof Request==="function"&&f instanceof Request||typeof URL==="function"&&f instanceof URL)f=fetch(f);let{instance:$,module:j}=await h(await f,b);return K=$.exports,S.__wbindgen_wasm_module=j,K}var F=S;var k=null,R=null;async function y(){if(k)return;if(R)return R;return R=(async()=>{try{let f=new URL(".","file:///home/bnowak/repos/squoosh-kit/packages/resize/src/resize.worker.ts"),b=["./wasm/squoosh_resize_bg.wasm","../wasm/squoosh_resize_bg.wasm"],$=null,j=null;for(let J of b)try{$=await v(J,f);break}catch(G){j=G instanceof Error?G:Error(String(G))}if(!$)throw j||Error("Could not load WASM binary from any path");try{await F($)}catch(J){if(J instanceof Error&&(J.message.includes("SharedArrayBuffer")||J.message.includes("first argument must be"))){if(typeof SharedArrayBuffer>"u")globalThis.SharedArrayBuffer=ArrayBuffer;try{await F($)}catch(G){throw Error(`WASM module initialization failed even with polyfill: ${G instanceof Error?G.message:String(G)}`)}}else throw J}k=V}catch(f){throw R=null,Error(`Failed to initialize resize WASM module: ${f instanceof Error?f.message:String(f)}`)}})(),R}async function E(f,b){if(P(f),D(b),await y(),!k)throw Error("Resize module not initialized");let{data:$,width:j,height:J}=f,G=b.width??j,N=b.height??J;if(b.width&&!b.height)N=Math.max(1,Math.round(J*b.width/j));else if(b.height&&!b.width)G=Math.max(1,Math.round(j*b.height/J));if(G<1||N<1)throw RangeError(`Output dimensions must be at least 1x1, got ${G}x${N}`);let Q=$ instanceof Uint8ClampedArray?new Uint8Array($.buffer,$.byteOffset,$.length):new Uint8Array($.buffer,$.byteOffset,$.length);return{data:k(Q,j,J,G,N,l(b),b.premultiply??!0,b.linearRGB??!0),width:G,height:N}}async function d(f,b,$){if($?.aborted)throw new DOMException("Aborted","AbortError");return E(f,b)}function l(f){return{triangular:0,catrom:1,mitchell:2,lanczos3:3}[f?.method??"lanczos3"]??3}if(typeof self<"u")self.onmessage=async(f)=>{let b=f.data;if(b?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let{id:$,type:j,payload:J}=b;try{if(j!=="resize:run")throw Error(`Unknown message type: ${j}`);let G=await E(J.image,J.options),N=new Uint8ClampedArray(G.data),Q={...G,data:N};z($,Q,[N.buffer])}catch(G){A($,G)}};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=517528BEBE1B97EF64756E2164756E21
|