@squoosh-kit/webp 0.0.5 → 0.0.8
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/bridge.browser.mjs +3 -3
- package/dist/bridge.browser.mjs.map +3 -3
- package/dist/bridge.bun.js +3 -3
- package/dist/bridge.bun.js.map +3 -3
- package/dist/bridge.node.cjs +2 -2
- package/dist/bridge.node.cjs.map +3 -3
- package/dist/bridge.node.mjs +3 -3
- package/dist/bridge.node.mjs.map +3 -3
- package/dist/webp.worker.browser.mjs.map +3 -3
- package/dist/webp.worker.bun.js.map +3 -3
- package/dist/webp.worker.d.ts.map +1 -1
- package/dist/webp.worker.node.cjs.map +3 -3
- package/dist/webp.worker.node.mjs.map +3 -3
- package/package.json +3 -3
package/dist/bridge.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
export{
|
|
1
|
+
import{b as P,c as B,d as E}from"./webp.worker.browser.mjs";function x(){return typeof Bun<"u"}var T=0;async function S(G,K,U,L,H){return new Promise((J,Q)=>{let X=++T;if(L?.aborted){Q(new DOMException("Aborted","AbortError"));return}let Z=(D)=>{let Y=D.data;if(Y.id!==X)return;if($(),Y.ok&&Y.data!==void 0)J(Y.data);else Q(Error(Y.error||"Unknown worker error"))},_=(D)=>{$(),Q(Error(`Worker error: ${D.message}`))},V=()=>{$(),Q(new DOMException("Aborted","AbortError"))},$=()=>{G.removeEventListener("message",Z),G.removeEventListener("error",_),L?.removeEventListener("abort",V)};G.addEventListener("message",Z),G.addEventListener("error",_),L?.addEventListener("abort",V);let O={type:K,id:X,payload:U};if(H&&H.length>0)G.postMessage(O,H);else G.postMessage(O)})}function q(G){let K=G.endsWith(".js")?G:`${G}.js`,U={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},L=U[K];if(!L)throw Error(`Unknown worker: ${K}. Supported workers: ${Object.keys(U).join(", ")}`);try{if(typeof window<"u"){let X=L.package.split("/")[1],Z=K.replace(".js",".browser.mjs"),_=`../../${X}/dist/${Z}`;return new Worker(new URL(_,import.meta.url),{type:"module"})}if(typeof import.meta.resolve==="function"){let X=import.meta.resolve(`${L.package}/${L.specifier}`);return new Worker(X,{type:"module"})}let H=x()?".bun.js":".node.mjs",J=K.replace(".js",""),Q=L.package.includes("resize")?`../../resize/dist/${J}.${H.slice(1)}`:`../../webp/dist/${J}.${H.slice(1)}`;return new Worker(new URL(Q,import.meta.url),{type:"module"})}catch(H){let J=H instanceof Error?H.message:String(H);throw Error(`Failed to create worker from ${K}: ${J}. 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 A(G,K=1e4){return new Promise((U,L)=>{let H=setTimeout(()=>{L(Error(`Worker initialization timeout after ${K}ms. Worker file: ${G}`))},K),J;try{J=q(G)}catch(X){clearTimeout(H),L(X);return}let Q=(X)=>{if(X.data?.type==="worker:ready")clearTimeout(H),J.removeEventListener("message",Q),U(J)};J.addEventListener("message",Q),J.postMessage({type:"worker:ping"})})}class I{async encode(G,K,U){return E(G,K,U)}async terminate(){}}class R{worker=null;workerReady=null;async getWorker(){if(!this.worker){if(!this.workerReady)this.workerReady=this.createWorker();this.worker=await this.workerReady}return this.worker}async createWorker(){return A("webp.worker")}async encode(G,K,U){let L=await this.getWorker();if(!G||typeof G!=="object")throw TypeError("image must be an object");let H=G;if(!H.data)throw TypeError("image.data is required");if(H.width===void 0||H.height===void 0)throw TypeError("image.width and image.height are required");let J={data:H.data,width:H.width,height:H.height};B(J);let Q=J.data.buffer;return P(Q),S(L,"webp:encode",{image:J,options:K},U,[Q])}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function y(G){return G==="client"?new I:new R}export{y as createBridge};
|
|
2
|
+
export{y as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=DC7407718501B5D064756E2164756E21
|
|
@@ -4,10 +4,10 @@
|
|
|
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
|
|
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 // Both packages are siblings in node_modules, so ../../resize or ../../webp works\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 const relPath = `../../${packageName}/dist/${workerFile}`;\n\n return new Worker(new URL(relPath, import.meta.url), {\n type: 'module',\n });\n }\n\n // Node.js/Bun: use import.meta.resolve if available\n if (typeof import.meta.resolve === 'function') {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n }\n\n // Fallback for Bun: use relative path from this file's location\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const relPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n\n return new Worker(new URL(relPath, import.meta.url), { type: 'module' });\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 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);\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 resolve(worker);\n }\n };\n\n worker.addEventListener('message', handleMessage);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
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 { validateArrayBuffer, validateImageInput } from '@squoosh-kit/runtime';\nimport { webpEncodeClient } from './webp.worker.js';\nimport type { WebpOptions } from './types.js';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: WebpOptions,\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.worker) {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n this.worker = await this.workerReady;\n }\n return this.worker;\n }\n\n private async createWorker(): Promise<Worker> {\n // Use the centralized worker helper for robust path resolution\n return createReadyWorker('webp.worker');\n }\n\n async encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n // Validate and normalize image - ensure all required properties exist\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageRecord = image as Record<string, unknown>;\n if (!imageRecord.data) {\n throw new TypeError('image.data is required');\n }\n if (imageRecord.width === undefined || imageRecord.height === undefined) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const normalizedImage: ImageInput = {\n data: imageRecord.data as Uint8Array | Uint8ClampedArray,\n width: imageRecord.width as number,\n height: imageRecord.height as number,\n };\n\n validateImageInput(normalizedImage);\n const buffer = normalizedImage.data.buffer;\n validateArrayBuffer(buffer);\n return callWorker(\n worker,\n 'webp:encode',\n { image: normalizedImage, options },\n signal,\n [buffer]\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(mode: 'worker' | 'client'): WebPBridge {\n return mode === 'client' ? new WebpClientBridge() : new WebpWorkerBridge();\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": "4DAyBO,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/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cACA,CAAE,MAAO,EAAiB,SAAQ,EAClC,EACA,CAAC,CAAM,CACT,OAGI,UAAS,EAAkB,CAC/B,GAAI,KAAK,OACP,KAAK,OAAO,UAAU,EACtB,KAAK,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAAC,EAAuC,CAClE,OAAO,IAAS,SAAW,IAAI,EAAqB,IAAI",
|
|
11
|
+
"debugId": "DC7407718501B5D064756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.bun.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{b as
|
|
3
|
-
export{
|
|
2
|
+
import{b as P,c as B,d as E}from"./webp.worker.bun.js";function x(){return typeof Bun<"u"}var T=0;async function S(G,K,U,L,H){return new Promise((J,Q)=>{let X=++T;if(L?.aborted){Q(new DOMException("Aborted","AbortError"));return}let Z=(D)=>{let Y=D.data;if(Y.id!==X)return;if($(),Y.ok&&Y.data!==void 0)J(Y.data);else Q(Error(Y.error||"Unknown worker error"))},_=(D)=>{$(),Q(Error(`Worker error: ${D.message}`))},V=()=>{$(),Q(new DOMException("Aborted","AbortError"))},$=()=>{G.removeEventListener("message",Z),G.removeEventListener("error",_),L?.removeEventListener("abort",V)};G.addEventListener("message",Z),G.addEventListener("error",_),L?.addEventListener("abort",V);let O={type:K,id:X,payload:U};if(H&&H.length>0)G.postMessage(O,H);else G.postMessage(O)})}function q(G){let K=G.endsWith(".js")?G:`${G}.js`,U={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},L=U[K];if(!L)throw Error(`Unknown worker: ${K}. Supported workers: ${Object.keys(U).join(", ")}`);try{if(typeof window<"u"){let X=L.package.split("/")[1],Z=K.replace(".js",".browser.mjs"),_=`../../${X}/dist/${Z}`;return new Worker(new URL(_,import.meta.url),{type:"module"})}if(typeof import.meta.resolve==="function"){let X=import.meta.resolve(`${L.package}/${L.specifier}`);return new Worker(X,{type:"module"})}let H=x()?".bun.js":".node.mjs",J=K.replace(".js",""),Q=L.package.includes("resize")?`../../resize/dist/${J}.${H.slice(1)}`:`../../webp/dist/${J}.${H.slice(1)}`;return new Worker(new URL(Q,import.meta.url),{type:"module"})}catch(H){let J=H instanceof Error?H.message:String(H);throw Error(`Failed to create worker from ${K}: ${J}. 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 A(G,K=1e4){return new Promise((U,L)=>{let H=setTimeout(()=>{L(Error(`Worker initialization timeout after ${K}ms. Worker file: ${G}`))},K),J;try{J=q(G)}catch(X){clearTimeout(H),L(X);return}let Q=(X)=>{if(X.data?.type==="worker:ready")clearTimeout(H),J.removeEventListener("message",Q),U(J)};J.addEventListener("message",Q),J.postMessage({type:"worker:ping"})})}class I{async encode(G,K,U){return E(G,K,U)}async terminate(){}}class R{worker=null;workerReady=null;async getWorker(){if(!this.worker){if(!this.workerReady)this.workerReady=this.createWorker();this.worker=await this.workerReady}return this.worker}async createWorker(){return A("webp.worker")}async encode(G,K,U){let L=await this.getWorker();if(!G||typeof G!=="object")throw TypeError("image must be an object");let H=G;if(!H.data)throw TypeError("image.data is required");if(H.width===void 0||H.height===void 0)throw TypeError("image.width and image.height are required");let J={data:H.data,width:H.width,height:H.height};B(J);let Q=J.data.buffer;return P(Q),S(L,"webp:encode",{image:J,options:K},U,[Q])}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function y(G){return G==="client"?new I:new R}export{y as createBridge};
|
|
3
|
+
export{y as a};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=7850AAC6E189F43E64756E2164756E21
|
package/dist/bridge.bun.js.map
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
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
|
|
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 // Both packages are siblings in node_modules, so ../../resize or ../../webp works\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 const relPath = `../../${packageName}/dist/${workerFile}`;\n\n return new Worker(new URL(relPath, import.meta.url), {\n type: 'module',\n });\n }\n\n // Node.js/Bun: use import.meta.resolve if available\n if (typeof import.meta.resolve === 'function') {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n }\n\n // Fallback for Bun: use relative path from this file's location\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const relPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n\n return new Worker(new URL(relPath, import.meta.url), { type: 'module' });\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 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);\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 resolve(worker);\n }\n };\n\n worker.addEventListener('message', handleMessage);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
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 { validateArrayBuffer, validateImageInput } from '@squoosh-kit/runtime';\nimport { webpEncodeClient } from './webp.worker.js';\nimport type { WebpOptions } from './types.js';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: WebpOptions,\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.worker) {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n this.worker = await this.workerReady;\n }\n return this.worker;\n }\n\n private async createWorker(): Promise<Worker> {\n // Use the centralized worker helper for robust path resolution\n return createReadyWorker('webp.worker');\n }\n\n async encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n // Validate and normalize image - ensure all required properties exist\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageRecord = image as Record<string, unknown>;\n if (!imageRecord.data) {\n throw new TypeError('image.data is required');\n }\n if (imageRecord.width === undefined || imageRecord.height === undefined) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const normalizedImage: ImageInput = {\n data: imageRecord.data as Uint8Array | Uint8ClampedArray,\n width: imageRecord.width as number,\n height: imageRecord.height as number,\n };\n\n validateImageInput(normalizedImage);\n const buffer = normalizedImage.data.buffer;\n validateArrayBuffer(buffer);\n return callWorker(\n worker,\n 'webp:encode',\n { image: normalizedImage, options },\n signal,\n [buffer]\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(mode: 'worker' | 'client'): WebPBridge {\n return mode === 'client' ? new WebpClientBridge() : new WebpWorkerBridge();\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": ";uDAyBO,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,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K,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAAC,EAAuC,CAClE,OAAO,IAAS,SAAW,IAAI,EAAqB,IAAI",
|
|
11
|
+
"debugId": "7850AAC6E189F43E64756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.node.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F={};z(F,{createBridge:()=>W});module.exports=N(F);function x(){return typeof Bun<"u"}var T=0;async function S(G,K,U,L,H){return new Promise((J,Q)=>{let X=++T;if(L?.aborted){Q(new DOMException("Aborted","AbortError"));return}let Z=(D)=>{let Y=D.data;if(Y.id!==X)return;if($(),Y.ok&&Y.data!==void 0)J(Y.data);else Q(Error(Y.error||"Unknown worker error"))},_=(D)=>{$(),Q(Error(`Worker error: ${D.message}`))},V=()=>{$(),Q(new DOMException("Aborted","AbortError"))},$=()=>{G.removeEventListener("message",Z),G.removeEventListener("error",_),L?.removeEventListener("abort",V)};G.addEventListener("message",Z),G.addEventListener("error",_),L?.addEventListener("abort",V);let O={type:K,id:X,payload:U};if(H&&H.length>0)G.postMessage(O,H);else G.postMessage(O)})}function q(G){let K=G.endsWith(".js")?G:`${G}.js`,U={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},L=U[K];if(!L)throw Error(`Unknown worker: ${K}. Supported workers: ${Object.keys(U).join(", ")}`);try{if(typeof window<"u"){let X=L.package.split("/")[1],Z=K.replace(".js",".browser.mjs"),_=`../../${X}/dist/${Z}`;return new Worker(new URL(_,"file:///home/bnowak/repos/squoosh-lite/packages/runtime/src/worker-helper.ts"),{type:"module"})}if(typeof import.meta.resolve==="function"){let X=import.meta.resolve(`${L.package}/${L.specifier}`);return new Worker(X,{type:"module"})}let H=x()?".bun.js":".node.mjs",J=K.replace(".js",""),Q=L.package.includes("resize")?`../../resize/dist/${J}.${H.slice(1)}`:`../../webp/dist/${J}.${H.slice(1)}`;return new Worker(new URL(Q,"file:///home/bnowak/repos/squoosh-lite/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch(H){let J=H instanceof Error?H.message:String(H);throw Error(`Failed to create worker from ${K}: ${J}. 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 A(G,K=1e4){return new Promise((U,L)=>{let H=setTimeout(()=>{L(Error(`Worker initialization timeout after ${K}ms. Worker file: ${G}`))},K),J;try{J=q(G)}catch(X){clearTimeout(H),L(X);return}let Q=(X)=>{if(X.data?.type==="worker:ready")clearTimeout(H),J.removeEventListener("message",Q),U(J)};J.addEventListener("message",Q),J.postMessage({type:"worker:ping"})})}class I{async encode(G,K,U){return E(G,K,U)}async terminate(){}}class R{worker=null;workerReady=null;async getWorker(){if(!this.worker){if(!this.workerReady)this.workerReady=this.createWorker();this.worker=await this.workerReady}return this.worker}async createWorker(){return A("webp.worker")}async encode(G,K,U){let L=await this.getWorker();if(!G||typeof G!=="object")throw TypeError("image must be an object");let H=G;if(!H.data)throw TypeError("image.data is required");if(H.width===void 0||H.height===void 0)throw TypeError("image.width and image.height are required");let J={data:H.data,width:H.width,height:H.height};B(J);let Q=J.data.buffer;return P(Q),S(L,"webp:encode",{image:J,options:K},U,[Q])}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function W(G){return G==="client"?new I:new R}
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=69A04E3654C4FF0964756E2164756E21
|
package/dist/bridge.node.cjs.map
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
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
|
|
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 // Both packages are siblings in node_modules, so ../../resize or ../../webp works\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 const relPath = `../../${packageName}/dist/${workerFile}`;\n\n return new Worker(new URL(relPath, import.meta.url), {\n type: 'module',\n });\n }\n\n // Node.js/Bun: use import.meta.resolve if available\n if (typeof import.meta.resolve === 'function') {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n }\n\n // Fallback for Bun: use relative path from this file's location\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const relPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n\n return new Worker(new URL(relPath, import.meta.url), { type: 'module' });\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 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);\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 resolve(worker);\n }\n };\n\n worker.addEventListener('message', handleMessage);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
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 { validateArrayBuffer, validateImageInput } from '@squoosh-kit/runtime';\nimport { webpEncodeClient } from './webp.worker.js';\nimport type { WebpOptions } from './types.js';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: WebpOptions,\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.worker) {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n this.worker = await this.workerReady;\n }\n return this.worker;\n }\n\n private async createWorker(): Promise<Worker> {\n // Use the centralized worker helper for robust path resolution\n return createReadyWorker('webp.worker');\n }\n\n async encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n // Validate and normalize image - ensure all required properties exist\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageRecord = image as Record<string, unknown>;\n if (!imageRecord.data) {\n throw new TypeError('image.data is required');\n }\n if (imageRecord.width === undefined || imageRecord.height === undefined) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const normalizedImage: ImageInput = {\n data: imageRecord.data as Uint8Array | Uint8ClampedArray,\n width: imageRecord.width as number,\n height: imageRecord.height as number,\n };\n\n validateImageInput(normalizedImage);\n const buffer = normalizedImage.data.buffer;\n validateArrayBuffer(buffer);\n return callWorker(\n worker,\n 'webp:encode',\n { image: normalizedImage, options },\n signal,\n [buffer]\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(mode: 'worker' | 'client'): WebPBridge {\n return mode === 'client' ? new WebpClientBridge() : new WebpWorkerBridge();\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": "uDAyBO,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,EAEp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debugId": "69A04E3654C4FF0964756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.node.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
export{
|
|
1
|
+
import{b as P,c as B,d as E}from"./webp.worker.node.mjs";function x(){return typeof Bun<"u"}var T=0;async function S(G,K,U,L,H){return new Promise((J,Q)=>{let X=++T;if(L?.aborted){Q(new DOMException("Aborted","AbortError"));return}let Z=(D)=>{let Y=D.data;if(Y.id!==X)return;if($(),Y.ok&&Y.data!==void 0)J(Y.data);else Q(Error(Y.error||"Unknown worker error"))},_=(D)=>{$(),Q(Error(`Worker error: ${D.message}`))},V=()=>{$(),Q(new DOMException("Aborted","AbortError"))},$=()=>{G.removeEventListener("message",Z),G.removeEventListener("error",_),L?.removeEventListener("abort",V)};G.addEventListener("message",Z),G.addEventListener("error",_),L?.addEventListener("abort",V);let O={type:K,id:X,payload:U};if(H&&H.length>0)G.postMessage(O,H);else G.postMessage(O)})}function q(G){let K=G.endsWith(".js")?G:`${G}.js`,U={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},L=U[K];if(!L)throw Error(`Unknown worker: ${K}. Supported workers: ${Object.keys(U).join(", ")}`);try{if(typeof window<"u"){let X=L.package.split("/")[1],Z=K.replace(".js",".browser.mjs"),_=`../../${X}/dist/${Z}`;return new Worker(new URL(_,import.meta.url),{type:"module"})}if(typeof import.meta.resolve==="function"){let X=import.meta.resolve(`${L.package}/${L.specifier}`);return new Worker(X,{type:"module"})}let H=x()?".bun.js":".node.mjs",J=K.replace(".js",""),Q=L.package.includes("resize")?`../../resize/dist/${J}.${H.slice(1)}`:`../../webp/dist/${J}.${H.slice(1)}`;return new Worker(new URL(Q,import.meta.url),{type:"module"})}catch(H){let J=H instanceof Error?H.message:String(H);throw Error(`Failed to create worker from ${K}: ${J}. 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 A(G,K=1e4){return new Promise((U,L)=>{let H=setTimeout(()=>{L(Error(`Worker initialization timeout after ${K}ms. Worker file: ${G}`))},K),J;try{J=q(G)}catch(X){clearTimeout(H),L(X);return}let Q=(X)=>{if(X.data?.type==="worker:ready")clearTimeout(H),J.removeEventListener("message",Q),U(J)};J.addEventListener("message",Q),J.postMessage({type:"worker:ping"})})}class I{async encode(G,K,U){return E(G,K,U)}async terminate(){}}class R{worker=null;workerReady=null;async getWorker(){if(!this.worker){if(!this.workerReady)this.workerReady=this.createWorker();this.worker=await this.workerReady}return this.worker}async createWorker(){return A("webp.worker")}async encode(G,K,U){let L=await this.getWorker();if(!G||typeof G!=="object")throw TypeError("image must be an object");let H=G;if(!H.data)throw TypeError("image.data is required");if(H.width===void 0||H.height===void 0)throw TypeError("image.width and image.height are required");let J={data:H.data,width:H.width,height:H.height};B(J);let Q=J.data.buffer;return P(Q),S(L,"webp:encode",{image:J,options:K},U,[Q])}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function y(G){return G==="client"?new I:new R}export{y as createBridge};
|
|
2
|
+
export{y as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=788E42D0A817EC5A64756E2164756E21
|
package/dist/bridge.node.mjs.map
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
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
|
|
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 // Both packages are siblings in node_modules, so ../../resize or ../../webp works\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 const relPath = `../../${packageName}/dist/${workerFile}`;\n\n return new Worker(new URL(relPath, import.meta.url), {\n type: 'module',\n });\n }\n\n // Node.js/Bun: use import.meta.resolve if available\n if (typeof import.meta.resolve === 'function') {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n }\n\n // Fallback for Bun: use relative path from this file's location\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const relPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n\n return new Worker(new URL(relPath, import.meta.url), { type: 'module' });\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 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);\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 resolve(worker);\n }\n };\n\n worker.addEventListener('message', handleMessage);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
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 { validateArrayBuffer, validateImageInput } from '@squoosh-kit/runtime';\nimport { webpEncodeClient } from './webp.worker.js';\nimport type { WebpOptions } from './types.js';\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: WebpOptions,\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.worker) {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n this.worker = await this.workerReady;\n }\n return this.worker;\n }\n\n private async createWorker(): Promise<Worker> {\n // Use the centralized worker helper for robust path resolution\n return createReadyWorker('webp.worker');\n }\n\n async encode(\n image: ImageInput,\n options?: WebpOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n // Validate and normalize image - ensure all required properties exist\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageRecord = image as Record<string, unknown>;\n if (!imageRecord.data) {\n throw new TypeError('image.data is required');\n }\n if (imageRecord.width === undefined || imageRecord.height === undefined) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const normalizedImage: ImageInput = {\n data: imageRecord.data as Uint8Array | Uint8ClampedArray,\n width: imageRecord.width as number,\n height: imageRecord.height as number,\n };\n\n validateImageInput(normalizedImage);\n const buffer = normalizedImage.data.buffer;\n validateArrayBuffer(buffer);\n return callWorker(\n worker,\n 'webp:encode',\n { image: normalizedImage, options },\n signal,\n [buffer]\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(mode: 'worker' | 'client'): WebPBridge {\n return mode === 'client' ? new WebpClientBridge() : new WebpWorkerBridge();\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": "yDAyBO,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,OAAO,YAAY,CAAO,EAE7B,
|
|
11
|
-
"debugId": "
|
|
10
|
+
"mappings": "yDAyBO,SAAS,CAAK,EAAY,CAC/B,OAAO,OAAO,IAAQ,ICTxB,IAAI,EAAY,EAYhB,eAA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