@squoosh-kit/core 0.0.42 → 0.0.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-02ytt443.js +5 -0
- package/dist/{chunk-szbj3b6y.js.map → chunk-02ytt443.js.map} +2 -2
- package/dist/chunk-14jg2dxs.js +5 -0
- package/dist/chunk-14jg2dxs.js.map +10 -0
- package/dist/chunk-306sggvm.js +3 -0
- package/dist/{chunk-5c9bqcya.js.map → chunk-306sggvm.js.map} +2 -2
- package/dist/chunk-374tq8cw.js +3 -0
- package/dist/chunk-374tq8cw.js.map +13 -0
- package/dist/chunk-5ap8cyw0.js +4 -0
- package/dist/chunk-5ap8cyw0.js.map +13 -0
- package/dist/chunk-6d2104pn.js +3 -0
- package/dist/{chunk-gw29pvyv.js.map → chunk-6d2104pn.js.map} +2 -2
- package/dist/chunk-afsays66.js +3 -0
- package/dist/{chunk-1nammd75.js.map → chunk-afsays66.js.map} +2 -2
- package/dist/chunk-btz1s2ws.js +3 -0
- package/dist/chunk-btz1s2ws.js.map +10 -0
- package/dist/chunk-c2p25yd3.js +4 -0
- package/dist/{chunk-vd90dz6z.js.map → chunk-c2p25yd3.js.map} +2 -2
- package/dist/chunk-h7zpk6jq.js +4 -0
- package/dist/chunk-h7zpk6jq.js.map +10 -0
- package/dist/chunk-mm6wmg56.js +4 -0
- package/dist/{chunk-q0apy7nk.js.map → chunk-mm6wmg56.js.map} +2 -2
- package/dist/chunk-p24n653d.js +4 -0
- package/dist/chunk-p24n653d.js.map +10 -0
- package/dist/chunk-rht1286y.js +3 -0
- package/dist/chunk-rht1286y.js.map +13 -0
- package/dist/chunk-vt6b43b9.js +3 -0
- package/dist/chunk-vt6b43b9.js.map +13 -0
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +7 -7
- package/dist/index.bun.js +2 -2
- package/dist/index.bun.js.map +7 -7
- package/dist/index.node.cjs +2 -2
- package/dist/index.node.cjs.map +7 -7
- package/dist/index.node.mjs +2 -2
- package/dist/index.node.mjs.map +7 -7
- package/package.json +3 -3
- package/dist/chunk-0zm3fssb.js +0 -27
- package/dist/chunk-0zm3fssb.js.map +0 -14
- package/dist/chunk-1nammd75.js +0 -3
- package/dist/chunk-32b1dzdk.js +0 -4
- package/dist/chunk-32b1dzdk.js.map +0 -9
- package/dist/chunk-43p1mhfj.js +0 -28
- package/dist/chunk-43p1mhfj.js.map +0 -14
- package/dist/chunk-514jszrs.js +0 -27
- package/dist/chunk-514jszrs.js.map +0 -10
- package/dist/chunk-5c9bqcya.js +0 -3
- package/dist/chunk-7xbe4p9k.js +0 -27
- package/dist/chunk-7xbe4p9k.js.map +0 -14
- package/dist/chunk-7yfp7f89.js +0 -5
- package/dist/chunk-7yfp7f89.js.map +0 -9
- package/dist/chunk-8rd8cz4p.js +0 -4
- package/dist/chunk-8rd8cz4p.js.map +0 -10
- package/dist/chunk-cx0mw714.js +0 -5
- package/dist/chunk-cx0mw714.js.map +0 -10
- package/dist/chunk-djaabg7r.js +0 -3
- package/dist/chunk-djaabg7r.js.map +0 -9
- package/dist/chunk-dp7438g1.js +0 -28
- package/dist/chunk-dp7438g1.js.map +0 -10
- package/dist/chunk-esqbfmnq.js +0 -3
- package/dist/chunk-esqbfmnq.js.map +0 -10
- package/dist/chunk-gw29pvyv.js +0 -3
- package/dist/chunk-kqhkejsf.js +0 -4
- package/dist/chunk-kqhkejsf.js.map +0 -10
- package/dist/chunk-mj23nwx3.js +0 -4
- package/dist/chunk-mj23nwx3.js.map +0 -10
- package/dist/chunk-q0apy7nk.js +0 -5
- package/dist/chunk-r36yp9st.js +0 -27
- package/dist/chunk-r36yp9st.js.map +0 -10
- package/dist/chunk-szbj3b6y.js +0 -4
- package/dist/chunk-vd90dz6z.js +0 -4
- package/dist/chunk-xp5z79cc.js +0 -27
- package/dist/chunk-xp5z79cc.js.map +0 -10
- package/dist/chunk-yzhw1jkm.js +0 -27
- package/dist/chunk-yzhw1jkm.js.map +0 -14
- package/dist/chunk-zzfbcc7e.js +0 -4
- package/dist/chunk-zzfbcc7e.js.map +0 -9
package/dist/index.node.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var u={};f(u,{resize:()=>v,encode:()=>
|
|
1
|
+
var u={};f(u,{resize:()=>v,encode:()=>B,createWebpEncoder:()=>F,createResizer:()=>C});module.exports=b(u);function q(){return typeof Bun<"u"}var E=0;async function U(G,L,H,Q,J){return new Promise((V,K)=>{let $=++E;if(Q?.aborted){K(new DOMException("Aborted","AbortError"));return}let X=(Z)=>{let S=Z.data;if(S.id!==$)return;if(I(),S.ok&&S.data!==void 0)V(S.data);else K(Error(S.error||"Unknown worker error"))},Y=(Z)=>{I(),K(Error(`Worker error: ${Z.message}`))},_=()=>{I(),K(new DOMException("Aborted","AbortError"))},I=()=>{G.removeEventListener("message",X),G.removeEventListener("error",Y),Q?.removeEventListener("abort",_)};G.addEventListener("message",X),G.addEventListener("error",Y),Q?.addEventListener("abort",_);let O={type:L,id:$,payload:H};if(J&&J.length>0)G.postMessage(O,J);else G.postMessage(O)})}function M(G,L){let H=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},J=Q[H];if(!J)throw Error(`Unknown worker: ${H}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let X=J.package.split("/")[1],Y=H.replace(".js",".browser.mjs");if(console.log("[worker-helper] In browser environment. Trying to create worker:"),console.log(`[worker-helper] - Package Name: ${X}`),console.log(`[worker-helper] - Worker File: ${Y}`),L?.assetPath){let O=`${window.location.origin}${L.assetPath}${X}/${Y}`;console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${O}`);try{return new Worker(O,{type:"module"})}catch(Z){throw console.error(`[worker-helper] CRITICAL: new Worker() failed synchronously for URL: ${O}`,Z),Z}}let _=[`../../${X}/dist/${Y}`,`../../../node_modules/@squoosh-kit/${X}/dist/${Y}`,`../../../${X}/dist/${Y}`],I=null;for(let O of _)try{let Z=new URL(O,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${Z.href}`);let S=new Worker(Z,{type:"module"});return console.log(`[worker-helper] Successfully created worker with URL: ${Z.href}`),S}catch(Z){console.warn(`[worker-helper] Path strategy failed for ${O}:`,Z),I=Z instanceof Error?Z:Error(String(Z))}if(I)throw console.error("[worker-helper] All path strategies failed.",I),I;throw Error(`Could not resolve worker ${H} using any available path strategy`)}let V=q()?".bun.js":".node.mjs",K=H.replace(".js",""),$=J.package.includes("resize")?`../../resize/src/${K}.ts`:`../../webp/src/${K}.ts`;try{return new Worker(new URL($,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{let X=J.package.includes("resize")?`../../resize/dist/${K}.${V.slice(1)}`:`../../webp/dist/${K}.${V.slice(1)}`;try{return new Worker(new URL(X,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Y=import.meta.resolve(`${J.package}/${J.specifier}`);return new Worker(Y,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${H}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(V){let K=V instanceof Error?V.message:String(V);throw Error(`Failed to create worker from ${H}: ${K}. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. If you're using Vite, ensure the worker files are not being optimized as dependencies.`)}}function x(G,L,H=1e4){return new Promise((Q,J)=>{let V=setTimeout(()=>{J(Error(`Worker initialization timeout after ${H}ms. Worker file: ${G}`))},H),K;try{K=M(G,L)}catch(_){clearTimeout(V),J(_);return}let $=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),Q(K)},X=(_)=>{clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},Y=()=>{clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker message error during initialization. Worker file: ${G}`))};K.addEventListener("message",$),K.addEventListener("error",X),K.addEventListener("messageerror",Y),K.postMessage({type:"worker:ping"})})}class N{async encode(G,L,H){let J=(await import("./chunk-374tq8cw.js")).webpEncodeClient;return J(G,L,H)}async terminate(){}}class W{worker=null;workerReady=null;options;constructor(G){console.log("[webp/bridge] WebpWorkerBridge constructor called with options:",G),this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return console.log("[webp/bridge] createWorker called. Creating ready worker..."),this.worker=await x("webp.worker.js",this.options),console.log("[webp/bridge] createWorker: Ready worker created successfully."),this.worker}async encode(G,L,H){let Q=await this.getWorker();return A(G),U(Q,"webp:encode",{image:G,options:L},H)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function P(G,L){if(console.log(`[webp/bridge] createBridge called with mode: ${G}`),G==="worker")return new W(L);return new N}var D=null;async function B(G,L,H){if(!D)D=P("worker");return D.encode(G,L,H)}function F(G="worker",L){let H=P(G,L);return Object.assign((Q,J,V)=>{return H.encode(Q,J,V)},{terminate:async()=>{await H.terminate()}})}class z{async resize(G,L,H){let J=(await import("./chunk-3bjh9q3d.js")).resizeClient;return J(G,L,H)}async terminate(){}}class j{worker=null;workerReady=null;options;constructor(G){this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return this.worker=await x("resize.worker.js",this.options),this.worker}async resize(G,L,H){let Q=await this.getWorker();A(G);try{return await U(Q,"resize:run",{image:G,options:L},H)}catch(J){throw console.error("Resize error:",J),J}}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function R(G,L){if(G==="worker")return new j(L);return new z}var T=null;async function v(G,L,H){if(!T)T=R("worker");return T.resize(G,L,H)}function C(G="worker",L){let H=R(G,L);return Object.assign((Q,J,V)=>{return H.resize(Q,J,V)},{terminate:async()=>{await H.terminate()}})}
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=94FB2CD23DD2D91864756E2164756E21
|
package/dist/index.node.cjs.map
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n",
|
|
6
6
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(workerFilename: string): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n
|
|
8
|
-
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n\n private async getWorker(): Promise<Worker> {\n if (!this.
|
|
9
|
-
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker'\n): WebpEncoderFactory {\n const bridge = createBridge(mode);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
|
-
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n\n private async getWorker(): Promise<Worker> {\n if (!this.
|
|
11
|
-
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker'\n): ResizerFactory {\n const bridge = createBridge(mode);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n"
|
|
7
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n const workerUrl = `${window.location.origin}${options.assetPath}${packageName}/${workerFile}`;\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n return new Worker(workerUrl, { type: 'module' });\n } catch (e) {\n console.error(\n `[worker-helper] CRITICAL: new Worker() failed synchronously for URL: ${workerUrl}`,\n e\n );\n throw e;\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
|
+
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n console.log(\n '[webp/bridge] WebpWorkerBridge constructor called with options:',\n options\n );\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n console.log('[webp/bridge] createWorker called. Creating ready worker...');\n this.worker = await createReadyWorker('webp.worker.js', this.options);\n console.log(\n '[webp/bridge] createWorker: Ready worker created successfully.'\n );\n return this.worker;\n }\n\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n return callWorker(worker, 'webp:encode', { image, options }, signal);\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): WebPBridge {\n console.log(`[webp/bridge] createBridge called with mode: ${mode}`);\n if (mode === 'worker') {\n return new WebpWorkerBridge(options);\n }\n return new WebpClientBridge();\n}\n",
|
|
9
|
+
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): WebpEncoderFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
|
+
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n this.worker = await createReadyWorker('resize.worker.js', this.options);\n return this.worker;\n }\n\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n\n try {\n const result = await callWorker<\n { image: ImageInput; options: ResizeOptions },\n ImageInput\n >(worker, 'resize:run', { image, options }, signal);\n\n return result;\n } catch (error) {\n console.error('Resize error:', error);\n throw error;\n }\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): ResizeBridge {\n if (mode === 'worker') {\n return new ResizeWorkerBridge(options);\n }\n return new ResizeClientBridge();\n}\n",
|
|
11
|
+
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): ResizerFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n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,CAAC,EACH,EAAqB,EAAa,QAAQ,EAG5C,OAAO,EAAmB,OAAO,EAAW,EAAS,CAAM,EAStD,SAAS,CAAa,CAC3B,EAA4B,SAC5B,EACgB,CAChB,IAAM,EAAS,EAAa,EAAM,CAAO,EAEzC,OAAO,OAAO,OACZ,CAAC,EAAuB,EAAwB,IAAyB,CACvE,OAAO,EAAO,OAAO,EAAW,EAAS,CAAM,GAEjD,CACE,UAAW,SAAY,CACrB,MAAM,EAAO,UAAU,EAE3B,CACF",
|
|
14
|
+
"debugId": "94FB2CD23DD2D91864756E2164756E21",
|
|
15
15
|
"names": []
|
|
16
16
|
}
|
package/dist/index.node.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as
|
|
1
|
+
import{b as y,c as N,d as A}from"./chunk-mm6wmg56.js";function q(){return typeof Bun<"u"}var M=0;async function U(G,L,H,Q,J){return new Promise((V,K)=>{let $=++M;if(Q?.aborted){K(new DOMException("Aborted","AbortError"));return}let X=(Z)=>{let S=Z.data;if(S.id!==$)return;if(I(),S.ok&&S.data!==void 0)V(S.data);else K(Error(S.error||"Unknown worker error"))},Y=(Z)=>{I(),K(Error(`Worker error: ${Z.message}`))},_=()=>{I(),K(new DOMException("Aborted","AbortError"))},I=()=>{G.removeEventListener("message",X),G.removeEventListener("error",Y),Q?.removeEventListener("abort",_)};G.addEventListener("message",X),G.addEventListener("error",Y),Q?.addEventListener("abort",_);let O={type:L,id:$,payload:H};if(J&&J.length>0)G.postMessage(O,J);else G.postMessage(O)})}function B(G,L){let H=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},J=Q[H];if(!J)throw Error(`Unknown worker: ${H}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let X=J.package.split("/")[1],Y=H.replace(".js",".browser.mjs");if(console.log("[worker-helper] In browser environment. Trying to create worker:"),console.log(`[worker-helper] - Package Name: ${X}`),console.log(`[worker-helper] - Worker File: ${Y}`),L?.assetPath){let O=`${window.location.origin}${L.assetPath}${X}/${Y}`;console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${O}`);try{return new Worker(O,{type:"module"})}catch(Z){throw console.error(`[worker-helper] CRITICAL: new Worker() failed synchronously for URL: ${O}`,Z),Z}}let _=[`../../${X}/dist/${Y}`,`../../../node_modules/@squoosh-kit/${X}/dist/${Y}`,`../../../${X}/dist/${Y}`],I=null;for(let O of _)try{let Z=new URL(O,import.meta.url);console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${Z.href}`);let S=new Worker(Z,{type:"module"});return console.log(`[worker-helper] Successfully created worker with URL: ${Z.href}`),S}catch(Z){console.warn(`[worker-helper] Path strategy failed for ${O}:`,Z),I=Z instanceof Error?Z:Error(String(Z))}if(I)throw console.error("[worker-helper] All path strategies failed.",I),I;throw Error(`Could not resolve worker ${H} using any available path strategy`)}let V=q()?".bun.js":".node.mjs",K=H.replace(".js",""),$=J.package.includes("resize")?`../../resize/src/${K}.ts`:`../../webp/src/${K}.ts`;try{return new Worker(new URL($,import.meta.url),{type:"module"})}catch{let X=J.package.includes("resize")?`../../resize/dist/${K}.${V.slice(1)}`:`../../webp/dist/${K}.${V.slice(1)}`;try{return new Worker(new URL(X,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Y=import.meta.resolve(`${J.package}/${J.specifier}`);return new Worker(Y,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${H}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(V){let K=V instanceof Error?V.message:String(V);throw Error(`Failed to create worker from ${H}: ${K}. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. If you're using Vite, ensure the worker files are not being optimized as dependencies.`)}}function x(G,L,H=1e4){return new Promise((Q,J)=>{let V=setTimeout(()=>{J(Error(`Worker initialization timeout after ${H}ms. Worker file: ${G}`))},H),K;try{K=B(G,L)}catch(_){clearTimeout(V),J(_);return}let $=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),Q(K)},X=(_)=>{clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},Y=()=>{clearTimeout(V),K.removeEventListener("message",$),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker message error during initialization. Worker file: ${G}`))};K.addEventListener("message",$),K.addEventListener("error",X),K.addEventListener("messageerror",Y),K.postMessage({type:"worker:ping"})})}class W{async encode(G,L,H){let J=(await import("./chunk-rht1286y.js")).webpEncodeClient;return J(G,L,H)}async terminate(){}}class z{worker=null;workerReady=null;options;constructor(G){console.log("[webp/bridge] WebpWorkerBridge constructor called with options:",G),this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return console.log("[webp/bridge] createWorker called. Creating ready worker..."),this.worker=await x("webp.worker.js",this.options),console.log("[webp/bridge] createWorker: Ready worker created successfully."),this.worker}async encode(G,L,H){let Q=await this.getWorker();return A(G),U(Q,"webp:encode",{image:G,options:L},H)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function P(G,L){if(console.log(`[webp/bridge] createBridge called with mode: ${G}`),G==="worker")return new z(L);return new W}var D=null;async function w(G,L,H){if(!D)D=P("worker");return D.encode(G,L,H)}function p(G="worker",L){let H=P(G,L);return Object.assign((Q,J,V)=>{return H.encode(Q,J,V)},{terminate:async()=>{await H.terminate()}})}class j{async resize(G,L,H){let J=(await import("./chunk-306sggvm.js")).resizeClient;return J(G,L,H)}async terminate(){}}class E{worker=null;workerReady=null;options;constructor(G){this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return this.worker=await x("resize.worker.js",this.options),this.worker}async resize(G,L,H){let Q=await this.getWorker();A(G);try{return await U(Q,"resize:run",{image:G,options:L},H)}catch(J){throw console.error("Resize error:",J),J}}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function R(G,L){if(G==="worker")return new E(L);return new j}var T=null;async function s(G,L,H){if(!T)T=R("worker");return T.resize(G,L,H)}function n(G="worker",L){let H=R(G,L);return Object.assign((Q,J,V)=>{return H.resize(Q,J,V)},{terminate:async()=>{await H.terminate()}})}export{s as resize,w as encode,p as createWebpEncoder,n as createResizer};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=E4B17291D29C808164756E2164756E21
|
package/dist/index.node.mjs.map
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n",
|
|
6
6
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(workerFilename: string): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n
|
|
8
|
-
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n\n private async getWorker(): Promise<Worker> {\n if (!this.
|
|
9
|
-
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker'\n): WebpEncoderFactory {\n const bridge = createBridge(mode);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
|
-
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n\n private async getWorker(): Promise<Worker> {\n if (!this.
|
|
11
|
-
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker'\n): ResizerFactory {\n const bridge = createBridge(mode);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n"
|
|
7
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n const workerUrl = `${window.location.origin}${options.assetPath}${packageName}/${workerFile}`;\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n return new Worker(workerUrl, { type: 'module' });\n } catch (e) {\n console.error(\n `[worker-helper] CRITICAL: new Worker() failed synchronously for URL: ${workerUrl}`,\n e\n );\n throw e;\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
|
+
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n console.log(\n '[webp/bridge] WebpWorkerBridge constructor called with options:',\n options\n );\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n console.log('[webp/bridge] createWorker called. Creating ready worker...');\n this.worker = await createReadyWorker('webp.worker.js', this.options);\n console.log(\n '[webp/bridge] createWorker: Ready worker created successfully.'\n );\n return this.worker;\n }\n\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n return callWorker(worker, 'webp:encode', { image, options }, signal);\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): WebPBridge {\n console.log(`[webp/bridge] createBridge called with mode: ${mode}`);\n if (mode === 'worker') {\n return new WebpWorkerBridge(options);\n }\n return new WebpClientBridge();\n}\n",
|
|
9
|
+
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): WebpEncoderFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
|
+
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n this.worker = await createReadyWorker('resize.worker.js', this.options);\n return this.worker;\n }\n\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n\n try {\n const result = await callWorker<\n { image: ImageInput; options: ResizeOptions },\n ImageInput\n >(worker, 'resize:run', { image, options }, signal);\n\n return result;\n } catch (error) {\n console.error('Resize error:', error);\n throw error;\n }\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): ResizeBridge {\n if (mode === 'worker') {\n return new ResizeWorkerBridge(options);\n }\n return new ResizeClientBridge();\n}\n",
|
|
11
|
+
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): ResizerFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n"
|
|
12
12
|
],
|
|
13
|
-
"mappings": "
|
|
14
|
-
"debugId": "
|
|
13
|
+
"mappings": "sDAyBO,SAAS,CAAK,EAAY,CAC/B,OAAO,OAAO,IAAQ,ICTxB,IAAI,EAAY,EAYhB,eAAsB,CAA+B,CACnD,EACA,EACA,EACA,EACA,EACoB,CACpB,OAAO,IAAI,QAAmB,CAAC,EAAS,IAAW,CACjD,IAAM,EAAK,EAAE,EAGb,GAAI,GAAQ,QAAS,CACnB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,OAGF,IAAM,EAAgB,CAAC,IAAwB,CAC7C,IAAM,EAAW,EAAM,KACvB,GAAI,EAAS,KAAO,EAAI,OAIxB,GAFA,EAAQ,EAEJ,EAAS,IAAM,EAAS,OAAS,OACnC,EAAQ,EAAS,IAAI,EAErB,OAAW,MAAM,EAAS,OAAS,sBAAsB,CAAC,GAIxD,EAAc,CAAC,IAAsB,CACzC,EAAQ,EACR,EAAW,MAAM,iBAAiB,EAAM,SAAS,CAAC,GAG9C,EAAc,IAAM,CACxB,EAAQ,EACR,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,GAG5C,EAAU,IAAM,CACpB,EAAO,oBAAoB,UAAW,CAAa,EACnD,EAAO,oBAAoB,QAAS,CAAW,EAC/C,GAAQ,oBAAoB,QAAS,CAAW,GAIlD,EAAO,iBAAiB,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,GAAQ,iBAAiB,QAAS,CAAW,EAG7C,IAAM,EAAmC,CAAE,OAAM,KAAI,SAAQ,EAE7D,GAAI,GAAY,EAAS,OAAS,EAChC,EAAO,YAAY,EAAS,CAAQ,EAEpC,OAA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AExB,GAAI,CAMF,OALe,MAAM,EAGnB,EAAQ,aAAc,CAAE,QAAO,SAAQ,EAAG,CAAM,EAGlD,MAAO,EAAO,CAEd,MADA,QAAQ,MAAM,gBAAiB,CAAK,EAC9B,QAIJ,UAAS,EAAkB,CAC/B,GAAI,KAAK,OACP,KAAK,OAAO,UAAU,EACtB,KAAK,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAC1B,EACA,EACc,CACd,GAAI,IAAS,SACX,OAAO,IAAI,EAAmB,CAAO,EAEvC,OAAO,IAAI,EC9Fb,IAAI,EAA6D,KA+CjE,eAAsB,CAAM,CAC1B,EACA,EACA,EACqB,CAErB,GAAI,CAAC,EACH,EAAqB,EAAa,QAAQ,EAG5C,OAAO,EAAmB,OAAO,EAAW,EAAS,CAAM,EAStD,SAAS,CAAa,CAC3B,EAA4B,SAC5B,EACgB,CAChB,IAAM,EAAS,EAAa,EAAM,CAAO,EAEzC,OAAO,OAAO,OACZ,CAAC,EAAuB,EAAwB,IAAyB,CACvE,OAAO,EAAO,OAAO,EAAW,EAAS,CAAM,GAEjD,CACE,UAAW,SAAY,CACrB,MAAM,EAAO,UAAU,EAE3B,CACF",
|
|
14
|
+
"debugId": "E4B17291D29C808164756E2164756E21",
|
|
15
15
|
"names": []
|
|
16
16
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@squoosh-kit/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.44",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Per-feature adapters around Squoosh codecs, worker/client runtimes.",
|
|
6
6
|
"author": "Bartosz Nowak <bnowak008@gmail.com>",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"typecheck": "tsc --noEmit"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@squoosh-kit/webp": "0.0.
|
|
66
|
-
"@squoosh-kit/resize": "0.0.
|
|
65
|
+
"@squoosh-kit/webp": "0.0.43",
|
|
66
|
+
"@squoosh-kit/resize": "0.0.43"
|
|
67
67
|
}
|
|
68
68
|
}
|
package/dist/chunk-0zm3fssb.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import{a as o1}from"./chunk-8rd8cz4p.js";import{b as a1}from"./chunk-szbj3b6y.js";import{c as F5,d as z5}from"./chunk-zzfbcc7e.js";var u1=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 a=null,K1=null;async function s1(){if(a!==null)return a;if(K1)return K1;return K1=(async()=>{try{return a=await u1(),a}catch(q){return a=!1,console.warn("SIMD detection failed, falling back to standard WASM modules:",q),!1}})(),K1}function i1(q){if(q===void 0)return;if(typeof q!=="object"||q===null)throw TypeError("options must be an object or undefined");let C=q;if("quality"in C&&C.quality!==void 0){let J=C.quality;if(Number.isNaN(J))throw RangeError("quality must be a valid number in the range 0-100, got NaN");if(typeof J!=="number")throw TypeError("quality must be a number");if(!Number.isInteger(J))throw RangeError("quality must be an integer in the range 0-100, got floating point");if(J<0||J>100)throw RangeError(`quality must be in the range 0-100, got ${J}`)}}var R5=function(){var q=import.meta.url;return function(J){J=J||{};var J=typeof J<"u"?J:{},U,L;J.ready=new Promise(function(A,Q){U=A,L=Q});var W={},R;for(R in J)if(J.hasOwnProperty(R))W[R]=J[R];var y=[],l="./this.program",g=function(A,Q){throw Q},t=!1,c=!0,D="";function j1(A){if(J.locateFile)return J.locateFile(A,D);return D+A}var r1,t1,q1,e1;if(t||c){if(c)D=self.location.href;else if(typeof document<"u"&&document.currentScript)D=document.currentScript.src;if(q)D=q;if(D.indexOf("blob:")!==0)D=D.substr(0,D.lastIndexOf("/")+1);else D="";{if(r1=function(A){var Q=new XMLHttpRequest;return Q.open("GET",A,!1),Q.send(null),Q.responseText},c)q1=function(A){var Q=new XMLHttpRequest;return Q.open("GET",A,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)};t1=function(A,Q,X){var Z=new XMLHttpRequest;Z.open("GET",A,!0),Z.responseType="arraybuffer",Z.onload=function(){if(Z.status==200||Z.status==0&&Z.response){Q(Z.response);return}X()},Z.onerror=X,Z.send(null)}}e1=function(A){document.title=A}}var I5=J.print||console.log.bind(console),m=J.printErr||console.warn.bind(console);for(R in W)if(W.hasOwnProperty(R))J[R]=W[R];if(W=null,J.arguments)y=J.arguments;if(J.thisProgram)l=J.thisProgram;if(J.quit)g=J.quit;var d;if(J.wasmBinary)d=J.wasmBinary;var P5=J.noExitRuntime||!0;if(typeof WebAssembly!=="object")Q1("no native wasm support detected");var e,D1=!1,A0,Q0=new TextDecoder("utf8");function X0(A,Q){if(!A)return"";var X=A+Q;for(var Z=A;!(Z>=X)&&H[Z];)++Z;return Q0.decode(H.subarray(A,Z))}function Z0(A,Q,X,Z){if(!(Z>0))return 0;var Y=X,G=X+Z-1;for(var j=0;j<A.length;++j){var $=A.charCodeAt(j);if($>=55296&&$<=57343){var K=A.charCodeAt(++j);$=65536+(($&1023)<<10)|K&1023}if($<=127){if(X>=G)break;Q[X++]=$}else if($<=2047){if(X+1>=G)break;Q[X++]=192|$>>6,Q[X++]=128|$&63}else if($<=65535){if(X+2>=G)break;Q[X++]=224|$>>12,Q[X++]=128|$>>6&63,Q[X++]=128|$&63}else{if(X+3>=G)break;Q[X++]=240|$>>18,Q[X++]=128|$>>12&63,Q[X++]=128|$>>6&63,Q[X++]=128|$&63}}return Q[X]=0,X-Y}function J0(A,Q,X){return Z0(A,H,Q,X)}function Y0(A){var Q=0;for(var X=0;X<A.length;++X){var Z=A.charCodeAt(X);if(Z>=55296&&Z<=57343)Z=65536+((Z&1023)<<10)|A.charCodeAt(++X)&1023;if(Z<=127)++Q;else if(Z<=2047)Q+=2;else if(Z<=65535)Q+=3;else Q+=4}return Q}var $0=new TextDecoder("utf-16le");function G0(A,Q){var X=A,Z=X>>1,Y=Z+Q/2;while(!(Z>=Y)&&u[Z])++Z;return X=Z<<1,$0.decode(H.subarray(A,X));var G="";for(var j=0;!(j>=Q/2);++j){var $=x[A+j*2>>1];if($==0)break;G+=String.fromCharCode($)}return G}function K0(A,Q,X){if(X===void 0)X=2147483647;if(X<2)return 0;X-=2;var Z=Q,Y=X<A.length*2?X/2:A.length;for(var G=0;G<Y;++G){var j=A.charCodeAt(G);x[Q>>1]=j,Q+=2}return x[Q>>1]=0,Q-Z}function j0(A){return A.length*2}function q0(A,Q){var X=0,Z="";while(!(X>=Q/4)){var Y=f[A+X*4>>2];if(Y==0)break;if(++X,Y>=65536){var G=Y-65536;Z+=String.fromCharCode(55296|G>>10,56320|G&1023)}else Z+=String.fromCharCode(Y)}return Z}function O0(A,Q,X){if(X===void 0)X=2147483647;if(X<4)return 0;var Z=Q,Y=Z+X-4;for(var G=0;G<A.length;++G){var j=A.charCodeAt(G);if(j>=55296&&j<=57343){var $=A.charCodeAt(++G);j=65536+((j&1023)<<10)|$&1023}if(f[Q>>2]=j,Q+=4,Q+4>Y)break}return f[Q>>2]=0,Q-Z}function E0(A){var Q=0;for(var X=0;X<A.length;++X){var Z=A.charCodeAt(X);if(Z>=55296&&Z<=57343)++X;Q+=4}return Q}function V0(A,Q){if(A%Q>0)A+=Q-A%Q;return A}var O1,A1,H,x,u,f,_,k1,R1;function F1(A){O1=A,J.HEAP8=A1=new Int8Array(A),J.HEAP16=x=new Int16Array(A),J.HEAP32=f=new Int32Array(A),J.HEAPU8=H=new Uint8Array(A),J.HEAPU16=u=new Uint16Array(A),J.HEAPU32=_=new Uint32Array(A),J.HEAPF32=k1=new Float32Array(A),J.HEAPF64=R1=new Float64Array(A)}var w5=J.INITIAL_MEMORY||16777216,s,z1=[],C1=[],_1=[],W0=!1;function L0(){if(J.preRun){if(typeof J.preRun=="function")J.preRun=[J.preRun];while(J.preRun.length)H0(J.preRun.shift())}V1(z1)}function b0(){W0=!0,V1(C1)}function U0(){if(J.postRun){if(typeof J.postRun=="function")J.postRun=[J.postRun];while(J.postRun.length)D0(J.postRun.shift())}V1(_1)}function H0(A){z1.unshift(A)}function N0(A){C1.unshift(A)}function D0(A){_1.unshift(A)}var v=0,E1=null,i=null;function k0(A){if(v++,J.monitorRunDependencies)J.monitorRunDependencies(v)}function R0(A){if(v--,J.monitorRunDependencies)J.monitorRunDependencies(v);if(v==0){if(E1!==null)clearInterval(E1),E1=null;if(i){var Q=i;i=null,Q()}}}J.preloadedImages={},J.preloadedAudios={};function Q1(A){if(J.onAbort)J.onAbort(A);A+="",m(A),D1=!0,A0=1,A="abort("+A+"). Build with -s ASSERTIONS=1 for more info.";var Q=new WebAssembly.RuntimeError(A);throw L(Q),Q}var F0="data:application/octet-stream;base64,";function B1(A){return A.startsWith(F0)}if(J.locateFile){var z="webp_enc.wasm";if(!B1(z))z=j1(z)}else var z=new URL("webp_enc.wasm",import.meta.url).toString();function I1(A){try{if(A==z&&d)return new Uint8Array(d);if(q1)return q1(A);else throw"both async and sync fetching of the wasm failed"}catch(Q){Q1(Q)}}function z0(){if(!d&&(t||c)){if(typeof fetch==="function")return fetch(z,{credentials:"same-origin"}).then(function(A){if(!A.ok)throw"failed to load wasm binary file at '"+z+"'";return A.arrayBuffer()}).catch(function(){return I1(z)})}return Promise.resolve().then(function(){return I1(z)})}function C0(){var A={a:H5};function Q(j,$){var K=j.exports;J.asm=K,e=J.asm.x,F1(e.buffer),s=J.asm.D,N0(J.asm.y),R0("wasm-instantiate")}k0("wasm-instantiate");function X(j){Q(j.instance)}function Z(j){return z0().then(function($){var K=WebAssembly.instantiate($,A);return K}).then(j,function($){m("failed to asynchronously prepare wasm: "+$),Q1($)})}function Y(){if(!d&&typeof WebAssembly.instantiateStreaming==="function"&&!B1(z)&&typeof fetch==="function")return fetch(z,{credentials:"same-origin"}).then(function(j){var $=WebAssembly.instantiateStreaming(j,A);return $.then(X,function(K){return m("wasm streaming compile failed: "+K),m("falling back to ArrayBuffer instantiation"),Z(X)})});else return Z(X)}if(J.instantiateWasm)try{var G=J.instantiateWasm(A,Q);return G}catch(j){return m("Module.instantiateWasm callback failed with error: "+j),!1}return Y().catch(L),{}}function V1(A){while(A.length>0){var Q=A.shift();if(typeof Q=="function"){Q(J);continue}var X=Q.func;if(typeof X==="number")if(Q.arg===void 0)s.get(X)();else s.get(X)(Q.arg);else X(Q.arg===void 0?null:Q.arg)}}function _0(A,Q){}function B0(A,Q){return _0(A,Q)}var X1={};function P1(A){while(A.length){var Q=A.pop(),X=A.pop();X(Q)}}function Z1(A){return this.fromWireType(_[A>>2])}var p={},T={},J1={},I0=48,P0=57;function w1(A){if(A===void 0)return"_unknown";A=A.replace(/[^a-zA-Z0-9_]/g,"$");var Q=A.charCodeAt(0);if(Q>=I0&&Q<=P0)return"_"+A;else return A}function W1(A,Q){return A=w1(A),Function("body","return function "+A+`() {
|
|
2
|
-
"use strict"; return body.apply(this, arguments);
|
|
3
|
-
};
|
|
4
|
-
`)(Q)}function L1(A,Q){var X=W1(Q,function(Z){this.name=Q,this.message=Z;var Y=Error(Z).stack;if(Y!==void 0)this.stack=this.toString()+`
|
|
5
|
-
`+Y.replace(/^Error(:[^\n]*)?\n/,"")});return X.prototype=Object.create(A.prototype),X.prototype.constructor=X,X.prototype.toString=function(){if(this.message===void 0)return this.name;else return this.name+": "+this.message},X}var S1=void 0;function f1(A){throw new S1(A)}function M1(A,Q,X){A.forEach(function($){J1[$]=Q});function Z($){var K=X($);if(K.length!==A.length)f1("Mismatched type converter count");for(var O=0;O<A.length;++O)B(A[O],K[O])}var Y=Array(Q.length),G=[],j=0;if(Q.forEach(function($,K){if(T.hasOwnProperty($))Y[K]=T[$];else{if(G.push($),!p.hasOwnProperty($))p[$]=[];p[$].push(function(){if(Y[K]=T[$],++j,j===G.length)Z(Y)})}}),G.length===0)Z(Y)}function w0(A){var Q=X1[A];delete X1[A];var{rawConstructor:X,rawDestructor:Z,fields:Y}=Q,G=Y.map(function(j){return j.getterReturnType}).concat(Y.map(function(j){return j.setterArgumentType}));M1([A],G,function(j){var $={};return Y.forEach(function(K,O){var E=K.fieldName,V=j[O],N=K.getter,S=K.getterContext,I=j[O+Y.length],h=K.setter,M=K.setterContext;$[E]={read:function(o){return V.fromWireType(N(S,o))},write:function(o,k5){var d1=[];h(M,o,I.toWireType(d1,k5)),P1(d1)}}}),[{name:Q.name,fromWireType:function(K){var O={};for(var E in $)O[E]=$[E].read(K);return Z(K),O},toWireType:function(K,O){for(var E in $)if(!(E in O))throw TypeError('Missing field: "'+E+'"');var V=X();for(E in $)$[E].write(V,O[E]);if(K!==null)K.push(Z,V);return V},argPackAdvance:8,readValueFromPointer:Z1,destructorFunction:Z}]})}function S0(A,Q,X,Z,Y){}function Y1(A){switch(A){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw TypeError("Unknown type size: "+A)}}function f0(){var A=Array(256);for(var Q=0;Q<256;++Q)A[Q]=String.fromCharCode(Q);x1=A}var x1=void 0;function b(A){var Q="",X=A;while(H[X])Q+=x1[H[X++]];return Q}var v1=void 0;function k(A){throw new v1(A)}function B(A,Q,X){if(X=X||{},!("argPackAdvance"in Q))throw TypeError("registerType registeredInstance requires argPackAdvance");var Z=Q.name;if(!A)k('type "'+Z+'" must have a positive integer typeid pointer');if(T.hasOwnProperty(A))if(X.ignoreDuplicateRegistrations)return;else k("Cannot register type '"+Z+"' twice");if(T[A]=Q,delete J1[A],p.hasOwnProperty(A)){var Y=p[A];delete p[A],Y.forEach(function(G){G()})}}function M0(A,Q,X,Z,Y){var G=Y1(X);Q=b(Q),B(A,{name:Q,fromWireType:function(j){return!!j},toWireType:function(j,$){return $?Z:Y},argPackAdvance:8,readValueFromPointer:function(j){var $;if(X===1)$=A1;else if(X===2)$=x;else if(X===4)$=f;else throw TypeError("Unknown boolean type size: "+Q);return this.fromWireType($[j>>G])},destructorFunction:null})}var b1=[],F=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function T1(A){if(A>4&&--F[A].refcount===0)F[A]=void 0,b1.push(A)}function x0(){var A=0;for(var Q=5;Q<F.length;++Q)if(F[Q]!==void 0)++A;return A}function v0(){for(var A=5;A<F.length;++A)if(F[A]!==void 0)return F[A];return null}function T0(){J.count_emval_handles=x0,J.get_first_emval=v0}function $1(A){switch(A){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var Q=b1.length?b1.pop():F.length;return F[Q]={refcount:1,value:A},Q}}}function h0(A,Q){Q=b(Q),B(A,{name:Q,fromWireType:function(X){var Z=F[X].value;return T1(X),Z},toWireType:function(X,Z){return $1(Z)},argPackAdvance:8,readValueFromPointer:Z1,destructorFunction:null})}function y0(A,Q,X){if(A[Q].overloadTable===void 0){var Z=A[Q];A[Q]=function(){if(!A[Q].overloadTable.hasOwnProperty(arguments.length))k("Function '"+X+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+A[Q].overloadTable+")!");return A[Q].overloadTable[arguments.length].apply(this,arguments)},A[Q].overloadTable=[],A[Q].overloadTable[Z.argCount]=Z}}function h1(A,Q,X){if(J.hasOwnProperty(A)){if(X===void 0||J[A].overloadTable!==void 0&&J[A].overloadTable[X]!==void 0)k("Cannot register public name '"+A+"' twice");if(y0(J,A,A),J.hasOwnProperty(X))k("Cannot register multiple overloads of a function with the same number of arguments ("+X+")!");J[A].overloadTable[X]=Q}else if(J[A]=Q,X!==void 0)J[A].numArguments=X}function g0(A,Q,X){switch(Q){case 0:return function(Z){var Y=X?A1:H;return this.fromWireType(Y[Z])};case 1:return function(Z){var Y=X?x:u;return this.fromWireType(Y[Z>>1])};case 2:return function(Z){var Y=X?f:_;return this.fromWireType(Y[Z>>2])};default:throw TypeError("Unknown integer type: "+A)}}function c0(A,Q,X,Z){var Y=Y1(X);Q=b(Q);function G(){}G.values={},B(A,{name:Q,constructor:G,fromWireType:function(j){return this.constructor.values[j]},toWireType:function(j,$){return $.value},argPackAdvance:8,readValueFromPointer:g0(Q,Y,Z),destructorFunction:null}),h1(Q,G)}function y1(A){var Q=m1(A),X=b(Q);return w(Q),X}function g1(A,Q){var X=T[A];if(X===void 0)k(Q+" has unknown type "+y1(A));return X}function p0(A,Q,X){var Z=g1(A,"enum");Q=b(Q);var Y=Z.constructor,G=Object.create(Z.constructor.prototype,{value:{value:X},constructor:{value:W1(Z.name+"_"+Q,function(){})}});Y.values[X]=G,Y[Q]=G}function U1(A){if(A===null)return"null";var Q=typeof A;if(Q==="object"||Q==="array"||Q==="function")return A.toString();else return""+A}function l0(A,Q){switch(Q){case 2:return function(X){return this.fromWireType(k1[X>>2])};case 3:return function(X){return this.fromWireType(R1[X>>3])};default:throw TypeError("Unknown float type: "+A)}}function m0(A,Q,X){var Z=Y1(X);Q=b(Q),B(A,{name:Q,fromWireType:function(Y){return Y},toWireType:function(Y,G){if(typeof G!=="number"&&typeof G!=="boolean")throw TypeError('Cannot convert "'+U1(G)+'" to '+this.name);return G},argPackAdvance:8,readValueFromPointer:l0(Q,Z),destructorFunction:null})}function d0(A,Q){if(!(A instanceof Function))throw TypeError("new_ called with constructor type "+typeof A+" which is not a function");var X=W1(A.name||"unknownFunctionName",function(){});X.prototype=A.prototype;var Z=new X,Y=A.apply(Z,Q);return Y instanceof Object?Y:Z}function u0(A,Q,X,Z,Y){var G=Q.length;if(G<2)k("argTypes array size mismatch! Must at least get return value and 'this' types!");var j=Q[1]!==null&&X!==null,$=!1;for(var K=1;K<Q.length;++K)if(Q[K]!==null&&Q[K].destructorFunction===void 0){$=!0;break}var O=Q[0].name!=="void",E="",V="";for(var K=0;K<G-2;++K)E+=(K!==0?", ":"")+"arg"+K,V+=(K!==0?", ":"")+"arg"+K+"Wired";var N="return function "+w1(A)+"("+E+`) {
|
|
6
|
-
if (arguments.length !== `+(G-2)+`) {
|
|
7
|
-
throwBindingError('function `+A+" called with ' + arguments.length + ' arguments, expected "+(G-2)+` args!');
|
|
8
|
-
}
|
|
9
|
-
`;if($)N+=`var destructors = [];
|
|
10
|
-
`;var S=$?"destructors":"null",I=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],h=[k,Z,Y,P1,Q[0],Q[1]];if(j)N+="var thisWired = classParam.toWireType("+S+`, this);
|
|
11
|
-
`;for(var K=0;K<G-2;++K)N+="var arg"+K+"Wired = argType"+K+".toWireType("+S+", arg"+K+"); // "+Q[K+2].name+`
|
|
12
|
-
`,I.push("argType"+K),h.push(Q[K+2]);if(j)V="thisWired"+(V.length>0?", ":"")+V;if(N+=(O?"var rv = ":"")+"invoker(fn"+(V.length>0?", ":"")+V+`);
|
|
13
|
-
`,$)N+=`runDestructors(destructors);
|
|
14
|
-
`;else for(var K=j?1:2;K<Q.length;++K){var M=K===1?"thisWired":"arg"+(K-2)+"Wired";if(Q[K].destructorFunction!==null)N+=M+"_dtor("+M+"); // "+Q[K].name+`
|
|
15
|
-
`,I.push(M+"_dtor"),h.push(Q[K].destructorFunction)}if(O)N+=`var ret = retType.fromWireType(rv);
|
|
16
|
-
return ret;
|
|
17
|
-
`;N+=`}
|
|
18
|
-
`,I.push(N);var o=d0(Function,I).apply(null,h);return o}function s0(A,Q){var X=[];for(var Z=0;Z<A;Z++)X.push(f[(Q>>2)+Z]);return X}function i0(A,Q,X){if(!J.hasOwnProperty(A))f1("Replacing nonexistant public symbol");if(J[A].overloadTable!==void 0&&X!==void 0)J[A].overloadTable[X]=Q;else J[A]=Q,J[A].argCount=X}function n0(A,Q,X){var Z=J["dynCall_"+A];return X&&X.length?Z.apply(null,[Q].concat(X)):Z.call(null,Q)}function o0(A,Q,X){if(A.includes("j"))return n0(A,Q,X);return s.get(Q).apply(null,X)}function a0(A,Q){var X=[];return function(){X.length=arguments.length;for(var Z=0;Z<arguments.length;Z++)X[Z]=arguments[Z];return o0(A,Q,X)}}function n(A,Q){A=b(A);function X(){if(A.includes("j"))return a0(A,Q);return s.get(Q)}var Z=X();if(typeof Z!=="function")k("unknown function pointer with signature "+A+": "+Q);return Z}var c1=void 0;function r0(A,Q){var X=[],Z={};function Y(G){if(Z[G])return;if(T[G])return;if(J1[G]){J1[G].forEach(Y);return}X.push(G),Z[G]=!0}throw Q.forEach(Y),new c1(A+": "+X.map(y1).join([", "]))}function t0(A,Q,X,Z,Y,G){var j=s0(Q,X);A=b(A),Y=n(Z,Y),h1(A,function(){r0("Cannot call "+A+" due to unbound types",j)},Q-1),M1([],j,function($){var K=[$[0],null].concat($.slice(1));return i0(A,u0(A,K,null,Y,G),Q-1),[]})}function e0(A,Q,X){switch(Q){case 0:return X?function(Y){return A1[Y]}:function(Y){return H[Y]};case 1:return X?function(Y){return x[Y>>1]}:function(Y){return u[Y>>1]};case 2:return X?function(Y){return f[Y>>2]}:function(Y){return _[Y>>2]};default:throw TypeError("Unknown integer type: "+A)}}function A5(A,Q,X,Z,Y){if(Q=b(Q),Y===-1)Y=4294967295;var G=Y1(X),j=function(O){return O};if(Z===0){var $=32-8*X;j=function(O){return O<<$>>>$}}var K=Q.includes("unsigned");B(A,{name:Q,fromWireType:j,toWireType:function(O,E){if(typeof E!=="number"&&typeof E!=="boolean")throw TypeError('Cannot convert "'+U1(E)+'" to '+this.name);if(E<Z||E>Y)throw TypeError('Passing a number "'+U1(E)+'" from JS side to C/C++ side to an argument of type "'+Q+'", which is outside the valid range ['+Z+", "+Y+"]!");return K?E>>>0:E|0},argPackAdvance:8,readValueFromPointer:e0(Q,G,Z!==0),destructorFunction:null})}function Q5(A,Q,X){var Z=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Y=Z[Q];function G(j){j=j>>2;var $=_,K=$[j],O=$[j+1];return new Y(O1,O,K)}X=b(X),B(A,{name:X,fromWireType:G,argPackAdvance:8,readValueFromPointer:G},{ignoreDuplicateRegistrations:!0})}function X5(A,Q){Q=b(Q);var X=Q==="std::string";B(A,{name:Q,fromWireType:function(Z){var Y=_[Z>>2],G;if(X){var j=Z+4;for(var $=0;$<=Y;++$){var K=Z+4+$;if($==Y||H[K]==0){var O=K-j,E=X0(j,O);if(G===void 0)G=E;else G+=String.fromCharCode(0),G+=E;j=K+1}}}else{var V=Array(Y);for(var $=0;$<Y;++$)V[$]=String.fromCharCode(H[Z+4+$]);G=V.join("")}return w(Z),G},toWireType:function(Z,Y){if(Y instanceof ArrayBuffer)Y=new Uint8Array(Y);var G,j=typeof Y==="string";if(!(j||Y instanceof Uint8Array||Y instanceof Uint8ClampedArray||Y instanceof Int8Array))k("Cannot pass non-string to std::string");if(X&&j)G=function(){return Y0(Y)};else G=function(){return Y.length};var $=G(),K=H1(4+$+1);if(_[K>>2]=$,X&&j)J0(Y,K+4,$+1);else if(j)for(var O=0;O<$;++O){var E=Y.charCodeAt(O);if(E>255)w(K),k("String has UTF-16 code units that do not fit in 8 bits");H[K+4+O]=E}else for(var O=0;O<$;++O)H[K+4+O]=Y[O];if(Z!==null)Z.push(w,K);return K},argPackAdvance:8,readValueFromPointer:Z1,destructorFunction:function(Z){w(Z)}})}function Z5(A,Q,X){X=b(X);var Z,Y,G,j,$;if(Q===2)Z=G0,Y=K0,j=j0,G=function(){return u},$=1;else if(Q===4)Z=q0,Y=O0,j=E0,G=function(){return _},$=2;B(A,{name:X,fromWireType:function(K){var O=_[K>>2],E=G(),V,N=K+4;for(var S=0;S<=O;++S){var I=K+4+S*Q;if(S==O||E[I>>$]==0){var h=I-N,M=Z(N,h);if(V===void 0)V=M;else V+=String.fromCharCode(0),V+=M;N=I+Q}}return w(K),V},toWireType:function(K,O){if(typeof O!=="string")k("Cannot pass non-string to C++ string type "+X);var E=j(O),V=H1(4+E+Q);if(_[V>>2]=E>>$,Y(O,V+4,E+Q),K!==null)K.push(w,V);return V},argPackAdvance:8,readValueFromPointer:Z1,destructorFunction:function(K){w(K)}})}function J5(A,Q,X,Z,Y,G){X1[A]={name:b(Q),rawConstructor:n(X,Z),rawDestructor:n(Y,G),fields:[]}}function Y5(A,Q,X,Z,Y,G,j,$,K,O){X1[A].fields.push({fieldName:b(Q),getterReturnType:X,getter:n(Z,Y),getterContext:G,setterArgumentType:j,setter:n($,K),setterContext:O})}function $5(A,Q){Q=b(Q),B(A,{isVoid:!0,name:Q,argPackAdvance:0,fromWireType:function(){return},toWireType:function(X,Z){return}})}var G5={};function K5(A){var Q=G5[A];if(Q===void 0)return b(A);else return Q}function p1(){if(typeof globalThis==="object")return globalThis;return function(){return Function}()("return this")()}function j5(A){if(A===0)return $1(p1());else return A=K5(A),$1(p1()[A])}function q5(A){if(A>4)F[A].refcount+=1}function O5(A){var Q="";for(var X=0;X<A;++X)Q+=(X!==0?", ":"")+"arg"+X;var Z="return function emval_allocator_"+A+`(constructor, argTypes, args) {
|
|
19
|
-
`;for(var X=0;X<A;++X)Z+="var argType"+X+" = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + "+X+'], "parameter '+X+`");
|
|
20
|
-
var arg`+X+" = argType"+X+`.readValueFromPointer(args);
|
|
21
|
-
args += argType`+X+`['argPackAdvance'];
|
|
22
|
-
`;return Z+="var obj = new constructor("+Q+`);
|
|
23
|
-
return __emval_register(obj);
|
|
24
|
-
}
|
|
25
|
-
`,Function("requireRegisteredType","Module","__emval_register",Z)(g1,J,$1)}var l1={};function E5(A){if(!A)k("Cannot use deleted val. handle = "+A);return F[A].value}function V5(A,Q,X,Z){A=E5(A);var Y=l1[Q];if(!Y)Y=O5(Q),l1[Q]=Y;return Y(A,X,Z)}function W5(){Q1()}function L5(A,Q,X){H.copyWithin(A,Q,Q+X)}function b5(A){try{return e.grow(A-O1.byteLength+65535>>>16),F1(e.buffer),1}catch(Q){}}function U5(A){var Q=H.length;A=A>>>0;var X=2147483648;if(A>X)return!1;for(var Z=1;Z<=4;Z*=2){var Y=Q*(1+0.2/Z);Y=Math.min(Y,A+100663296);var G=Math.min(X,V0(Math.max(A,Y),65536)),j=b5(G);if(j)return!0}return!1}S1=J.InternalError=L1(Error,"InternalError"),f0(),v1=J.BindingError=L1(Error,"BindingError"),T0(),c1=J.UnboundTypeError=L1(Error,"UnboundTypeError");var H5={w:B0,l:w0,p:S0,s:M0,r:h0,n:c0,d:p0,j:m0,h:t0,c:A5,b:Q5,k:X5,g:Z5,m:J5,a:Y5,t:$5,f:T1,v:j5,u:q5,o:V5,i:W5,q:L5,e:U5},S5=C0(),N5=J.___wasm_call_ctors=function(){return(N5=J.___wasm_call_ctors=J.asm.y).apply(null,arguments)},H1=J._malloc=function(){return(H1=J._malloc=J.asm.z).apply(null,arguments)},w=J._free=function(){return(w=J._free=J.asm.A).apply(null,arguments)},m1=J.___getTypeName=function(){return(m1=J.___getTypeName=J.asm.B).apply(null,arguments)},D5=J.___embind_register_native_and_builtin_types=function(){return(D5=J.___embind_register_native_and_builtin_types=J.asm.C).apply(null,arguments)},G1;i=function A(){if(!G1)N1();if(!G1)i=A};function N1(A){if(A=A||y,v>0)return;if(L0(),v>0)return;function Q(){if(G1)return;if(G1=!0,J.calledRun=!0,D1)return;if(b0(),U(J),J.onRuntimeInitialized)J.onRuntimeInitialized();U0()}if(J.setStatus)J.setStatus("Running..."),setTimeout(function(){setTimeout(function(){J.setStatus("")},1),Q()},1);else Q()}if(J.run=N1,J.preInit){if(typeof J.preInit=="function")J.preInit=[J.preInit];while(J.preInit.length>0)J.preInit.pop()()}return N1(),J.ready}}(),n1=R5;var P=null,r=null;async function C5(){if(P)return P;if(r)return r;return r=(async()=>{try{if(typeof self>"u")global.self=global;if(typeof self<"u"&&!self.location)self.location={href:import.meta.url};if(typeof SharedArrayBuffer>"u"&&typeof window>"u")globalThis.SharedArrayBuffer=ArrayBuffer;let q=async(J,U)=>{try{let L=await o1(U);if(typeof console<"u"&&console.log)console.log(`[WebP] Loaded WASM binary from ${U} (${(L.byteLength/1024).toFixed(1)}KB)`);return J({noInitialRun:!0,wasmBinary:L})}catch(L){if(typeof console<"u"&&console.warn)console.warn("[WebP] Failed to load WASM binary explicitly, trying module initialization without it:",L);return J({noInitialRun:!0})}};if(await s1()){if(typeof console<"u"&&console.log)console.log("[WebP] SIMD support detected, loading SIMD encoder");try{let J=await import("./chunk-r36yp9st.js");if(P=await q(J.default,new URL("../wasm/webp/webp_enc_simd.wasm",import.meta.url).href),P)return P}catch(J){if(typeof console<"u"&&console.warn)console.warn("[WebP] Failed to load SIMD encoder, falling back to standard:",J)}}if(P=await q(n1,new URL("../wasm/webp/webp_enc.wasm",import.meta.url).href),!P)throw Error("Failed to load WebP module");return P}catch(q){throw r=null,Error(`Failed to load WebP module: ${q instanceof Error?q.message:String(q)}`)}})(),r}function _5(q){return{quality:q?.quality??75,target_size:0,target_PSNR:0,method:q?.method??4,sns_strength:q?.sns_strength??50,filter_strength:q?.filter_strength??60,filter_sharpness:q?.filter_sharpness??0,filter_type:q?.filter_type??1,partitions:q?.partitions??0,segments:q?.segments??4,pass:q?.pass??1,show_compressed:0,preprocessing:q?.preprocessing??0,autofilter:q?.autofilter??0,partition_limit:0,alpha_compression:q?.alpha_compression??1,alpha_filtering:q?.alpha_filtering??1,alpha_quality:q?.alpha_quality??q?.quality??75,lossless:q?.lossless?1:0,exact:q?.exact??0,image_hint:q?.image_hint??0,emulate_jpeg_size:0,thread_level:0,low_memory:0,near_lossless:q?.near_lossless??q?.quality??75,use_delta_palette:0,use_sharp_yuv:q?.use_sharp_yuv??0}}async function B5(q,C,J){if(a1(q),i1(C),J?.aborted)throw new DOMException("Aborted","AbortError");let{width:U,height:L,data:W}=q;if(!(W instanceof Uint8Array)&&!(W instanceof Uint8ClampedArray))throw Error("Image data must be Uint8Array or Uint8ClampedArray");let R=performance.now(),y=await C5(),l=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] module loading took ${(l-R).toFixed(2)}ms`),console.log(`[WebP] Module type: ${P&&"encode"in P?"Ready":"Unknown"}`);if(J?.aborted)throw new DOMException("Aborted","AbortError");let g=_5(C),t=W instanceof Uint8ClampedArray?new Uint8Array(W.buffer,W.byteOffset,W.length):new Uint8Array(W.buffer,W.byteOffset,W.length);if(typeof console<"u"&&console.log)console.log("[WebP] encode options:",g);let c=performance.now(),D=y.encode(t,U,L,g),j1=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP] actual encoding took ${(j1-c).toFixed(2)}ms`);if(J?.aborted)throw new DOMException("Aborted","AbortError");if(!D)throw Error("WebP encoding failed");return D}if(typeof self<"u")self.onmessage=async(q)=>{let C=q.data;if(C?.type==="worker:ping"){self.postMessage({type:"worker:ready"});return}let J=C,U={id:J.id,ok:!1};try{if(J.type==="webp:encode"){let{image:L,options:W}=J.payload,R=performance.now(),y=new AbortController,l=await B5(L,W,y.signal),g=performance.now();if(typeof console<"u"&&console.log)console.log(`[WebP Worker] encode took ${(g-R).toFixed(2)}ms`);U.ok=!0,U.data=l,self.postMessage(U)}else U.error=`Unknown message type: ${J.type}`,self.postMessage(U)}catch(L){U.error=L instanceof Error?L.message:String(L),self.postMessage(U)}};export{B5 as webpEncodeClient};
|
|
26
|
-
|
|
27
|
-
//# debugId=47C2C4CA979BC5D164756E2164756E21
|