@squoosh-kit/webp 0.0.31 → 0.0.33
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 +2 -2
- package/dist/webp.worker.browser.mjs.map +3 -3
- package/dist/webp.worker.bun.js +2 -2
- package/dist/webp.worker.bun.js.map +3 -3
- package/dist/webp.worker.node.cjs +2 -2
- package/dist/webp.worker.node.cjs.map +3 -3
- package/dist/webp.worker.node.mjs +2 -2
- package/dist/webp.worker.node.mjs.map +3 -3
- package/package.json +3 -4
package/dist/bridge.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
export{
|
|
1
|
+
import{b as B}from"./chunk-szbj3b6y.js";import{d as z,e as y}from"./chunk-bhj61bkd.js";function R(){return typeof Bun<"u"}var P=0;async function T(G,K,Q,V,X){return new Promise((L,J)=>{let H=++P;if(V?.aborted){J(new DOMException("Aborted","AbortError"));return}let Y=(D)=>{let x=D.data;if(x.id!==H)return;if(_(),x.ok&&x.data!==void 0)L(x.data);else J(Error(x.error||"Unknown worker error"))},Z=(D)=>{_(),J(Error(`Worker error: ${D.message}`))},$=()=>{_(),J(new DOMException("Aborted","AbortError"))},_=()=>{G.removeEventListener("message",Y),G.removeEventListener("error",Z),V?.removeEventListener("abort",$)};G.addEventListener("message",Y),G.addEventListener("error",Z),V?.addEventListener("abort",$);let O={type:K,id:H,payload:Q};if(X&&X.length>0)G.postMessage(O,X);else G.postMessage(O)})}function q(G,K){if(K)try{return new Worker(K,{type:"module"})}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from custom URL ${K}: ${J}`)}let Q=G.endsWith(".js")?G:`${G}.js`,V={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},X=V[Q];if(!X)throw Error(`Unknown worker: ${Q}. Supported workers: ${Object.keys(V).join(", ")}`);try{if(typeof window<"u"){let Y=X.package.split("/")[1],Z=Q.replace(".js",".browser.mjs"),$=[`../../${Y}/dist/${Z}`,`../../../node_modules/@squoosh-kit/${Y}/dist/${Z}`,`../../../${Y}/dist/${Z}`],_=null;for(let O of $)try{let D=new URL(O,import.meta.url);return new Worker(D,{type:"module"})}catch(D){_=D instanceof Error?D:Error(String(D))}if(_)throw _;throw Error(`Could not resolve worker ${Q} using any available path strategy`)}let L=R()?".bun.js":".node.mjs",J=Q.replace(".js",""),H=X.package.includes("resize")?`../../resize/src/${J}.ts`:`../../webp/src/${J}.ts`;try{return new Worker(new URL(H,import.meta.url),{type:"module"})}catch{let Y=X.package.includes("resize")?`../../resize/dist/${J}.${L.slice(1)}`:`../../webp/dist/${J}.${L.slice(1)}`;try{return new Worker(new URL(Y,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Z=import.meta.resolve(`${X.package}/${X.specifier}`);return new Worker(Z,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${Q}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from ${Q}: ${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){let Q,V=1e4;if(typeof K==="number")V=K;else if(K)Q=K.customWorkerUrl,V=K.timeoutMs??1e4;return new Promise((X,L)=>{let J=setTimeout(()=>{L(Error(`Worker initialization timeout after ${V}ms. Worker file: ${G}`))},V),H;try{H=q(G,Q)}catch(_){clearTimeout(J),L(_);return}let Y=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),X(H)},Z=(_)=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},$=()=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker message error during initialization. Worker file: ${G}`))};H.addEventListener("message",Y),H.addEventListener("error",Z),H.addEventListener("messageerror",$),H.postMessage({type:"worker:ping"})})}class S{async encode(G,K,Q){let X=(await import("./webp.worker.browser.mjs")).webpEncodeClient;return X(G,K,Q)}async terminate(){}}class I{worker=null;workerReady=null;customWorkerUrl;constructor(G){this.customWorkerUrl=G}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",{customWorkerUrl:this.customWorkerUrl})}async encode(G,K,Q){let V=await this.getWorker();return B(G),T(V,"webp:encode",{image:G,options:K},Q)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function j(G,K){return G==="client"?new S:new I(K)}export{j as createBridge};
|
|
2
|
+
export{j as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=2ED822ABADC571AD64756E2164756E21
|
|
@@ -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 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 * Smart auto-detection: Automatically detects the correct worker base URL\n * using meta tags, import.meta.url inference, and HEAD request probing.\n */\n\nimport { isBun } from './env';\n\n// Cache for detected worker base URL\n// undefined = not yet detected, null = detection failed, string = detected base\nlet detectedWorkerBase: string | null | undefined;\nlet detectionPromise: Promise<string | null> | null = null;\n\n/**\n * Auto-detect the correct base URL for squoosh-kit worker files\n * Simple fallback strategies for non-Vite environments (Node.js, Bun, development)\n *\n * Note: For Vite production builds, use explicit ?url imports + configureResizeWorker()\n */\nasync function detectWorkerBase(): Promise<string | null> {\n if (detectedWorkerBase !== undefined) {\n return detectedWorkerBase;\n }\n\n if (detectionPromise) {\n return detectionPromise;\n }\n\n detectionPromise = (async () => {\n // Only run in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return (detectedWorkerBase = null);\n }\n\n // Strategy 1: Check for optional meta tag (for custom deployments)\n const metaTag = document.querySelector(\n 'meta[name=\"squoosh-base\"]'\n ) as HTMLMetaElement | null;\n if (metaTag?.content) {\n return (detectedWorkerBase = metaTag.content);\n }\n\n // Strategy 2: Infer from current script context (for npm-installed packages in development)\n try {\n const currentUrl = import.meta.url;\n const match = currentUrl.match(\n /^(.*\\/node_modules\\/@squoosh-kit\\/runtime\\/)/\n );\n if (match) {\n const base = match[1].replace('runtime/', '');\n return (detectedWorkerBase = base);\n }\n } catch {\n // Continue - detection failed\n }\n\n // No detection successful - will fall back to relative paths\n return (detectedWorkerBase = null);\n })();\n\n return detectionPromise;\n}\n\n/**\n * Manually trigger worker base URL detection\n * Useful for debugging or for apps that need explicit control over detection timing\n *\n * @returns Promise that resolves to the detected base URL (or null if detection fails)\n */\nexport async function initializeWorkerDetection(): Promise<string | null> {\n return detectWorkerBase();\n}\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Ensure base ends with / and doesn't have leading @\n const normalizedBase = base.replace(/\\/$/, '') + '/';\n return `${normalizedBase}@squoosh-kit/${packageName}/dist/${workerFile}`;\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 simple auto-detection (meta tag, import.meta.url)\n * with fallback to relative paths.\n *\n * For Vite production builds, use explicit ?url imports + configureResizeWorker().\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Required for Vite production builds using ?url imports.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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, try smart auto-detection first, then fall back to relative paths\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 // If detection has already been attempted, use cached result\n const cachedBase =\n detectedWorkerBase !== undefined ? detectedWorkerBase : null;\n if (cachedBase) {\n try {\n const detectedUrl = buildWorkerUrlFromBase(\n cachedBase,\n packageName,\n workerFile\n );\n return new Worker(detectedUrl, { type: 'module' });\n } catch {\n // Fall through to relative paths\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 * Automatically triggers simple auto-detection of worker base URLs in browser environments\n * (meta tag, import.meta.url inference). For Vite production, use explicit ?url imports.\n *\n * @param workerFilename - The name of the worker file\n * @param options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file. Required for Vite production.\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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 (async () => {\n try {\n // Await detection before creating the worker\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n // Silently fail detection - we'll fall back to relative paths\n await detectWorkerBase().catch(() => {});\n }\n\n const worker = createCodecWorker(workerFilename, customWorkerUrl);\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: ${\n event?.message || 'Unknown error'\n }. 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 } catch (error) {\n clearTimeout(timeout);\n reject(error);\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\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 * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Useful for Vite apps to pass explicitly resolved worker URLs.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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, customWorkerUrl);\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
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 private customWorkerUrl: string | undefined;\n\n constructor(customWorkerUrl?: string) {\n this.customWorkerUrl = customWorkerUrl;\n }\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 customWorkerUrl: this.customWorkerUrl,\n });\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 customWorkerUrl?: string\n): WebPBridge {\n return mode === 'client'\n ? new WebpClientBridge()\n : new WebpWorkerBridge(customWorkerUrl);\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": "6FAyBO,GAAS,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": "6FA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B,CAAkB,EAC7D,EACM,MACF,4DAA4D,GAC9D,CACF,GAGF,EAAO,iBAAiB,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,EAAO,iBAAiB,eAAgB,CAAkB,EAC1D,EAAO,YAAY,CAAE,KAAM,aAAc,CAAC,EAC3C,EC3NH,MAAM,CAAuC,MACrC,OAAM,CACV,EACA,EACA,EACqB,CAGrB,IAAM,GADS,KAAa,sCACI,iBAKhC,OAAO,EAAiB,EAAO,EAAS,CAAM,OAG1C,UAAS,EAAkB,EAGnC,CAEA,MAAM,CAAuC,CACnC,OAAwB,KACxB,YAAsC,KACtC,gBAER,WAAW,CAAC,EAA0B,CACpC,KAAK,gBAAkB,OAGX,UAAS,EAAoB,CACzC,GAAI,CAAC,KAAK,OAAQ,CAChB,GAAI,CAAC,KAAK,YACR,KAAK,YAAc,KAAK,aAAa,EAEvC,KAAK,OAAS,MAAM,KAAK,YAE3B,OAAO,KAAK,YAGA,aAAY,EAAoB,CAE5C,OAAO,EAAkB,cAAe,CACtC,gBAAiB,KAAK,eACxB,CAAC,OAGG,OAAM,CACV,EACA,EACA,EACqB,CACrB,IAAM,EAAS,MAAM,KAAK,UAAU,EAGpC,OADA,EAAmB,CAAK,EACjB,EAAW,EAAQ,cAAe,CAAE,QAAO,SAAQ,EAAG,CAAM,OAG/D,UAAS,EAAkB,CAC/B,GAAI,KAAK,OACP,KAAK,OAAO,UAAU,EACtB,KAAK,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAC1B,EACA,EACY,CACZ,OAAO,IAAS,SACZ,IAAI,EACJ,IAAI,EAAiB,CAAe",
|
|
11
|
+
"debugId": "2ED822ABADC571AD64756E2164756E21",
|
|
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 B}from"./chunk-q0apy7nk.js";import{d as z,e as y}from"./chunk-8y42hv65.js";function R(){return typeof Bun<"u"}var P=0;async function T(G,K,Q,V,X){return new Promise((L,J)=>{let H=++P;if(V?.aborted){J(new DOMException("Aborted","AbortError"));return}let Y=(D)=>{let x=D.data;if(x.id!==H)return;if(_(),x.ok&&x.data!==void 0)L(x.data);else J(Error(x.error||"Unknown worker error"))},Z=(D)=>{_(),J(Error(`Worker error: ${D.message}`))},$=()=>{_(),J(new DOMException("Aborted","AbortError"))},_=()=>{G.removeEventListener("message",Y),G.removeEventListener("error",Z),V?.removeEventListener("abort",$)};G.addEventListener("message",Y),G.addEventListener("error",Z),V?.addEventListener("abort",$);let O={type:K,id:H,payload:Q};if(X&&X.length>0)G.postMessage(O,X);else G.postMessage(O)})}function q(G,K){if(K)try{return new Worker(K,{type:"module"})}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from custom URL ${K}: ${J}`)}let Q=G.endsWith(".js")?G:`${G}.js`,V={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},X=V[Q];if(!X)throw Error(`Unknown worker: ${Q}. Supported workers: ${Object.keys(V).join(", ")}`);try{if(typeof window<"u"){let Y=X.package.split("/")[1],Z=Q.replace(".js",".browser.mjs"),$=[`../../${Y}/dist/${Z}`,`../../../node_modules/@squoosh-kit/${Y}/dist/${Z}`,`../../../${Y}/dist/${Z}`],_=null;for(let O of $)try{let D=new URL(O,import.meta.url);return new Worker(D,{type:"module"})}catch(D){_=D instanceof Error?D:Error(String(D))}if(_)throw _;throw Error(`Could not resolve worker ${Q} using any available path strategy`)}let L=R()?".bun.js":".node.mjs",J=Q.replace(".js",""),H=X.package.includes("resize")?`../../resize/src/${J}.ts`:`../../webp/src/${J}.ts`;try{return new Worker(new URL(H,import.meta.url),{type:"module"})}catch{let Y=X.package.includes("resize")?`../../resize/dist/${J}.${L.slice(1)}`:`../../webp/dist/${J}.${L.slice(1)}`;try{return new Worker(new URL(Y,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Z=import.meta.resolve(`${X.package}/${X.specifier}`);return new Worker(Z,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${Q}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from ${Q}: ${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){let Q,V=1e4;if(typeof K==="number")V=K;else if(K)Q=K.customWorkerUrl,V=K.timeoutMs??1e4;return new Promise((X,L)=>{let J=setTimeout(()=>{L(Error(`Worker initialization timeout after ${V}ms. Worker file: ${G}`))},V),H;try{H=q(G,Q)}catch(_){clearTimeout(J),L(_);return}let Y=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),X(H)},Z=(_)=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},$=()=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker message error during initialization. Worker file: ${G}`))};H.addEventListener("message",Y),H.addEventListener("error",Z),H.addEventListener("messageerror",$),H.postMessage({type:"worker:ping"})})}class S{async encode(G,K,Q){let X=(await import("./webp.worker.bun.js")).webpEncodeClient;return X(G,K,Q)}async terminate(){}}class I{worker=null;workerReady=null;customWorkerUrl;constructor(G){this.customWorkerUrl=G}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",{customWorkerUrl:this.customWorkerUrl})}async encode(G,K,Q){let V=await this.getWorker();return B(G),T(V,"webp:encode",{image:G,options:K},Q)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function j(G,K){return G==="client"?new S:new I(K)}export{j as createBridge};
|
|
3
|
+
export{j as a};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=FECAE6D70704A64864756E2164756E21
|
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 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 * Smart auto-detection: Automatically detects the correct worker base URL\n * using meta tags, import.meta.url inference, and HEAD request probing.\n */\n\nimport { isBun } from './env';\n\n// Cache for detected worker base URL\n// undefined = not yet detected, null = detection failed, string = detected base\nlet detectedWorkerBase: string | null | undefined;\nlet detectionPromise: Promise<string | null> | null = null;\n\n/**\n * Auto-detect the correct base URL for squoosh-kit worker files\n * Simple fallback strategies for non-Vite environments (Node.js, Bun, development)\n *\n * Note: For Vite production builds, use explicit ?url imports + configureResizeWorker()\n */\nasync function detectWorkerBase(): Promise<string | null> {\n if (detectedWorkerBase !== undefined) {\n return detectedWorkerBase;\n }\n\n if (detectionPromise) {\n return detectionPromise;\n }\n\n detectionPromise = (async () => {\n // Only run in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return (detectedWorkerBase = null);\n }\n\n // Strategy 1: Check for optional meta tag (for custom deployments)\n const metaTag = document.querySelector(\n 'meta[name=\"squoosh-base\"]'\n ) as HTMLMetaElement | null;\n if (metaTag?.content) {\n return (detectedWorkerBase = metaTag.content);\n }\n\n // Strategy 2: Infer from current script context (for npm-installed packages in development)\n try {\n const currentUrl = import.meta.url;\n const match = currentUrl.match(\n /^(.*\\/node_modules\\/@squoosh-kit\\/runtime\\/)/\n );\n if (match) {\n const base = match[1].replace('runtime/', '');\n return (detectedWorkerBase = base);\n }\n } catch {\n // Continue - detection failed\n }\n\n // No detection successful - will fall back to relative paths\n return (detectedWorkerBase = null);\n })();\n\n return detectionPromise;\n}\n\n/**\n * Manually trigger worker base URL detection\n * Useful for debugging or for apps that need explicit control over detection timing\n *\n * @returns Promise that resolves to the detected base URL (or null if detection fails)\n */\nexport async function initializeWorkerDetection(): Promise<string | null> {\n return detectWorkerBase();\n}\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Ensure base ends with / and doesn't have leading @\n const normalizedBase = base.replace(/\\/$/, '') + '/';\n return `${normalizedBase}@squoosh-kit/${packageName}/dist/${workerFile}`;\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 simple auto-detection (meta tag, import.meta.url)\n * with fallback to relative paths.\n *\n * For Vite production builds, use explicit ?url imports + configureResizeWorker().\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Required for Vite production builds using ?url imports.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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, try smart auto-detection first, then fall back to relative paths\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 // If detection has already been attempted, use cached result\n const cachedBase =\n detectedWorkerBase !== undefined ? detectedWorkerBase : null;\n if (cachedBase) {\n try {\n const detectedUrl = buildWorkerUrlFromBase(\n cachedBase,\n packageName,\n workerFile\n );\n return new Worker(detectedUrl, { type: 'module' });\n } catch {\n // Fall through to relative paths\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 * Automatically triggers simple auto-detection of worker base URLs in browser environments\n * (meta tag, import.meta.url inference). For Vite production, use explicit ?url imports.\n *\n * @param workerFilename - The name of the worker file\n * @param options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file. Required for Vite production.\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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 (async () => {\n try {\n // Await detection before creating the worker\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n // Silently fail detection - we'll fall back to relative paths\n await detectWorkerBase().catch(() => {});\n }\n\n const worker = createCodecWorker(workerFilename, customWorkerUrl);\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: ${\n event?.message || 'Unknown error'\n }. 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 } catch (error) {\n clearTimeout(timeout);\n reject(error);\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\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 * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Useful for Vite apps to pass explicitly resolved worker URLs.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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, customWorkerUrl);\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
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 private customWorkerUrl: string | undefined;\n\n constructor(customWorkerUrl?: string) {\n this.customWorkerUrl = customWorkerUrl;\n }\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 customWorkerUrl: this.customWorkerUrl,\n });\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 customWorkerUrl?: string\n): WebPBridge {\n return mode === 'client'\n ? new WebpClientBridge()\n : new WebpWorkerBridge(customWorkerUrl);\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": ";6FAyBO,GAAS,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,sBAA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,KAAK,eACxB,CAAC,OAGG,OAAM,CACV,EACA,EACA,EACqB,CACrB,IAAM,EAAS,MAAM,KAAK,UAAU,EAGpC,OADA,EAAmB,CAAK,EACjB,EAAW,EAAQ,cAAe,CAAE,QAAO,SAAQ,EAAG,CAAM,OAG/D,UAAS,EAAkB,CAC/B,GAAI,KAAK,OACP,KAAK,OAAO,UAAU,EACtB,KAAK,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAC1B,EACA,EACY,CACZ,OAAO,IAAS,SACZ,IAAI,EACJ,IAAI,EAAiB,CAAe",
|
|
11
|
+
"debugId": "FECAE6D70704A64864756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.node.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var U={};C(U,{createBridge:()=>N});module.exports=y(U);function R(){return typeof Bun<"u"}var P=0;async function T(G,K,Q,V,X){return new Promise((L,J)=>{let H=++P;if(V?.aborted){J(new DOMException("Aborted","AbortError"));return}let Y=(D)=>{let x=D.data;if(x.id!==H)return;if(_(),x.ok&&x.data!==void 0)L(x.data);else J(Error(x.error||"Unknown worker error"))},Z=(D)=>{_(),J(Error(`Worker error: ${D.message}`))},$=()=>{_(),J(new DOMException("Aborted","AbortError"))},_=()=>{G.removeEventListener("message",Y),G.removeEventListener("error",Z),V?.removeEventListener("abort",$)};G.addEventListener("message",Y),G.addEventListener("error",Z),V?.addEventListener("abort",$);let O={type:K,id:H,payload:Q};if(X&&X.length>0)G.postMessage(O,X);else G.postMessage(O)})}function q(G,K){if(K)try{return new Worker(K,{type:"module"})}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from custom URL ${K}: ${J}`)}let Q=G.endsWith(".js")?G:`${G}.js`,V={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},X=V[Q];if(!X)throw Error(`Unknown worker: ${Q}. Supported workers: ${Object.keys(V).join(", ")}`);try{if(typeof window<"u"){let Y=X.package.split("/")[1],Z=Q.replace(".js",".browser.mjs"),$=[`../../${Y}/dist/${Z}`,`../../../node_modules/@squoosh-kit/${Y}/dist/${Z}`,`../../../${Y}/dist/${Z}`],_=null;for(let O of $)try{let D=new URL(O,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");return new Worker(D,{type:"module"})}catch(D){_=D instanceof Error?D:Error(String(D))}if(_)throw _;throw Error(`Could not resolve worker ${Q} using any available path strategy`)}let L=R()?".bun.js":".node.mjs",J=Q.replace(".js",""),H=X.package.includes("resize")?`../../resize/src/${J}.ts`:`../../webp/src/${J}.ts`;try{return new Worker(new URL(H,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{let Y=X.package.includes("resize")?`../../resize/dist/${J}.${L.slice(1)}`:`../../webp/dist/${J}.${L.slice(1)}`;try{return new Worker(new URL(Y,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Z=import.meta.resolve(`${X.package}/${X.specifier}`);return new Worker(Z,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${Q}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from ${Q}: ${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){let Q,V=1e4;if(typeof K==="number")V=K;else if(K)Q=K.customWorkerUrl,V=K.timeoutMs??1e4;return new Promise((X,L)=>{let J=setTimeout(()=>{L(Error(`Worker initialization timeout after ${V}ms. Worker file: ${G}`))},V),H;try{H=q(G,Q)}catch(_){clearTimeout(J),L(_);return}let Y=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),X(H)},Z=(_)=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},$=()=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker message error during initialization. Worker file: ${G}`))};H.addEventListener("message",Y),H.addEventListener("error",Z),H.addEventListener("messageerror",$),H.postMessage({type:"worker:ping"})})}class S{async encode(G,K,Q){let X=(await import("./webp.worker.node.cjs")).webpEncodeClient;return X(G,K,Q)}async terminate(){}}class I{worker=null;workerReady=null;customWorkerUrl;constructor(G){this.customWorkerUrl=G}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",{customWorkerUrl:this.customWorkerUrl})}async encode(G,K,Q){let V=await this.getWorker();return B(G),T(V,"webp:encode",{image:G,options:K},Q)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function N(G,K){return G==="client"?new S:new I(K)}
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=56DA00D2A00D8BFE64756E2164756E21
|
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 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 * Smart auto-detection: Automatically detects the correct worker base URL\n * using meta tags, import.meta.url inference, and HEAD request probing.\n */\n\nimport { isBun } from './env';\n\n// Cache for detected worker base URL\n// undefined = not yet detected, null = detection failed, string = detected base\nlet detectedWorkerBase: string | null | undefined;\nlet detectionPromise: Promise<string | null> | null = null;\n\n/**\n * Auto-detect the correct base URL for squoosh-kit worker files\n * Simple fallback strategies for non-Vite environments (Node.js, Bun, development)\n *\n * Note: For Vite production builds, use explicit ?url imports + configureResizeWorker()\n */\nasync function detectWorkerBase(): Promise<string | null> {\n if (detectedWorkerBase !== undefined) {\n return detectedWorkerBase;\n }\n\n if (detectionPromise) {\n return detectionPromise;\n }\n\n detectionPromise = (async () => {\n // Only run in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return (detectedWorkerBase = null);\n }\n\n // Strategy 1: Check for optional meta tag (for custom deployments)\n const metaTag = document.querySelector(\n 'meta[name=\"squoosh-base\"]'\n ) as HTMLMetaElement | null;\n if (metaTag?.content) {\n return (detectedWorkerBase = metaTag.content);\n }\n\n // Strategy 2: Infer from current script context (for npm-installed packages in development)\n try {\n const currentUrl = import.meta.url;\n const match = currentUrl.match(\n /^(.*\\/node_modules\\/@squoosh-kit\\/runtime\\/)/\n );\n if (match) {\n const base = match[1].replace('runtime/', '');\n return (detectedWorkerBase = base);\n }\n } catch {\n // Continue - detection failed\n }\n\n // No detection successful - will fall back to relative paths\n return (detectedWorkerBase = null);\n })();\n\n return detectionPromise;\n}\n\n/**\n * Manually trigger worker base URL detection\n * Useful for debugging or for apps that need explicit control over detection timing\n *\n * @returns Promise that resolves to the detected base URL (or null if detection fails)\n */\nexport async function initializeWorkerDetection(): Promise<string | null> {\n return detectWorkerBase();\n}\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Ensure base ends with / and doesn't have leading @\n const normalizedBase = base.replace(/\\/$/, '') + '/';\n return `${normalizedBase}@squoosh-kit/${packageName}/dist/${workerFile}`;\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 simple auto-detection (meta tag, import.meta.url)\n * with fallback to relative paths.\n *\n * For Vite production builds, use explicit ?url imports + configureResizeWorker().\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Required for Vite production builds using ?url imports.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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, try smart auto-detection first, then fall back to relative paths\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 // If detection has already been attempted, use cached result\n const cachedBase =\n detectedWorkerBase !== undefined ? detectedWorkerBase : null;\n if (cachedBase) {\n try {\n const detectedUrl = buildWorkerUrlFromBase(\n cachedBase,\n packageName,\n workerFile\n );\n return new Worker(detectedUrl, { type: 'module' });\n } catch {\n // Fall through to relative paths\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 * Automatically triggers simple auto-detection of worker base URLs in browser environments\n * (meta tag, import.meta.url inference). For Vite production, use explicit ?url imports.\n *\n * @param workerFilename - The name of the worker file\n * @param options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file. Required for Vite production.\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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 (async () => {\n try {\n // Await detection before creating the worker\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n // Silently fail detection - we'll fall back to relative paths\n await detectWorkerBase().catch(() => {});\n }\n\n const worker = createCodecWorker(workerFilename, customWorkerUrl);\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: ${\n event?.message || 'Unknown error'\n }. 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 } catch (error) {\n clearTimeout(timeout);\n reject(error);\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\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 * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Useful for Vite apps to pass explicitly resolved worker URLs.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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, customWorkerUrl);\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
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 private customWorkerUrl: string | undefined;\n\n constructor(customWorkerUrl?: string) {\n this.customWorkerUrl = customWorkerUrl;\n }\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 customWorkerUrl: this.customWorkerUrl,\n });\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 customWorkerUrl?: string\n): WebPBridge {\n return mode === 'client'\n ? new WebpClientBridge()\n : new WebpWorkerBridge(customWorkerUrl);\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,EAEpC,OAAO,YAAY,CAAO,EAE7B,
|
|
11
|
-
"debugId": "
|
|
10
|
+
"mappings": "uDAyBO,SAAS,CAAK,EAAY,CAC/B,OAAO,OAAO,IAAQ,ICTxB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,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,EAAO,iBAAiB,eAAgB,CAAkB,EAC1D,EAAO,YAAY,CAAE,KAAM,aAAc,CAAC,EAC3C,EC3NH,MAAM,CAAuC,MACrC,OAAM,CACV,EACA,EACA,EACqB,CAGrB,IAAM,GADS,KAAa,mCACI,iBAKhC,OAAO,EAAiB,EAAO,EAAS,CAAM,OAG1C,UAAS,EAAkB,EAGnC,CAEA,MAAM,CAAuC,CACnC,OAAwB,KACxB,YAAsC,KACtC,gBAER,WAAW,CAAC,EAA0B,CACpC,KAAK,gBAAkB,OAGX,UAAS,EAAoB,CACzC,GAAI,CAAC,KAAK,OAAQ,CAChB,GAAI,CAAC,KAAK,YACR,KAAK,YAAc,KAAK,aAAa,EAEvC,KAAK,OAAS,MAAM,KAAK,YAE3B,OAAO,KAAK,YAGA,aAAY,EAAoB,CAE5C,OAAO,EAAkB,cAAe,CACtC,gBAAiB,KAAK,eACxB,CAAC,OAGG,OAAM,CACV,EACA,EACA,EACqB,CACrB,IAAM,EAAS,MAAM,KAAK,UAAU,EAGpC,OADA,EAAmB,CAAK,EACjB,EAAW,EAAQ,cAAe,CAAE,QAAO,SAAQ,EAAG,CAAM,OAG/D,UAAS,EAAkB,CAC/B,GAAI,KAAK,OACP,KAAK,OAAO,UAAU,EACtB,KAAK,OAAS,KACd,KAAK,YAAc,KAGzB,CAEO,SAAS,CAAY,CAC1B,EACA,EACY,CACZ,OAAO,IAAS,SACZ,IAAI,EACJ,IAAI,EAAiB,CAAe",
|
|
11
|
+
"debugId": "56DA00D2A00D8BFE64756E2164756E21",
|
|
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 B}from"./chunk-szbj3b6y.js";import{d as z,e as y}from"./chunk-c6cx0d7q.js";function R(){return typeof Bun<"u"}var P=0;async function T(G,K,Q,V,X){return new Promise((L,J)=>{let H=++P;if(V?.aborted){J(new DOMException("Aborted","AbortError"));return}let Y=(D)=>{let x=D.data;if(x.id!==H)return;if(_(),x.ok&&x.data!==void 0)L(x.data);else J(Error(x.error||"Unknown worker error"))},Z=(D)=>{_(),J(Error(`Worker error: ${D.message}`))},$=()=>{_(),J(new DOMException("Aborted","AbortError"))},_=()=>{G.removeEventListener("message",Y),G.removeEventListener("error",Z),V?.removeEventListener("abort",$)};G.addEventListener("message",Y),G.addEventListener("error",Z),V?.addEventListener("abort",$);let O={type:K,id:H,payload:Q};if(X&&X.length>0)G.postMessage(O,X);else G.postMessage(O)})}function q(G,K){if(K)try{return new Worker(K,{type:"module"})}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from custom URL ${K}: ${J}`)}let Q=G.endsWith(".js")?G:`${G}.js`,V={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},X=V[Q];if(!X)throw Error(`Unknown worker: ${Q}. Supported workers: ${Object.keys(V).join(", ")}`);try{if(typeof window<"u"){let Y=X.package.split("/")[1],Z=Q.replace(".js",".browser.mjs"),$=[`../../${Y}/dist/${Z}`,`../../../node_modules/@squoosh-kit/${Y}/dist/${Z}`,`../../../${Y}/dist/${Z}`],_=null;for(let O of $)try{let D=new URL(O,import.meta.url);return new Worker(D,{type:"module"})}catch(D){_=D instanceof Error?D:Error(String(D))}if(_)throw _;throw Error(`Could not resolve worker ${Q} using any available path strategy`)}let L=R()?".bun.js":".node.mjs",J=Q.replace(".js",""),H=X.package.includes("resize")?`../../resize/src/${J}.ts`:`../../webp/src/${J}.ts`;try{return new Worker(new URL(H,import.meta.url),{type:"module"})}catch{let Y=X.package.includes("resize")?`../../resize/dist/${J}.${L.slice(1)}`:`../../webp/dist/${J}.${L.slice(1)}`;try{return new Worker(new URL(Y,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Z=import.meta.resolve(`${X.package}/${X.specifier}`);return new Worker(Z,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${Q}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(L){let J=L instanceof Error?L.message:String(L);throw Error(`Failed to create worker from ${Q}: ${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){let Q,V=1e4;if(typeof K==="number")V=K;else if(K)Q=K.customWorkerUrl,V=K.timeoutMs??1e4;return new Promise((X,L)=>{let J=setTimeout(()=>{L(Error(`Worker initialization timeout after ${V}ms. Worker file: ${G}`))},V),H;try{H=q(G,Q)}catch(_){clearTimeout(J),L(_);return}let Y=(_)=>{if(_.data?.type==="worker:ready")clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),X(H)},Z=(_)=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker failed to start: ${_?.message||"Unknown error"}. Worker file: ${G}`))},$=()=>{clearTimeout(J),H.removeEventListener("message",Y),H.removeEventListener("error",Z),H.removeEventListener("messageerror",$),L(Error(`Worker message error during initialization. Worker file: ${G}`))};H.addEventListener("message",Y),H.addEventListener("error",Z),H.addEventListener("messageerror",$),H.postMessage({type:"worker:ping"})})}class S{async encode(G,K,Q){let X=(await import("./webp.worker.node.mjs")).webpEncodeClient;return X(G,K,Q)}async terminate(){}}class I{worker=null;workerReady=null;customWorkerUrl;constructor(G){this.customWorkerUrl=G}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",{customWorkerUrl:this.customWorkerUrl})}async encode(G,K,Q){let V=await this.getWorker();return B(G),T(V,"webp:encode",{image:G,options:K},Q)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function j(G,K){return G==="client"?new S:new I(K)}export{j as createBridge};
|
|
2
|
+
export{j as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=03BDEB7E8944975164756E2164756E21
|
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 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 * Smart auto-detection: Automatically detects the correct worker base URL\n * using meta tags, import.meta.url inference, and HEAD request probing.\n */\n\nimport { isBun } from './env';\n\n// Cache for detected worker base URL\n// undefined = not yet detected, null = detection failed, string = detected base\nlet detectedWorkerBase: string | null | undefined;\nlet detectionPromise: Promise<string | null> | null = null;\n\n/**\n * Auto-detect the correct base URL for squoosh-kit worker files\n * Simple fallback strategies for non-Vite environments (Node.js, Bun, development)\n *\n * Note: For Vite production builds, use explicit ?url imports + configureResizeWorker()\n */\nasync function detectWorkerBase(): Promise<string | null> {\n if (detectedWorkerBase !== undefined) {\n return detectedWorkerBase;\n }\n\n if (detectionPromise) {\n return detectionPromise;\n }\n\n detectionPromise = (async () => {\n // Only run in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return (detectedWorkerBase = null);\n }\n\n // Strategy 1: Check for optional meta tag (for custom deployments)\n const metaTag = document.querySelector(\n 'meta[name=\"squoosh-base\"]'\n ) as HTMLMetaElement | null;\n if (metaTag?.content) {\n return (detectedWorkerBase = metaTag.content);\n }\n\n // Strategy 2: Infer from current script context (for npm-installed packages in development)\n try {\n const currentUrl = import.meta.url;\n const match = currentUrl.match(\n /^(.*\\/node_modules\\/@squoosh-kit\\/runtime\\/)/\n );\n if (match) {\n const base = match[1].replace('runtime/', '');\n return (detectedWorkerBase = base);\n }\n } catch {\n // Continue - detection failed\n }\n\n // No detection successful - will fall back to relative paths\n return (detectedWorkerBase = null);\n })();\n\n return detectionPromise;\n}\n\n/**\n * Manually trigger worker base URL detection\n * Useful for debugging or for apps that need explicit control over detection timing\n *\n * @returns Promise that resolves to the detected base URL (or null if detection fails)\n */\nexport async function initializeWorkerDetection(): Promise<string | null> {\n return detectWorkerBase();\n}\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Ensure base ends with / and doesn't have leading @\n const normalizedBase = base.replace(/\\/$/, '') + '/';\n return `${normalizedBase}@squoosh-kit/${packageName}/dist/${workerFile}`;\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 simple auto-detection (meta tag, import.meta.url)\n * with fallback to relative paths.\n *\n * For Vite production builds, use explicit ?url imports + configureResizeWorker().\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Required for Vite production builds using ?url imports.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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, try smart auto-detection first, then fall back to relative paths\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 // If detection has already been attempted, use cached result\n const cachedBase =\n detectedWorkerBase !== undefined ? detectedWorkerBase : null;\n if (cachedBase) {\n try {\n const detectedUrl = buildWorkerUrlFromBase(\n cachedBase,\n packageName,\n workerFile\n );\n return new Worker(detectedUrl, { type: 'module' });\n } catch {\n // Fall through to relative paths\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 * Automatically triggers simple auto-detection of worker base URLs in browser environments\n * (meta tag, import.meta.url inference). For Vite production, use explicit ?url imports.\n *\n * @param workerFilename - The name of the worker file\n * @param options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file. Required for Vite production.\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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 (async () => {\n try {\n // Await detection before creating the worker\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n // Silently fail detection - we'll fall back to relative paths\n await detectWorkerBase().catch(() => {});\n }\n\n const worker = createCodecWorker(workerFilename, customWorkerUrl);\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: ${\n event?.message || 'Unknown error'\n }. 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 } catch (error) {\n clearTimeout(timeout);\n reject(error);\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\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 * @param customWorkerUrl - (Optional) Custom URL for the worker file. When provided, this takes precedence.\n * Useful for Vite apps to pass explicitly resolved worker URLs.\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n customWorkerUrl?: string\n): Worker {\n // If a custom worker URL is provided, use it directly\n if (customWorkerUrl) {\n try {\n return new Worker(customWorkerUrl, { type: 'module' });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from custom URL ${customWorkerUrl}: ${errorMessage}`\n );\n }\n }\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 return new Worker(workerUrl, {\n type: 'module',\n });\n } catch (error) {\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 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 options - Configuration options for worker creation\n * @param options.customWorkerUrl - (Optional) Custom URL for the worker file\n * @param options.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?: { customWorkerUrl?: string; timeoutMs?: number } | number\n): Promise<Worker> {\n // Support both old API (timeoutMs as number) and new API (options object)\n let customWorkerUrl: string | undefined;\n let timeoutMs: number = 10000;\n\n if (typeof options === 'number') {\n timeoutMs = options;\n } else if (options) {\n customWorkerUrl = options.customWorkerUrl;\n timeoutMs = options.timeoutMs ?? 10000;\n }\n\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, customWorkerUrl);\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
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 private customWorkerUrl: string | undefined;\n\n constructor(customWorkerUrl?: string) {\n this.customWorkerUrl = customWorkerUrl;\n }\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 customWorkerUrl: this.customWorkerUrl,\n });\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 customWorkerUrl?: string\n): WebPBridge {\n return mode === 'client'\n ? new WebpClientBridge()\n : new WebpWorkerBridge(customWorkerUrl);\n}\n"
|
|
9
9
|
],
|
|
10
|
-
"mappings": "6FAyBO,GAAS,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,EA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