@squoosh-kit/webp 0.0.28 → 0.0.29
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 +2 -2
- package/dist/bridge.browser.mjs.map +3 -3
- package/dist/bridge.bun.js +2 -2
- 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 +2 -2
- package/dist/bridge.node.mjs.map +3 -3
- package/package.json +2 -2
package/dist/bridge.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as z}from"./chunk-szbj3b6y.js";import{d as B,e as
|
|
1
|
+
import{b as z}from"./chunk-szbj3b6y.js";import{d as B,e as N}from"./chunk-bhj61bkd.js";function S(){return typeof Bun<"u"}var y=0;async function T(G,V,J,Q,Y){return new Promise((Z,X)=>{let L=++y;if(Q?.aborted){X(new DOMException("Aborted","AbortError"));return}let _=(A)=>{let D=A.data;if(D.id!==L)return;if(x(),D.ok&&D.data!==void 0)Z(D.data);else X(Error(D.error||"Unknown worker error"))},$=(A)=>{x(),X(Error(`Worker error: ${A.message}`))},O=()=>{x(),X(new DOMException("Aborted","AbortError"))},x=()=>{G.removeEventListener("message",_),G.removeEventListener("error",$),Q?.removeEventListener("abort",O)};G.addEventListener("message",_),G.addEventListener("error",$),Q?.addEventListener("abort",O);let K={type:V,id:L,payload:J};if(Y&&Y.length>0)G.postMessage(K,Y);else G.postMessage(K)})}var H,R=null;async function E(){if(H!==void 0)return H;if(R)return R;return R=(async()=>{if(typeof window>"u"||typeof document>"u")return H=null;let G=document.querySelector('meta[name="squoosh-base"]');if(G?.content)return H=G.content;try{let J=Array.from(document.scripts),Q=[{name:"resize",regex:/resize\.worker\.browser.*\.js$/},{name:"webp",regex:/webp\.worker\.browser.*\.js$/}];for(let{name:Y,regex:Z}of Q){let X=J.find((L)=>Z.test(L.src));if(X){let L=X.src;return j(Y,`${Y}.worker.browser.mjs`,L),H=L.substring(0,L.lastIndexOf("/")+1)}}}catch{}try{let Q=import.meta.url.match(/^(.*\/node_modules\/@squoosh-kit\/runtime\/)/);if(Q)return H=Q[1].replace("runtime/","")}catch{}let V=["/node_modules/@squoosh-kit/","/@squoosh-kit/",window.location.origin+"/node_modules/@squoosh-kit/"];for(let J of V)try{let Q=`${J}resize/dist/resize.worker.browser.mjs`;return await fetch(Q,{method:"HEAD",mode:"no-cors"}),H=J}catch{}return H=null})(),R}var I={};function v(G,V,J){let Q=`${V}:${J}`;if(I[Q])return I[Q];return`${G.replace(/\/$/,"")+"/"}@squoosh-kit/${V}/dist/${J}`}function j(G,V,J){let Q=`${G}:${V}`;I[Q]=J}function M(G,V){if(V)try{return new Worker(V,{type:"module"})}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from custom URL ${V}: ${X}`)}let J=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},Y=Q[J];if(!Y)throw Error(`Unknown worker: ${J}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let _=Y.package.split("/")[1],$=J.replace(".js",".browser.mjs"),O=H!==void 0?H:null;if(O)try{let A=v(O,_,$);return new Worker(A,{type:"module"})}catch{}let x=[`../../${_}/dist/${$}`,`../../../node_modules/@squoosh-kit/${_}/dist/${$}`,`../../../${_}/dist/${$}`],K=null;for(let A of x)try{let D=new URL(A,import.meta.url);return new Worker(D,{type:"module"})}catch(D){K=D instanceof Error?D:Error(String(D))}if(K)throw K;throw Error(`Could not resolve worker ${J} using any available path strategy`)}let Z=S()?".bun.js":".node.mjs",X=J.replace(".js",""),L=Y.package.includes("resize")?`../../resize/src/${X}.ts`:`../../webp/src/${X}.ts`;try{return new Worker(new URL(L,import.meta.url),{type:"module"})}catch{let _=Y.package.includes("resize")?`../../resize/dist/${X}.${Z.slice(1)}`:`../../webp/dist/${X}.${Z.slice(1)}`;try{return new Worker(new URL(_,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let $=import.meta.resolve(`${Y.package}/${Y.specifier}`);return new Worker($,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${J}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from ${J}: ${X}. 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 q(G,V){let J,Q=1e4;if(typeof V==="number")Q=V;else if(V)J=V.customWorkerUrl,Q=V.timeoutMs??1e4;return new Promise((Y,Z)=>{let X=setTimeout(()=>{Z(Error(`Worker initialization timeout after ${Q}ms. Worker file: ${G}`))},Q);(async()=>{try{if(typeof window<"u"&&H===void 0)await E().catch(()=>{});let L=M(G,J),_=(x)=>{if(x.data?.type==="worker:ready")clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Y(L)},$=(x)=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker failed to start: ${x?.message||"Unknown error"}. Worker file: ${G}`))},O=()=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker message error during initialization. Worker file: ${G}`))};L.addEventListener("message",_),L.addEventListener("error",$),L.addEventListener("messageerror",O),L.postMessage({type:"worker:ping"})}catch(L){clearTimeout(X),Z(L)}})()})}class C{async encode(G,V,J){let Y=(await import("./webp.worker.browser.mjs")).webpEncodeClient;return Y(G,V,J)}async terminate(){}}class P{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 q("webp.worker",{customWorkerUrl:this.customWorkerUrl})}async encode(G,V,J){let Q=await this.getWorker();return z(G),T(Q,"webp:encode",{image:G,options:V},J)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function g(G,V){return G==="client"?new C:new P(V)}export{g as createBridge};
|
|
2
2
|
export{g as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=6B3DC7BD931204B964756E2164756E21
|
|
@@ -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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Fetch the current HTML document to find script references\n const html = await fetch(window.location.href).then((r) => r.text());\n\n // Look for both resize and webp worker scripts in assets\n const workerPatterns = [\n {\n regex:\n /[\"']([^\"']*assets[^\"']*resize\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'resize',\n },\n {\n regex: /[\"']([^\"']*assets[^\"']*webp\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'webp',\n },\n ];\n\n for (const { regex, package: packageName } of workerPatterns) {\n const match = html.match(regex);\n if (match?.[1]) {\n const workerPath = match[1];\n // Cache the full hashed URL\n cacheHashedWorkerUrl(\n packageName,\n `${packageName}.worker.browser.mjs`,\n workerPath\n );\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 // Kick off auto-detection in the background (doesn't block)\n // This will cache the result for subsequent calls\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n detectWorkerBase().catch(() => {\n // Silently fail detection - we'll fall back to relative paths\n });\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",
|
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Look for worker scripts in the live DOM, which is more reliable for SPAs\n const scripts = Array.from(document.scripts);\n const workerPatterns = [\n {\n name: 'resize',\n regex: /resize\\.worker\\.browser.*\\.js$/,\n },\n {\n name: 'webp',\n regex: /webp\\.worker\\.browser.*\\.js$/,\n },\n ];\n\n for (const { name, regex } of workerPatterns) {\n const script = scripts.find((s) => regex.test(s.src));\n if (script) {\n const workerPath = script.src; // This will be the full, absolute URL\n // Cache the full hashed URL\n cacheHashedWorkerUrl(name, `${name}.worker.browser.mjs`, workerPath);\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 (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",
|
|
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,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,IAAI,EACJ,IAAI,EAAiB,CAAe",
|
|
11
|
+
"debugId": "6B3DC7BD931204B964756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.bun.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{b as z}from"./chunk-q0apy7nk.js";import{d as B,e as
|
|
2
|
+
import{b as z}from"./chunk-q0apy7nk.js";import{d as B,e as N}from"./chunk-8y42hv65.js";function S(){return typeof Bun<"u"}var y=0;async function T(G,V,J,Q,Y){return new Promise((Z,X)=>{let L=++y;if(Q?.aborted){X(new DOMException("Aborted","AbortError"));return}let _=(A)=>{let D=A.data;if(D.id!==L)return;if(x(),D.ok&&D.data!==void 0)Z(D.data);else X(Error(D.error||"Unknown worker error"))},$=(A)=>{x(),X(Error(`Worker error: ${A.message}`))},O=()=>{x(),X(new DOMException("Aborted","AbortError"))},x=()=>{G.removeEventListener("message",_),G.removeEventListener("error",$),Q?.removeEventListener("abort",O)};G.addEventListener("message",_),G.addEventListener("error",$),Q?.addEventListener("abort",O);let K={type:V,id:L,payload:J};if(Y&&Y.length>0)G.postMessage(K,Y);else G.postMessage(K)})}var H,R=null;async function E(){if(H!==void 0)return H;if(R)return R;return R=(async()=>{if(typeof window>"u"||typeof document>"u")return H=null;let G=document.querySelector('meta[name="squoosh-base"]');if(G?.content)return H=G.content;try{let J=Array.from(document.scripts),Q=[{name:"resize",regex:/resize\.worker\.browser.*\.js$/},{name:"webp",regex:/webp\.worker\.browser.*\.js$/}];for(let{name:Y,regex:Z}of Q){let X=J.find((L)=>Z.test(L.src));if(X){let L=X.src;return j(Y,`${Y}.worker.browser.mjs`,L),H=L.substring(0,L.lastIndexOf("/")+1)}}}catch{}try{let Q=import.meta.url.match(/^(.*\/node_modules\/@squoosh-kit\/runtime\/)/);if(Q)return H=Q[1].replace("runtime/","")}catch{}let V=["/node_modules/@squoosh-kit/","/@squoosh-kit/",window.location.origin+"/node_modules/@squoosh-kit/"];for(let J of V)try{let Q=`${J}resize/dist/resize.worker.browser.mjs`;return await fetch(Q,{method:"HEAD",mode:"no-cors"}),H=J}catch{}return H=null})(),R}var I={};function v(G,V,J){let Q=`${V}:${J}`;if(I[Q])return I[Q];return`${G.replace(/\/$/,"")+"/"}@squoosh-kit/${V}/dist/${J}`}function j(G,V,J){let Q=`${G}:${V}`;I[Q]=J}function M(G,V){if(V)try{return new Worker(V,{type:"module"})}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from custom URL ${V}: ${X}`)}let J=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},Y=Q[J];if(!Y)throw Error(`Unknown worker: ${J}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let _=Y.package.split("/")[1],$=J.replace(".js",".browser.mjs"),O=H!==void 0?H:null;if(O)try{let A=v(O,_,$);return new Worker(A,{type:"module"})}catch{}let x=[`../../${_}/dist/${$}`,`../../../node_modules/@squoosh-kit/${_}/dist/${$}`,`../../../${_}/dist/${$}`],K=null;for(let A of x)try{let D=new URL(A,import.meta.url);return new Worker(D,{type:"module"})}catch(D){K=D instanceof Error?D:Error(String(D))}if(K)throw K;throw Error(`Could not resolve worker ${J} using any available path strategy`)}let Z=S()?".bun.js":".node.mjs",X=J.replace(".js",""),L=Y.package.includes("resize")?`../../resize/src/${X}.ts`:`../../webp/src/${X}.ts`;try{return new Worker(new URL(L,import.meta.url),{type:"module"})}catch{let _=Y.package.includes("resize")?`../../resize/dist/${X}.${Z.slice(1)}`:`../../webp/dist/${X}.${Z.slice(1)}`;try{return new Worker(new URL(_,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let $=import.meta.resolve(`${Y.package}/${Y.specifier}`);return new Worker($,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${J}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from ${J}: ${X}. 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 q(G,V){let J,Q=1e4;if(typeof V==="number")Q=V;else if(V)J=V.customWorkerUrl,Q=V.timeoutMs??1e4;return new Promise((Y,Z)=>{let X=setTimeout(()=>{Z(Error(`Worker initialization timeout after ${Q}ms. Worker file: ${G}`))},Q);(async()=>{try{if(typeof window<"u"&&H===void 0)await E().catch(()=>{});let L=M(G,J),_=(x)=>{if(x.data?.type==="worker:ready")clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Y(L)},$=(x)=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker failed to start: ${x?.message||"Unknown error"}. Worker file: ${G}`))},O=()=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker message error during initialization. Worker file: ${G}`))};L.addEventListener("message",_),L.addEventListener("error",$),L.addEventListener("messageerror",O),L.postMessage({type:"worker:ping"})}catch(L){clearTimeout(X),Z(L)}})()})}class C{async encode(G,V,J){let Y=(await import("./webp.worker.bun.js")).webpEncodeClient;return Y(G,V,J)}async terminate(){}}class P{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 q("webp.worker",{customWorkerUrl:this.customWorkerUrl})}async encode(G,V,J){let Q=await this.getWorker();return z(G),T(Q,"webp:encode",{image:G,options:V},J)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function g(G,V){return G==="client"?new C:new P(V)}export{g as createBridge};
|
|
3
3
|
export{g as a};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=ACAB24C04E3FBAAE64756E2164756E21
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Fetch the current HTML document to find script references\n const html = await fetch(window.location.href).then((r) => r.text());\n\n // Look for both resize and webp worker scripts in assets\n const workerPatterns = [\n {\n regex:\n /[\"']([^\"']*assets[^\"']*resize\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'resize',\n },\n {\n regex: /[\"']([^\"']*assets[^\"']*webp\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'webp',\n },\n ];\n\n for (const { regex, package: packageName } of workerPatterns) {\n const match = html.match(regex);\n if (match?.[1]) {\n const workerPath = match[1];\n // Cache the full hashed URL\n cacheHashedWorkerUrl(\n packageName,\n `${packageName}.worker.browser.mjs`,\n workerPath\n );\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 // Kick off auto-detection in the background (doesn't block)\n // This will cache the result for subsequent calls\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n detectWorkerBase().catch(() => {\n // Silently fail detection - we'll fall back to relative paths\n });\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",
|
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Look for worker scripts in the live DOM, which is more reliable for SPAs\n const scripts = Array.from(document.scripts);\n const workerPatterns = [\n {\n name: 'resize',\n regex: /resize\\.worker\\.browser.*\\.js$/,\n },\n {\n name: 'webp',\n regex: /webp\\.worker\\.browser.*\\.js$/,\n },\n ];\n\n for (const { name, regex } of workerPatterns) {\n const script = scripts.find((s) => regex.test(s.src));\n if (script) {\n const workerPath = script.src; // This will be the full, absolute URL\n // Cache the full hashed URL\n cacheHashedWorkerUrl(name, `${name}.worker.browser.mjs`, workerPath);\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 (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",
|
|
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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={};
|
|
1
|
+
var f={};b(f,{createBridge:()=>U});module.exports=N(f);function S(){return typeof Bun<"u"}var y=0;async function T(G,V,J,Q,Y){return new Promise((Z,X)=>{let L=++y;if(Q?.aborted){X(new DOMException("Aborted","AbortError"));return}let _=(A)=>{let D=A.data;if(D.id!==L)return;if(x(),D.ok&&D.data!==void 0)Z(D.data);else X(Error(D.error||"Unknown worker error"))},$=(A)=>{x(),X(Error(`Worker error: ${A.message}`))},O=()=>{x(),X(new DOMException("Aborted","AbortError"))},x=()=>{G.removeEventListener("message",_),G.removeEventListener("error",$),Q?.removeEventListener("abort",O)};G.addEventListener("message",_),G.addEventListener("error",$),Q?.addEventListener("abort",O);let K={type:V,id:L,payload:J};if(Y&&Y.length>0)G.postMessage(K,Y);else G.postMessage(K)})}var H,R=null;async function E(){if(H!==void 0)return H;if(R)return R;return R=(async()=>{if(typeof window>"u"||typeof document>"u")return H=null;let G=document.querySelector('meta[name="squoosh-base"]');if(G?.content)return H=G.content;try{let J=Array.from(document.scripts),Q=[{name:"resize",regex:/resize\.worker\.browser.*\.js$/},{name:"webp",regex:/webp\.worker\.browser.*\.js$/}];for(let{name:Y,regex:Z}of Q){let X=J.find((L)=>Z.test(L.src));if(X){let L=X.src;return j(Y,`${Y}.worker.browser.mjs`,L),H=L.substring(0,L.lastIndexOf("/")+1)}}}catch{}try{let Q="file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts".match(/^(.*\/node_modules\/@squoosh-kit\/runtime\/)/);if(Q)return H=Q[1].replace("runtime/","")}catch{}let V=["/node_modules/@squoosh-kit/","/@squoosh-kit/",window.location.origin+"/node_modules/@squoosh-kit/"];for(let J of V)try{let Q=`${J}resize/dist/resize.worker.browser.mjs`;return await fetch(Q,{method:"HEAD",mode:"no-cors"}),H=J}catch{}return H=null})(),R}var I={};function v(G,V,J){let Q=`${V}:${J}`;if(I[Q])return I[Q];return`${G.replace(/\/$/,"")+"/"}@squoosh-kit/${V}/dist/${J}`}function j(G,V,J){let Q=`${G}:${V}`;I[Q]=J}function M(G,V){if(V)try{return new Worker(V,{type:"module"})}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from custom URL ${V}: ${X}`)}let J=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},Y=Q[J];if(!Y)throw Error(`Unknown worker: ${J}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let _=Y.package.split("/")[1],$=J.replace(".js",".browser.mjs"),O=H!==void 0?H:null;if(O)try{let A=v(O,_,$);return new Worker(A,{type:"module"})}catch{}let x=[`../../${_}/dist/${$}`,`../../../node_modules/@squoosh-kit/${_}/dist/${$}`,`../../../${_}/dist/${$}`],K=null;for(let A of x)try{let D=new URL(A,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");return new Worker(D,{type:"module"})}catch(D){K=D instanceof Error?D:Error(String(D))}if(K)throw K;throw Error(`Could not resolve worker ${J} using any available path strategy`)}let Z=S()?".bun.js":".node.mjs",X=J.replace(".js",""),L=Y.package.includes("resize")?`../../resize/src/${X}.ts`:`../../webp/src/${X}.ts`;try{return new Worker(new URL(L,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{let _=Y.package.includes("resize")?`../../resize/dist/${X}.${Z.slice(1)}`:`../../webp/dist/${X}.${Z.slice(1)}`;try{return new Worker(new URL(_,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let $=import.meta.resolve(`${Y.package}/${Y.specifier}`);return new Worker($,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${J}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from ${J}: ${X}. 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 q(G,V){let J,Q=1e4;if(typeof V==="number")Q=V;else if(V)J=V.customWorkerUrl,Q=V.timeoutMs??1e4;return new Promise((Y,Z)=>{let X=setTimeout(()=>{Z(Error(`Worker initialization timeout after ${Q}ms. Worker file: ${G}`))},Q);(async()=>{try{if(typeof window<"u"&&H===void 0)await E().catch(()=>{});let L=M(G,J),_=(x)=>{if(x.data?.type==="worker:ready")clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Y(L)},$=(x)=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker failed to start: ${x?.message||"Unknown error"}. Worker file: ${G}`))},O=()=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker message error during initialization. Worker file: ${G}`))};L.addEventListener("message",_),L.addEventListener("error",$),L.addEventListener("messageerror",O),L.postMessage({type:"worker:ping"})}catch(L){clearTimeout(X),Z(L)}})()})}class C{async encode(G,V,J){let Y=(await import("./webp.worker.node.cjs")).webpEncodeClient;return Y(G,V,J)}async terminate(){}}class P{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 q("webp.worker",{customWorkerUrl:this.customWorkerUrl})}async encode(G,V,J){let Q=await this.getWorker();return z(G),T(Q,"webp:encode",{image:G,options:V},J)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function U(G,V){return G==="client"?new C:new P(V)}
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=83055C74A0023AD064756E2164756E21
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Fetch the current HTML document to find script references\n const html = await fetch(window.location.href).then((r) => r.text());\n\n // Look for both resize and webp worker scripts in assets\n const workerPatterns = [\n {\n regex:\n /[\"']([^\"']*assets[^\"']*resize\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'resize',\n },\n {\n regex: /[\"']([^\"']*assets[^\"']*webp\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'webp',\n },\n ];\n\n for (const { regex, package: packageName } of workerPatterns) {\n const match = html.match(regex);\n if (match?.[1]) {\n const workerPath = match[1];\n // Cache the full hashed URL\n cacheHashedWorkerUrl(\n packageName,\n `${packageName}.worker.browser.mjs`,\n workerPath\n );\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 // Kick off auto-detection in the background (doesn't block)\n // This will cache the result for subsequent calls\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n detectWorkerBase().catch(() => {\n // Silently fail detection - we'll fall back to relative paths\n });\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",
|
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Look for worker scripts in the live DOM, which is more reliable for SPAs\n const scripts = Array.from(document.scripts);\n const workerPatterns = [\n {\n name: 'resize',\n regex: /resize\\.worker\\.browser.*\\.js$/,\n },\n {\n name: 'webp',\n regex: /webp\\.worker\\.browser.*\\.js$/,\n },\n ];\n\n for (const { name, regex } of workerPatterns) {\n const script = scripts.find((s) => regex.test(s.src));\n if (script) {\n const workerPath = script.src; // This will be the full, absolute URL\n // Cache the full hashed URL\n cacheHashedWorkerUrl(name, `${name}.worker.browser.mjs`, workerPath);\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 (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",
|
|
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,KAA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AkB,EAC1D,EAAO,YAAY,CAAE,KAAM,aAAc,CAAC,EAC1C,MAAO,EAAO,CACd,aAAa,CAAO,EACpB,EAAO,CAAK,KAEb,EACJ,ECnZH,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": "83055C74A0023AD064756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/dist/bridge.node.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as z}from"./chunk-szbj3b6y.js";import{d as B,e as
|
|
1
|
+
import{b as z}from"./chunk-szbj3b6y.js";import{d as B,e as N}from"./chunk-c6cx0d7q.js";function S(){return typeof Bun<"u"}var y=0;async function T(G,V,J,Q,Y){return new Promise((Z,X)=>{let L=++y;if(Q?.aborted){X(new DOMException("Aborted","AbortError"));return}let _=(A)=>{let D=A.data;if(D.id!==L)return;if(x(),D.ok&&D.data!==void 0)Z(D.data);else X(Error(D.error||"Unknown worker error"))},$=(A)=>{x(),X(Error(`Worker error: ${A.message}`))},O=()=>{x(),X(new DOMException("Aborted","AbortError"))},x=()=>{G.removeEventListener("message",_),G.removeEventListener("error",$),Q?.removeEventListener("abort",O)};G.addEventListener("message",_),G.addEventListener("error",$),Q?.addEventListener("abort",O);let K={type:V,id:L,payload:J};if(Y&&Y.length>0)G.postMessage(K,Y);else G.postMessage(K)})}var H,R=null;async function E(){if(H!==void 0)return H;if(R)return R;return R=(async()=>{if(typeof window>"u"||typeof document>"u")return H=null;let G=document.querySelector('meta[name="squoosh-base"]');if(G?.content)return H=G.content;try{let J=Array.from(document.scripts),Q=[{name:"resize",regex:/resize\.worker\.browser.*\.js$/},{name:"webp",regex:/webp\.worker\.browser.*\.js$/}];for(let{name:Y,regex:Z}of Q){let X=J.find((L)=>Z.test(L.src));if(X){let L=X.src;return j(Y,`${Y}.worker.browser.mjs`,L),H=L.substring(0,L.lastIndexOf("/")+1)}}}catch{}try{let Q=import.meta.url.match(/^(.*\/node_modules\/@squoosh-kit\/runtime\/)/);if(Q)return H=Q[1].replace("runtime/","")}catch{}let V=["/node_modules/@squoosh-kit/","/@squoosh-kit/",window.location.origin+"/node_modules/@squoosh-kit/"];for(let J of V)try{let Q=`${J}resize/dist/resize.worker.browser.mjs`;return await fetch(Q,{method:"HEAD",mode:"no-cors"}),H=J}catch{}return H=null})(),R}var I={};function v(G,V,J){let Q=`${V}:${J}`;if(I[Q])return I[Q];return`${G.replace(/\/$/,"")+"/"}@squoosh-kit/${V}/dist/${J}`}function j(G,V,J){let Q=`${G}:${V}`;I[Q]=J}function M(G,V){if(V)try{return new Worker(V,{type:"module"})}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from custom URL ${V}: ${X}`)}let J=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},Y=Q[J];if(!Y)throw Error(`Unknown worker: ${J}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let _=Y.package.split("/")[1],$=J.replace(".js",".browser.mjs"),O=H!==void 0?H:null;if(O)try{let A=v(O,_,$);return new Worker(A,{type:"module"})}catch{}let x=[`../../${_}/dist/${$}`,`../../../node_modules/@squoosh-kit/${_}/dist/${$}`,`../../../${_}/dist/${$}`],K=null;for(let A of x)try{let D=new URL(A,import.meta.url);return new Worker(D,{type:"module"})}catch(D){K=D instanceof Error?D:Error(String(D))}if(K)throw K;throw Error(`Could not resolve worker ${J} using any available path strategy`)}let Z=S()?".bun.js":".node.mjs",X=J.replace(".js",""),L=Y.package.includes("resize")?`../../resize/src/${X}.ts`:`../../webp/src/${X}.ts`;try{return new Worker(new URL(L,import.meta.url),{type:"module"})}catch{let _=Y.package.includes("resize")?`../../resize/dist/${X}.${Z.slice(1)}`:`../../webp/dist/${X}.${Z.slice(1)}`;try{return new Worker(new URL(_,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let $=import.meta.resolve(`${Y.package}/${Y.specifier}`);return new Worker($,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${J}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to create worker from ${J}: ${X}. 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 q(G,V){let J,Q=1e4;if(typeof V==="number")Q=V;else if(V)J=V.customWorkerUrl,Q=V.timeoutMs??1e4;return new Promise((Y,Z)=>{let X=setTimeout(()=>{Z(Error(`Worker initialization timeout after ${Q}ms. Worker file: ${G}`))},Q);(async()=>{try{if(typeof window<"u"&&H===void 0)await E().catch(()=>{});let L=M(G,J),_=(x)=>{if(x.data?.type==="worker:ready")clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Y(L)},$=(x)=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker failed to start: ${x?.message||"Unknown error"}. Worker file: ${G}`))},O=()=>{clearTimeout(X),L.removeEventListener("message",_),L.removeEventListener("error",$),L.removeEventListener("messageerror",O),Z(Error(`Worker message error during initialization. Worker file: ${G}`))};L.addEventListener("message",_),L.addEventListener("error",$),L.addEventListener("messageerror",O),L.postMessage({type:"worker:ping"})}catch(L){clearTimeout(X),Z(L)}})()})}class C{async encode(G,V,J){let Y=(await import("./webp.worker.node.mjs")).webpEncodeClient;return Y(G,V,J)}async terminate(){}}class P{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 q("webp.worker",{customWorkerUrl:this.customWorkerUrl})}async encode(G,V,J){let Q=await this.getWorker();return z(G),T(Q,"webp:encode",{image:G,options:V},J)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function g(G,V){return G==="client"?new C:new P(V)}export{g as createBridge};
|
|
2
2
|
export{g as a};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=C8E2EA498C538CE564756E2164756E21
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Fetch the current HTML document to find script references\n const html = await fetch(window.location.href).then((r) => r.text());\n\n // Look for both resize and webp worker scripts in assets\n const workerPatterns = [\n {\n regex:\n /[\"']([^\"']*assets[^\"']*resize\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'resize',\n },\n {\n regex: /[\"']([^\"']*assets[^\"']*webp\\.worker\\.browser[^\"']*\\.js)[\"']/,\n package: 'webp',\n },\n ];\n\n for (const { regex, package: packageName } of workerPatterns) {\n const match = html.match(regex);\n if (match?.[1]) {\n const workerPath = match[1];\n // Cache the full hashed URL\n cacheHashedWorkerUrl(\n packageName,\n `${packageName}.worker.browser.mjs`,\n workerPath\n );\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 // Kick off auto-detection in the background (doesn't block)\n // This will cache the result for subsequent calls\n if (typeof window !== 'undefined' && detectedWorkerBase === undefined) {\n detectWorkerBase().catch(() => {\n // Silently fail detection - we'll fall back to relative paths\n });\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",
|
|
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 * Uses multiple strategies: meta tag, import.meta.url inference, and HEAD requests\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 users with complex deploys)\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: Look for Vite-bundled workers in assets directory FIRST\n // Vite bundles workers as separate chunks with hashes, e.g., resize.worker.browser-ABC123.js\n // This is the most common case for production Vite/React apps\n try {\n // Look for worker scripts in the live DOM, which is more reliable for SPAs\n const scripts = Array.from(document.scripts);\n const workerPatterns = [\n {\n name: 'resize',\n regex: /resize\\.worker\\.browser.*\\.js$/,\n },\n {\n name: 'webp',\n regex: /webp\\.worker\\.browser.*\\.js$/,\n },\n ];\n\n for (const { name, regex } of workerPatterns) {\n const script = scripts.find((s) => regex.test(s.src));\n if (script) {\n const workerPath = script.src; // This will be the full, absolute URL\n // Cache the full hashed URL\n cacheHashedWorkerUrl(name, `${name}.worker.browser.mjs`, workerPath);\n // Return the base assets path for fallback\n const assetsBase = workerPath.substring(\n 0,\n workerPath.lastIndexOf('/') + 1\n );\n return (detectedWorkerBase = assetsBase);\n }\n }\n } catch {\n // Continue to next strategy\n }\n\n // Strategy 3: Infer from current script context (for npm-installed packages)\n try {\n // Try to detect if we're already in node_modules by checking import.meta.url\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 to next strategy\n }\n\n // Strategy 4: Try common CDN/deployment patterns with HEAD requests\n const testPatterns = [\n '/node_modules/@squoosh-kit/',\n '/@squoosh-kit/',\n window.location.origin + '/node_modules/@squoosh-kit/',\n ];\n\n for (const pattern of testPatterns) {\n try {\n // Test if the pattern is valid by checking if resize worker exists\n const testUrl = `${pattern}resize/dist/resize.worker.browser.mjs`;\n await fetch(testUrl, {\n method: 'HEAD',\n mode: 'no-cors',\n });\n // If fetch succeeds without error, pattern is valid\n return (detectedWorkerBase = pattern);\n } catch {\n // Continue to next pattern\n }\n }\n\n // No detection successful\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// Cache for hashed worker URLs (for Vite-bundled apps)\nconst hashedWorkerUrls: Record<string, string> = {};\n\n/**\n * Build worker URL from detected base\n */\nfunction buildWorkerUrlFromBase(\n base: string,\n packageName: string,\n workerFile: string\n): string {\n // Check if we have a cached hashed URL for this worker\n const cacheKey = `${packageName}:${workerFile}`;\n if (hashedWorkerUrls[cacheKey]) {\n return hashedWorkerUrls[cacheKey];\n }\n\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 * Cache a hashed worker URL (called during Vite assets detection)\n */\nfunction cacheHashedWorkerUrl(\n packageName: string,\n workerFile: string,\n hashedUrl: string\n): void {\n const cacheKey = `${packageName}:${workerFile}`;\n hashedWorkerUrls[cacheKey] = hashedUrl;\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 smart auto-detection with fallback to relative paths.\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 explicit URL configuration when auto-detection fails.\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 smart auto-detection of worker base URLs in browser environments.\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 (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",
|
|
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,GAG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hC,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": "C8E2EA498C538CE564756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@squoosh-kit/webp",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.29",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "WebP codec for squoosh-kit, providing encoding functionality.",
|
|
6
6
|
"author": "Bartosz Nowak <bnowak008@gmail.com>",
|
|
@@ -45,6 +45,6 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@squoosh-kit/runtime": "0.0.
|
|
48
|
+
"@squoosh-kit/runtime": "0.0.28"
|
|
49
49
|
}
|
|
50
50
|
}
|