@squoosh-kit/core 0.1.15 → 0.1.16

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.
Files changed (61) hide show
  1. package/dist/chunk-02ytt443.js +5 -0
  2. package/dist/{chunk-cfpkr9nw.js.map → chunk-02ytt443.js.map} +4 -5
  3. package/dist/chunk-14jg2dxs.js +5 -0
  4. package/dist/chunk-14jg2dxs.js.map +10 -0
  5. package/dist/{chunk-kqn499ka.js → chunk-374tq8cw.js} +2 -2
  6. package/dist/chunk-374tq8cw.js.map +13 -0
  7. package/dist/chunk-3rt7m395.js +3 -0
  8. package/dist/{chunk-245sw6kx.js.map → chunk-3rt7m395.js.map} +3 -3
  9. package/dist/chunk-5ap8cyw0.js +4 -0
  10. package/dist/chunk-5ap8cyw0.js.map +13 -0
  11. package/dist/{chunk-kjhvs4qe.js → chunk-69d55ymx.js} +2 -2
  12. package/dist/{chunk-kjhvs4qe.js.map → chunk-69d55ymx.js.map} +3 -3
  13. package/dist/chunk-6d2104pn.js +3 -0
  14. package/dist/{chunk-vk3k7qxb.js.map → chunk-6d2104pn.js.map} +4 -5
  15. package/dist/chunk-btz1s2ws.js +3 -0
  16. package/dist/chunk-btz1s2ws.js.map +10 -0
  17. package/dist/chunk-h7zpk6jq.js +4 -0
  18. package/dist/chunk-h7zpk6jq.js.map +10 -0
  19. package/dist/chunk-mm6wmg56.js +4 -0
  20. package/dist/{chunk-d3fxpzrq.js.map → chunk-mm6wmg56.js.map} +4 -5
  21. package/dist/chunk-p24n653d.js +4 -0
  22. package/dist/{chunk-rta7shf1.js.map → chunk-p24n653d.js.map} +4 -5
  23. package/dist/chunk-rht1286y.js +3 -0
  24. package/dist/chunk-rht1286y.js.map +13 -0
  25. package/dist/chunk-vt6b43b9.js +3 -0
  26. package/dist/chunk-vt6b43b9.js.map +13 -0
  27. package/dist/chunk-yd1vfk89.js +4 -0
  28. package/dist/{chunk-sycf5j9m.js.map → chunk-yd1vfk89.js.map} +3 -3
  29. package/dist/chunk-yv042k8x.js +3 -0
  30. package/dist/{chunk-5d1w8na7.js.map → chunk-yv042k8x.js.map} +3 -3
  31. package/dist/index.browser.mjs +2 -2
  32. package/dist/index.browser.mjs.map +4 -3
  33. package/dist/index.bun.js +2 -2
  34. package/dist/index.bun.js.map +4 -3
  35. package/dist/index.node.cjs +2 -2
  36. package/dist/index.node.cjs.map +4 -3
  37. package/dist/index.node.mjs +2 -2
  38. package/dist/index.node.mjs.map +4 -3
  39. package/package.json +3 -3
  40. package/dist/chunk-245sw6kx.js +0 -3
  41. package/dist/chunk-5d1w8na7.js +0 -3
  42. package/dist/chunk-6qtap428.js +0 -4
  43. package/dist/chunk-6qtap428.js.map +0 -12
  44. package/dist/chunk-74bcayvr.js +0 -3
  45. package/dist/chunk-74bcayvr.js.map +0 -13
  46. package/dist/chunk-8r69sf95.js +0 -5
  47. package/dist/chunk-8r69sf95.js.map +0 -12
  48. package/dist/chunk-cfpkr9nw.js +0 -5
  49. package/dist/chunk-d3fxpzrq.js +0 -4
  50. package/dist/chunk-f8hc5gnf.js +0 -4
  51. package/dist/chunk-f8hc5gnf.js.map +0 -12
  52. package/dist/chunk-fks9mwgb.js +0 -3
  53. package/dist/chunk-fks9mwgb.js.map +0 -13
  54. package/dist/chunk-kqn499ka.js.map +0 -13
  55. package/dist/chunk-rta7shf1.js +0 -4
  56. package/dist/chunk-sycf5j9m.js +0 -4
  57. package/dist/chunk-t4jk8xn4.js +0 -3
  58. package/dist/chunk-t4jk8xn4.js.map +0 -12
  59. package/dist/chunk-vk3k7qxb.js +0 -3
  60. package/dist/chunk-wvd3rsja.js +0 -4
  61. package/dist/chunk-wvd3rsja.js.map +0 -13
@@ -1,13 +0,0 @@
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,CAAO,EACtB,MAAU,WACR,4DACF,EAGF,GAAI,OAAO,IAAY,SACrB,MAAU,UAAU,0BAA0B,EAGhD,GAAI,CAAC,OAAO,UAAU,CAAO,EAC3B,MAAU,WACR,mEACF,EAGF,GAAI,EAAU,GAAK,EAAU,IAC3B,MAAU,WACR,2CAA2C,GAC7C,GClBN,IAAI,EAAkC,KAEtC,eAAe,CAAc,EAAwB,CACnD,GAAI,EACF,OAAO,EAGT,IAAM,EAAgB,MAAM,EAAW,EACjC,EAAa,EACf,wBACA,mBA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Q,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
- }
@@ -1,5 +0,0 @@
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
@@ -1,12 +0,0 @@
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
- }
@@ -1,5 +0,0 @@
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,4 +0,0 @@
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,4 +0,0 @@
1
- import{d as J,e as K,f 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
@@ -1,12 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
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
@@ -1,13 +0,0 @@
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,CAAO,EACtB,MAAU,WACR,4DACF,EAGF,GAAI,OAAO,IAAY,SACrB,MAAU,UAAU,0BAA0B,EAGhD,GAAI,CAAC,OAAO,UAAU,CAAO,EAC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O,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
- }
@@ -1,13 +0,0 @@
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": "AAAO,IAA4uE,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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,QAAQ,IAC5C,QAAQ,IAAI,gCAAgC,EAAK,GAAI,QAAQ,CAAC,KAAK,EAGrE,GAAI,GAAQ,QACV,MAAM,IAAI,aAAa,UAAW,YAAY,EAGhD,GAAI,CAAC,EACH,MAAU,MAAM,sBAAsB,EAGxC,OAAO,EAOT,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,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": "E48E9E267FCA20FD64756E2164756E21",
12
- "names": []
13
- }
@@ -1,4 +0,0 @@
1
- var L=Object.create;var{getPrototypeOf:M,defineProperty:K,getOwnPropertyNames:N}=Object;var P=Object.prototype.hasOwnProperty;var Q=(q,H,E)=>{E=q!=null?L(M(q)):{};let F=H||!q||!q.__esModule?K(E,"default",{value:q,enumerable:!0}):E;for(let G of N(q))if(!P.call(F,G))K(F,G,{get:()=>q[G],enumerable:!0});return F};var R=((q)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(q,{get:(H,E)=>(typeof require<"u"?require:H)[E]}):q)(function(q){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});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:E}=H;if(!(E instanceof Uint8Array||E 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:F,height:G}=H;if(typeof F!=="number"||!Number.isInteger(F)||F<=0)throw RangeError(`image.width must be a positive integer, got ${F}`);if(typeof G!=="number"||!Number.isInteger(G)||G<=0)throw RangeError(`image.height must be a positive integer, got ${G}`);let J=F*G*4;if(E.length<J)throw RangeError(`image.data too small: ${E.length} bytes, expected at least ${J} bytes for ${F}x${G} RGBA image`)}function W(){return typeof Bun<"u"}function X(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}
2
- export{Q as d,R as e,W as f,X as g,U as h};
3
-
4
- //# debugId=9102CFDB2D39C7D464756E2164756E21
@@ -1,4 +0,0 @@
1
- // @bun
2
- import{a as v,b as z,c as A}from"./chunk-8r69sf95.js";import{h as P}from"./chunk-cfpkr9nw.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};
3
-
4
- //# debugId=04B58783BF17DA4264756E2164756E21
@@ -1,3 +0,0 @@
1
- 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 Q(z,j){let C=j?typeof j==="string"?new URL(".",j):new URL(".",j.href):new URL(".","file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/wasm-loader.ts"),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 V(z,j,C=[]){let q={id:z,ok:!0,data:j},D=C.filter((E)=>!(E instanceof SharedArrayBuffer));self.postMessage(q,D)}function W(z,j){let C=j instanceof Error?j.message:String(j),q={id:z,ok:!1,error:C};self.postMessage(q)}
2
-
3
- //# debugId=DBF0C4CD8FFD565464756E2164756E21
@@ -1,12 +0,0 @@
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": "AAOA,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,IAAiB,2EAAG,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": "DBF0C4CD8FFD565464756E2164756E21",
11
- "names": []
12
- }
@@ -1,3 +0,0 @@
1
- var P=Object.create;var{getPrototypeOf:Q,defineProperty:J,getOwnPropertyNames:M,getOwnPropertyDescriptor:R}=Object,N=Object.prototype.hasOwnProperty;var T=(q,E,G)=>{G=q!=null?P(Q(q)):{};let F=E||!q||!q.__esModule?J(G,"default",{value:q,enumerable:!0}):G;for(let H of M(q))if(!N.call(F,H))J(F,H,{get:()=>q[H],enumerable:!0});return F},L=new WeakMap,U=(q)=>{var E=L.get(q),G;if(E)return E;if(E=J({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function")M(q).map((F)=>!N.call(E,F)&&J(E,F,{get:()=>q[F],enumerable:!(G=R(q,F))||G.enumerable}));return L.set(q,E),E};var V=(q,E)=>{for(var G in E)J(q,G,{get:E[G],enumerable:!0,configurable:!0,set:(F)=>E[G]=()=>F})};function X(q){if(!q||typeof q!=="object")throw TypeError("image must be an object");let E=q;if(!("data"in E))throw TypeError("image.data is required");let{data:G}=E;if(!(G instanceof Uint8Array||G instanceof Uint8ClampedArray))throw TypeError("image.data must be Uint8Array or Uint8ClampedArray");if(!("width"in E)||!("height"in E))throw TypeError("image.width and image.height are required");let{width:F,height:H}=E;if(typeof F!=="number"||!Number.isInteger(F)||F<=0)throw RangeError(`image.width must be a positive integer, got ${F}`);if(typeof H!=="number"||!Number.isInteger(H)||H<=0)throw RangeError(`image.height must be a positive integer, got ${H}`);let K=F*H*4;if(G.length<K)throw RangeError(`image.data too small: ${G.length} bytes, expected at least ${K} bytes for ${F}x${H} RGBA image`)}function Z(){return typeof Bun<"u"}function _(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}
2
-
3
- //# debugId=DA15CB8ADE51A22664756E2164756E21
@@ -1,4 +0,0 @@
1
- // @bun
2
- import{a as G,b as X,c as C}from"./chunk-8r69sf95.js";import{h as Q}from"./chunk-cfpkr9nw.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};
3
-
4
- //# debugId=68396818A16DBA4164756E2164756E21
@@ -1,13 +0,0 @@
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,EAA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