@squoosh-kit/core 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-245sw6kx.js +3 -0
- package/dist/{chunk-3rt7m395.js.map → chunk-245sw6kx.js.map} +3 -3
- package/dist/chunk-5d1w8na7.js +3 -0
- package/dist/{chunk-yv042k8x.js.map → chunk-5d1w8na7.js.map} +3 -3
- package/dist/chunk-6qtap428.js +4 -0
- package/dist/chunk-6qtap428.js.map +12 -0
- package/dist/chunk-74bcayvr.js +3 -0
- package/dist/chunk-74bcayvr.js.map +13 -0
- package/dist/chunk-8r69sf95.js +5 -0
- package/dist/chunk-8r69sf95.js.map +12 -0
- package/dist/chunk-cfpkr9nw.js +5 -0
- package/dist/{chunk-02ytt443.js.map → chunk-cfpkr9nw.js.map} +5 -4
- package/dist/chunk-d3fxpzrq.js +4 -0
- package/dist/{chunk-mm6wmg56.js.map → chunk-d3fxpzrq.js.map} +5 -4
- package/dist/chunk-f8hc5gnf.js +4 -0
- package/dist/chunk-f8hc5gnf.js.map +12 -0
- package/dist/chunk-fks9mwgb.js +3 -0
- package/dist/chunk-fks9mwgb.js.map +13 -0
- package/dist/{chunk-69d55ymx.js → chunk-kjhvs4qe.js} +2 -2
- package/dist/{chunk-69d55ymx.js.map → chunk-kjhvs4qe.js.map} +3 -3
- package/dist/{chunk-374tq8cw.js → chunk-kqn499ka.js} +2 -2
- package/dist/chunk-kqn499ka.js.map +13 -0
- package/dist/chunk-rta7shf1.js +4 -0
- package/dist/{chunk-p24n653d.js.map → chunk-rta7shf1.js.map} +5 -4
- package/dist/chunk-sycf5j9m.js +4 -0
- package/dist/{chunk-yd1vfk89.js.map → chunk-sycf5j9m.js.map} +3 -3
- package/dist/chunk-t4jk8xn4.js +3 -0
- package/dist/chunk-t4jk8xn4.js.map +12 -0
- package/dist/chunk-vk3k7qxb.js +3 -0
- package/dist/{chunk-6d2104pn.js.map → chunk-vk3k7qxb.js.map} +5 -4
- package/dist/chunk-wvd3rsja.js +4 -0
- package/dist/chunk-wvd3rsja.js.map +13 -0
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +4 -5
- package/dist/index.bun.js +2 -2
- package/dist/index.bun.js.map +4 -5
- package/dist/index.node.cjs +2 -2
- package/dist/index.node.cjs.map +4 -5
- package/dist/index.node.mjs +2 -2
- package/dist/index.node.mjs.map +4 -5
- package/package.json +3 -3
- package/dist/chunk-02ytt443.js +0 -5
- package/dist/chunk-14jg2dxs.js +0 -5
- package/dist/chunk-14jg2dxs.js.map +0 -10
- package/dist/chunk-374tq8cw.js.map +0 -13
- package/dist/chunk-3rt7m395.js +0 -3
- package/dist/chunk-5ap8cyw0.js +0 -4
- package/dist/chunk-5ap8cyw0.js.map +0 -13
- package/dist/chunk-6d2104pn.js +0 -3
- package/dist/chunk-btz1s2ws.js +0 -3
- package/dist/chunk-btz1s2ws.js.map +0 -10
- package/dist/chunk-h7zpk6jq.js +0 -4
- package/dist/chunk-h7zpk6jq.js.map +0 -10
- package/dist/chunk-mm6wmg56.js +0 -4
- package/dist/chunk-p24n653d.js +0 -4
- package/dist/chunk-rht1286y.js +0 -3
- package/dist/chunk-rht1286y.js.map +0 -13
- package/dist/chunk-vt6b43b9.js +0 -3
- package/dist/chunk-vt6b43b9.js.map +0 -13
- package/dist/chunk-yd1vfk89.js +0 -4
- package/dist/chunk-yv042k8x.js +0 -3
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/
|
|
3
|
+
"sources": ["../../runtime/src/worker-call.ts", "../../runtime/src/worker-helper.ts", "../../webp/src/bridge.ts", "../../webp/src/index.ts", "../../resize/src/bridge.ts", "../../resize/src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
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
5
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
6
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\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 console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\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\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\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 console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
7
|
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n console.log(\n '[webp/bridge] WebpWorkerBridge constructor called with options:',\n options\n );\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n console.log('[webp/bridge] createWorker called. Creating ready worker...');\n this.worker = await createReadyWorker('webp.worker.js', this.options);\n console.log(\n '[webp/bridge] createWorker: Ready worker created successfully.'\n );\n return this.worker;\n }\n\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n return callWorker(worker, 'webp:encode', { image, options }, signal);\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): WebPBridge {\n console.log(`[webp/bridge] createBridge called with mode: ${mode}`);\n if (mode === 'worker') {\n return new WebpWorkerBridge(options);\n }\n return new WebpClientBridge();\n}\n",
|
|
9
8
|
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): WebpEncoderFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
9
|
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n this.worker = await createReadyWorker('resize.worker.js', this.options);\n return this.worker;\n }\n\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n\n try {\n const result = await callWorker<\n { image: ImageInput; options: ResizeOptions },\n ImageInput\n >(worker, 'resize:run', { image, options }, signal);\n\n return result;\n } catch (error) {\n console.error('Resize error:', error);\n throw error;\n }\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): ResizeBridge {\n if (mode === 'worker') {\n return new ResizeWorkerBridge(options);\n }\n return new ResizeClientBridge();\n}\n",
|
|
11
10
|
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): ResizerFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n"
|
|
12
11
|
],
|
|
13
|
-
"mappings": "
|
|
14
|
-
"debugId": "
|
|
12
|
+
"mappings": "6DAiBA,IAAI,EAAY,EAYhB,eAAsB,CAA+B,CACnD,EACA,EACA,EACA,EACA,EACoB,CACpB,OAAO,IAAI,QAAmB,CAAC,EAAS,IAAW,CACjD,IAAM,EAAK,EAAE,EAGb,GAAI,GAAQ,QAAS,CACnB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,OAGF,IAAM,EAAgB,CAAC,IAAwB,CAC7C,IAAM,EAAW,EAAM,KACvB,GAAI,EAAS,KAAO,EAAI,OAIxB,GAFA,EAAQ,EAEJ,EAAS,IAAM,EAAS,OAAS,OACnC,EAAQ,EAAS,IAAI,EAErB,OAAW,MAAM,EAAS,OAAS,sBAAsB,CAAC,GAIxD,EAAc,CAAC,IAAsB,CACzC,EAAQ,EACR,EAAW,MAAM,iBAAiB,EAAM,SAAS,CAAC,GAG9C,EAAc,IAAM,CACxB,EAAQ,EACR,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,GAG5C,EAAU,IAAM,CACpB,EAAO,oBAAoB,UAAW,CAAa,EACnD,EAAO,oBAAoB,QAAS,CAAW,EAC/C,GAAQ,oBAAoB,QAAS,CAAW,GAIlD,EAAO,iBAAiB,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,GAAQ,iBAAiB,QAAS,CAAW,EAG7C,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AAM,EAAS,EAAa,EAAM,CAAO,EAEzC,OAAO,OAAO,OACZ,CAAC,EAAuB,EAAwB,IAAyB,CACvE,OAAO,EAAO,OAAO,EAAW,EAAS,CAAM,GAEjD,CACE,UAAW,SAAY,CACrB,MAAM,EAAO,UAAU,EAE3B,CACF",
|
|
13
|
+
"debugId": "EE3CE22F4274C98464756E2164756E21",
|
|
15
14
|
"names": []
|
|
16
15
|
}
|
package/dist/index.bun.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{d as W,e as j,f as N,h as T}from"./chunk-cfpkr9nw.js";var v=0;async function D(G,L,H,Q,J){return new Promise((V,K)=>{let O=++v;if(Q?.aborted){K(new DOMException("Aborted","AbortError"));return}let X=(_)=>{let $=_.data;if($.id!==O)return;if(S(),$.ok&&$.data!==void 0)V($.data);else K(Error($.error||"Unknown worker error"))},Y=(_)=>{S(),K(Error(`Worker error: ${_.message}`))},I=()=>{S(),K(new DOMException("Aborted","AbortError"))},S=()=>{G.removeEventListener("message",X),G.removeEventListener("error",Y),Q?.removeEventListener("abort",I)};G.addEventListener("message",X),G.addEventListener("error",Y),Q?.addEventListener("abort",I);let Z={type:L,id:O,payload:H};if(J&&J.length>0)G.postMessage(Z,J);else G.postMessage(Z)})}function F(G,L){let H=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},J=Q[H];if(!J)throw Error(`Unknown worker: ${H}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let X=J.package.split("/")[1],Y=H.replace(".js",".browser.mjs");if(console.log("[worker-helper] In browser environment. Trying to create worker:"),console.log(`[worker-helper] - Package Name: ${X}`),console.log(`[worker-helper] - Worker File: ${Y}`),L?.assetPath){let Z=L.assetPath;if(!Z.startsWith("/"))Z="/"+Z;if(Z.endsWith("/"))Z=Z.slice(0,-1);let _=`${Z}/${X}/${Y}`,$=new URL(_,window.location.origin).href;console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${$}`);try{let x=new Worker($,{type:"module"});return console.log(`[worker-helper] Successfully created worker with assetPath: ${$}`),x}catch(x){throw console.error(`[worker-helper] Failed to load worker from assetPath URL: ${$}`,x),Error(`Worker failed to load from ${$}: ${x instanceof Error?x.message:String(x)}`)}}let I=[`../../${X}/dist/${Y}`,`../../../node_modules/@squoosh-kit/${X}/dist/${Y}`,`../../../${X}/dist/${Y}`],S=null;for(let Z of I){console.log("relPath:",Z),console.log("import.meta.url:",import.meta.url);try{let _=new URL(Z,import.meta.url);console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${_.href}`);let $=new Worker(_,{type:"module"});return console.log(`[worker-helper] Successfully created worker with URL: ${_.href}`),$}catch(_){console.warn(`[worker-helper] Path strategy failed for ${Z}:`,_),S=_ instanceof Error?_:Error(String(_))}}if(S)throw console.error("[worker-helper] All path strategies failed.",S),S;throw Error(`Could not resolve worker ${H} using any available path strategy`)}let V=N()?".bun.js":".node.mjs",K=H.replace(".js",""),O=J.package.includes("resize")?`../../resize/src/${K}.ts`:`../../webp/src/${K}.ts`;console.log("srcRelPath:",O),console.log("import.meta.url:",import.meta.url);try{return new Worker(new URL(O,import.meta.url),{type:"module"})}catch{let X=J.package.includes("resize")?`../../resize/dist/${K}.${V.slice(1)}`:`../../webp/dist/${K}.${V.slice(1)}`;console.log("distRelPath:",X),console.log("import.meta.url:",import.meta.url);try{return new Worker(new URL(X,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Y=import.meta.resolve(`${J.package}/${J.specifier}`);return console.log("resolved:",Y),new Worker(Y,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${H}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(V){let K=V instanceof Error?V.message:String(V);throw Error(`Failed to create worker from ${H}: ${K}. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. If you're using Vite, ensure the worker files are not being optimized as dependencies.`)}}function U(G,L,H=1e4){return new Promise((Q,J)=>{let V=setTimeout(()=>{J(Error(`Worker initialization timeout after ${H}ms. Worker file: ${G}`))},H),K;try{K=F(G,L)}catch(I){clearTimeout(V),J(I);return}let O=(I)=>{if(I.data?.type==="worker:ready")clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),Q(K)},X=(I)=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker failed to start: ${I?.message||"Unknown error"}. Worker file: ${G}`))},Y=()=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker message error during initialization. Worker file: ${G}`))};K.addEventListener("message",O),K.addEventListener("error",X),K.addEventListener("messageerror",Y),K.postMessage({type:"worker:ping"})})}class E{async encode(G,L,H){let J=(await import("./chunk-wvd3rsja.js")).webpEncodeClient;return J(G,L,H)}async terminate(){}}class M{worker=null;workerReady=null;options;constructor(G){console.log("[webp/bridge] WebpWorkerBridge constructor called with options:",G),this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return console.log("[webp/bridge] createWorker called. Creating ready worker..."),this.worker=await U("webp.worker.js",this.options),console.log("[webp/bridge] createWorker: Ready worker created successfully."),this.worker}async encode(G,L,H){let Q=await this.getWorker();return T(G),D(Q,"webp:encode",{image:G,options:L},H)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function q(G,L){if(console.log(`[webp/bridge] createBridge called with mode: ${G}`),G==="worker")return new M(L);return new E}var R=null;async function w(G,L,H){if(!R)R=q("worker");return R.encode(G,L,H)}function p(G="worker",L){let H=q(G,L);return Object.assign((Q,J,V)=>{return H.encode(Q,J,V)},{terminate:async()=>{await H.terminate()}})}class B{async resize(G,L,H){let J=(await import("./chunk-sycf5j9m.js")).resizeClient;return J(G,L,H)}async terminate(){}}class P{worker=null;workerReady=null;options;constructor(G){this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return this.worker=await U("resize.worker.js",this.options),this.worker}async resize(G,L,H){let Q=await this.getWorker();T(G);try{return await D(Q,"resize:run",{image:G,options:L},H)}catch(J){throw console.error("Resize error:",J),J}}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function A(G,L){if(G==="worker")return new P(L);return new B}var y=null;async function s(G,L,H){if(!y)y=A("worker");return y.resize(G,L,H)}function n(G="worker",L){let H=A(G,L);return Object.assign((Q,J,V)=>{return H.resize(Q,J,V)},{terminate:async()=>{await H.terminate()}})}export{s as resize,w as encode,p as createWebpEncoder,n as createResizer};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=FA1EE033D287B13764756E2164756E21
|
package/dist/index.bun.js.map
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/
|
|
3
|
+
"sources": ["../../runtime/src/worker-call.ts", "../../runtime/src/worker-helper.ts", "../../webp/src/bridge.ts", "../../webp/src/index.ts", "../../resize/src/bridge.ts", "../../resize/src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
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
5
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
6
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\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 console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\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\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\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 console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
7
|
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n console.log(\n '[webp/bridge] WebpWorkerBridge constructor called with options:',\n options\n );\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n console.log('[webp/bridge] createWorker called. Creating ready worker...');\n this.worker = await createReadyWorker('webp.worker.js', this.options);\n console.log(\n '[webp/bridge] createWorker: Ready worker created successfully.'\n );\n return this.worker;\n }\n\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n return callWorker(worker, 'webp:encode', { image, options }, signal);\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): WebPBridge {\n console.log(`[webp/bridge] createBridge called with mode: ${mode}`);\n if (mode === 'worker') {\n return new WebpWorkerBridge(options);\n }\n return new WebpClientBridge();\n}\n",
|
|
9
8
|
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): WebpEncoderFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
9
|
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n this.worker = await createReadyWorker('resize.worker.js', this.options);\n return this.worker;\n }\n\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n\n try {\n const result = await callWorker<\n { image: ImageInput; options: ResizeOptions },\n ImageInput\n >(worker, 'resize:run', { image, options }, signal);\n\n return result;\n } catch (error) {\n console.error('Resize error:', error);\n throw error;\n }\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): ResizeBridge {\n if (mode === 'worker') {\n return new ResizeWorkerBridge(options);\n }\n return new ResizeClientBridge();\n}\n",
|
|
11
10
|
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): ResizerFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n"
|
|
12
11
|
],
|
|
13
|
-
"mappings": ";
|
|
14
|
-
"debugId": "
|
|
12
|
+
"mappings": ";6DAiBA,IAAI,EAAY,EAYhB,eAAsB,CAA+B,CACnD,EACA,EACA,EACA,EACA,EACoB,CACpB,OAAO,IAAI,QAAmB,CAAC,EAAS,IAAW,CACjD,IAAM,EAAK,EAAE,EAGb,GAAI,GAAQ,QAAS,CACnB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,OAGF,IAAM,EAAgB,CAAC,IAAwB,CAC7C,IAAM,EAAW,EAAM,KACvB,GAAI,EAAS,KAAO,EAAI,OAIxB,GAFA,EAAQ,EAEJ,EAAS,IAAM,EAAS,OAAS,OACnC,EAAQ,EAAS,IAAI,EAErB,OAAW,MAAM,EAAS,OAAS,sBAAsB,CAAC,GAIxD,EAAc,CAAC,IAAsB,CACzC,EAAQ,EACR,EAAW,MAAM,iBAAiB,EAAM,SAAS,CAAC,GAG9C,EAAc,IAAM,CACxB,EAAQ,EACR,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,GAG5C,EAAU,IAAM,CACpB,EAAO,oBAAoB,UAAW,CAAa,EACnD,EAAO,oBAAoB,QAAS,CAAW,EAC/C,GAAQ,oBAAoB,QAAS,CAAW,GAIlD,EAAO,iBAAiB,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,GAAQ,iBAAiB,QAAS,CAAW,EAG7C,IAAM,EAAmC,CAAE,OAAM,KAAI,SAAQ,EAE7D,GAAI,GAAY,EAAS,OAAS,EAChC,EAAO,YAAY,EAAS,CAAQ,EAEpC,OAAO,YAAY,CAAO,EAE7B,EC/DI,SAAS,CAAiB,CAC/B,EACA,EACQ,CAER,IAAM,EAAiB,EAAe,SAAS,KAAK,EAChD,EACA,GAAG,OAGD,EAAoE,CACxE,mBAAoB,CAClB,QAAS,sB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ist/index.node.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var c={};u(c,{resize:()=>C,encode:()=>
|
|
1
|
+
var c={};u(c,{resize:()=>C,encode:()=>F,createWebpEncoder:()=>z,createResizer:()=>b});module.exports=f(c);var P=0;async function D(G,L,H,Q,J){return new Promise((V,K)=>{let O=++P;if(Q?.aborted){K(new DOMException("Aborted","AbortError"));return}let X=(_)=>{let $=_.data;if($.id!==O)return;if(S(),$.ok&&$.data!==void 0)V($.data);else K(Error($.error||"Unknown worker error"))},Y=(_)=>{S(),K(Error(`Worker error: ${_.message}`))},I=()=>{S(),K(new DOMException("Aborted","AbortError"))},S=()=>{G.removeEventListener("message",X),G.removeEventListener("error",Y),Q?.removeEventListener("abort",I)};G.addEventListener("message",X),G.addEventListener("error",Y),Q?.addEventListener("abort",I);let Z={type:L,id:O,payload:H};if(J&&J.length>0)G.postMessage(Z,J);else G.postMessage(Z)})}function v(G,L){let H=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},J=Q[H];if(!J)throw Error(`Unknown worker: ${H}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let X=J.package.split("/")[1],Y=H.replace(".js",".browser.mjs");if(console.log("[worker-helper] In browser environment. Trying to create worker:"),console.log(`[worker-helper] - Package Name: ${X}`),console.log(`[worker-helper] - Worker File: ${Y}`),L?.assetPath){let Z=L.assetPath;if(!Z.startsWith("/"))Z="/"+Z;if(Z.endsWith("/"))Z=Z.slice(0,-1);let _=`${Z}/${X}/${Y}`,$=new URL(_,window.location.origin).href;console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${$}`);try{let x=new Worker($,{type:"module"});return console.log(`[worker-helper] Successfully created worker with assetPath: ${$}`),x}catch(x){throw console.error(`[worker-helper] Failed to load worker from assetPath URL: ${$}`,x),Error(`Worker failed to load from ${$}: ${x instanceof Error?x.message:String(x)}`)}}let I=[`../../${X}/dist/${Y}`,`../../../node_modules/@squoosh-kit/${X}/dist/${Y}`,`../../../${X}/dist/${Y}`],S=null;for(let Z of I){console.log("relPath:",Z),console.log("import.meta.url:","file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");try{let _=new URL(Z,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${_.href}`);let $=new Worker(_,{type:"module"});return console.log(`[worker-helper] Successfully created worker with URL: ${_.href}`),$}catch(_){console.warn(`[worker-helper] Path strategy failed for ${Z}:`,_),S=_ instanceof Error?_:Error(String(_))}}if(S)throw console.error("[worker-helper] All path strategies failed.",S),S;throw Error(`Could not resolve worker ${H} using any available path strategy`)}let V=N()?".bun.js":".node.mjs",K=H.replace(".js",""),O=J.package.includes("resize")?`../../resize/src/${K}.ts`:`../../webp/src/${K}.ts`;console.log("srcRelPath:",O),console.log("import.meta.url:","file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");try{return new Worker(new URL(O,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{let X=J.package.includes("resize")?`../../resize/dist/${K}.${V.slice(1)}`:`../../webp/dist/${K}.${V.slice(1)}`;console.log("distRelPath:",X),console.log("import.meta.url:","file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts");try{return new Worker(new URL(X,"file:///home/bnowak/repos/squoosh-kit/packages/runtime/src/worker-helper.ts"),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Y=import.meta.resolve(`${J.package}/${J.specifier}`);return console.log("resolved:",Y),new Worker(Y,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${H}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(V){let K=V instanceof Error?V.message:String(V);throw Error(`Failed to create worker from ${H}: ${K}. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. If you're using Vite, ensure the worker files are not being optimized as dependencies.`)}}function U(G,L,H=1e4){return new Promise((Q,J)=>{let V=setTimeout(()=>{J(Error(`Worker initialization timeout after ${H}ms. Worker file: ${G}`))},H),K;try{K=v(G,L)}catch(I){clearTimeout(V),J(I);return}let O=(I)=>{if(I.data?.type==="worker:ready")clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),Q(K)},X=(I)=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker failed to start: ${I?.message||"Unknown error"}. Worker file: ${G}`))},Y=()=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker message error during initialization. Worker file: ${G}`))};K.addEventListener("message",O),K.addEventListener("error",X),K.addEventListener("messageerror",Y),K.postMessage({type:"worker:ping"})})}class j{async encode(G,L,H){let J=(await import("./chunk-kqn499ka.js")).webpEncodeClient;return J(G,L,H)}async terminate(){}}class E{worker=null;workerReady=null;options;constructor(G){console.log("[webp/bridge] WebpWorkerBridge constructor called with options:",G),this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return console.log("[webp/bridge] createWorker called. Creating ready worker..."),this.worker=await U("webp.worker.js",this.options),console.log("[webp/bridge] createWorker: Ready worker created successfully."),this.worker}async encode(G,L,H){let Q=await this.getWorker();return T(G),D(Q,"webp:encode",{image:G,options:L},H)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function q(G,L){if(console.log(`[webp/bridge] createBridge called with mode: ${G}`),G==="worker")return new E(L);return new j}var R=null;async function F(G,L,H){if(!R)R=q("worker");return R.encode(G,L,H)}function z(G="worker",L){let H=q(G,L);return Object.assign((Q,J,V)=>{return H.encode(Q,J,V)},{terminate:async()=>{await H.terminate()}})}class M{async resize(G,L,H){let J=(await import("./chunk-kjhvs4qe.js")).resizeClient;return J(G,L,H)}async terminate(){}}class B{worker=null;workerReady=null;options;constructor(G){this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return this.worker=await U("resize.worker.js",this.options),this.worker}async resize(G,L,H){let Q=await this.getWorker();T(G);try{return await D(Q,"resize:run",{image:G,options:L},H)}catch(J){throw console.error("Resize error:",J),J}}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function A(G,L){if(G==="worker")return new B(L);return new M}var y=null;async function C(G,L,H){if(!y)y=A("worker");return y.resize(G,L,H)}function b(G="worker",L){let H=A(G,L);return Object.assign((Q,J,V)=>{return H.resize(Q,J,V)},{terminate:async()=>{await H.terminate()}})}
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=0390E3019FF0240264756E2164756E21
|
package/dist/index.node.cjs.map
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/
|
|
3
|
+
"sources": ["../../runtime/src/worker-call.ts", "../../runtime/src/worker-helper.ts", "../../webp/src/bridge.ts", "../../webp/src/index.ts", "../../resize/src/bridge.ts", "../../resize/src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
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
5
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = workerConfig.package.includes('resize')\n ? `../../resize/dist/${baseName}.${platformExt.slice(1)}`\n : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
6
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`\n );\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 console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = workerConfig.package.includes('resize')\n ? `../../resize/src/${baseName}.ts`\n : `../../webp/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\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\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\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 console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
7
|
"/**\n * Bridge implementation for the WebP package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { EncodeInputOptions } from './types';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface WebPBridge {\n encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array>;\n terminate(): Promise<void>;\n}\n\nclass WebpClientBridge implements WebPBridge {\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n // Dynamically import the client encoder to avoid module loading issues in Vite\n const module = await import('./webp.worker.js');\n const webpEncodeClient = module.webpEncodeClient as (\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => Promise<Uint8Array>;\n return webpEncodeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass WebpWorkerBridge implements WebPBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n console.log(\n '[webp/bridge] WebpWorkerBridge constructor called with options:',\n options\n );\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n console.log('[webp/bridge] createWorker called. Creating ready worker...');\n this.worker = await createReadyWorker('webp.worker.js', this.options);\n console.log(\n '[webp/bridge] createWorker: Ready worker created successfully.'\n );\n return this.worker;\n }\n\n async encode(\n image: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ): Promise<Uint8Array> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n return callWorker(worker, 'webp:encode', { image, options }, signal);\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): WebPBridge {\n console.log(`[webp/bridge] createBridge called with mode: ${mode}`);\n if (mode === 'worker') {\n return new WebpWorkerBridge(options);\n }\n return new WebpClientBridge();\n}\n",
|
|
9
8
|
"/**\n * @squoosh-kit/webp public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { EncodeInputOptions } from './types';\n\nexport type { ImageInput, EncodeInputOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A WebP image encoder that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type WebpEncoderFactory = ((\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n) => Promise<Uint8Array>) & {\n /**\n * Terminates the encoder and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const encoder = createWebpEncoder('worker');\n * try {\n * const result = await encoder(imageData, options);\n * } finally {\n * await encoder.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Encodes an image to WebP format. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to encode.\n * @param options - WebP encoding options.\n * @param signal - (Optional) AbortSignal to cancel the encoding operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the encoded WebP data as a Uint8Array.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await encode(imageData, { quality: 85 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await encode(imageData, { quality: 85 });\n */\nexport async function encode(\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.encode(imageData, options, signal);\n}\n\n/**\n * Creates a reusable WebP encoder function for a specific execution mode.\n * This is useful for processing multiple images without the overhead of\n * creating a new worker or client instance each time.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that encodes an image to WebP format with optional AbortSignal.\n */\nexport function createWebpEncoder(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): WebpEncoderFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (\n imageData: ImageInput,\n options?: EncodeInputOptions,\n signal?: AbortSignal\n ) => {\n return bridge.encode(imageData, options, signal);\n },\n {\n terminate: async () => {\n await bridge.terminate();\n },\n }\n );\n}\n",
|
|
10
9
|
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport {\n callWorker,\n createReadyWorker,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateImageInput } from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\nexport type BridgeOptions = {\n assetPath?: string;\n};\n\ninterface ResizeBridge {\n resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput>;\n terminate(): Promise<void>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n // Dynamically import the client resizer to avoid module loading issues in Vite\n const module = await import('./resize.worker.ts');\n const resizeClient = module.resizeClient as (\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ) => Promise<ImageInput>;\n return resizeClient(image, options, signal);\n }\n\n async terminate(): Promise<void> {\n // Client mode has nothing to terminate\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private workerReady: Promise<Worker> | null = null;\n private options?: BridgeOptions;\n\n constructor(options?: BridgeOptions) {\n this.options = options;\n }\n\n private async getWorker(): Promise<Worker> {\n if (!this.workerReady) {\n this.workerReady = this.createWorker();\n }\n return this.workerReady;\n }\n\n private async createWorker(): Promise<Worker> {\n this.worker = await createReadyWorker('resize.worker.js', this.options);\n return this.worker;\n }\n\n async resize(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n\n validateImageInput(image);\n\n try {\n const result = await callWorker<\n { image: ImageInput; options: ResizeOptions },\n ImageInput\n >(worker, 'resize:run', { image, options }, signal);\n\n return result;\n } catch (error) {\n console.error('Resize error:', error);\n throw error;\n }\n }\n\n async terminate(): Promise<void> {\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n this.workerReady = null;\n }\n }\n}\n\nexport function createBridge(\n mode: 'worker' | 'client',\n options?: BridgeOptions\n): ResizeBridge {\n if (mode === 'worker') {\n return new ResizeWorkerBridge(options);\n }\n return new ResizeClientBridge();\n}\n",
|
|
11
10
|
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge, type BridgeOptions } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n// Global bridge instance for reuse\nlet globalClientBridge: ReturnType<typeof createBridge> | null = null;\n\n/**\n * A resizable image processor that can be reused for multiple operations.\n * Can be terminated to clean up associated resources (especially workers).\n */\nexport type ResizerFactory = ((\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n) => Promise<ImageInput>) & {\n /**\n * Terminates the resizer and cleans up resources.\n * Important for worker mode to prevent memory leaks.\n *\n * @example\n * const resizer = createResizer('worker');\n * try {\n * const result = await resizer(imageData, options);\n * } finally {\n * await resizer.terminate();\n * }\n */\n terminate(): Promise<void>;\n};\n\n/**\n * Resizes an image. Uses worker mode for UI responsiveness.\n *\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @param signal - (Optional) AbortSignal to cancel the resizing operation.\n * If provided, you can cancel the operation by calling\n * `controller.abort()` on the associated AbortController.\n * If not provided, the operation cannot be cancelled.\n * @returns A Promise resolving to the resized image data.\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController();\n * const result = await resize(imageData, { width: 800 }, controller.signal);\n * setTimeout(() => controller.abort(), 5000);\n *\n * @example\n * // Without cancellation (operation cannot be stopped)\n * const result = await resize(imageData, { width: 800 });\n */\nexport async function resize(\n imageData: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n // Use worker mode for UI responsiveness - prevents blocking the main thread\n if (!globalClientBridge) {\n globalClientBridge = createBridge('worker');\n }\n\n return globalClientBridge.resize(imageData, options, signal);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image with optional AbortSignal.\n */\nexport function createResizer(\n mode: 'worker' | 'client' = 'worker',\n options?: BridgeOptions\n): ResizerFactory {\n const bridge = createBridge(mode, options);\n\n return Object.assign(\n (imageData: ImageInput, options: ResizeOptions, signal?: AbortSignal) => {\n return bridge.resize(imageData, options, signal);\n },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|
1
|
+
import{d as W,e as j,f as N,h as T}from"./chunk-d3fxpzrq.js";var v=0;async function D(G,L,H,Q,J){return new Promise((V,K)=>{let O=++v;if(Q?.aborted){K(new DOMException("Aborted","AbortError"));return}let X=(_)=>{let $=_.data;if($.id!==O)return;if(S(),$.ok&&$.data!==void 0)V($.data);else K(Error($.error||"Unknown worker error"))},Y=(_)=>{S(),K(Error(`Worker error: ${_.message}`))},I=()=>{S(),K(new DOMException("Aborted","AbortError"))},S=()=>{G.removeEventListener("message",X),G.removeEventListener("error",Y),Q?.removeEventListener("abort",I)};G.addEventListener("message",X),G.addEventListener("error",Y),Q?.addEventListener("abort",I);let Z={type:L,id:O,payload:H};if(J&&J.length>0)G.postMessage(Z,J);else G.postMessage(Z)})}function F(G,L){let H=G.endsWith(".js")?G:`${G}.js`,Q={"resize.worker.js":{package:"@squoosh-kit/resize",specifier:"resize.worker.js"},"webp.worker.js":{package:"@squoosh-kit/webp",specifier:"webp.worker.js"}},J=Q[H];if(!J)throw Error(`Unknown worker: ${H}. Supported workers: ${Object.keys(Q).join(", ")}`);try{if(typeof window<"u"){let X=J.package.split("/")[1],Y=H.replace(".js",".browser.mjs");if(console.log("[worker-helper] In browser environment. Trying to create worker:"),console.log(`[worker-helper] - Package Name: ${X}`),console.log(`[worker-helper] - Worker File: ${Y}`),L?.assetPath){let Z=L.assetPath;if(!Z.startsWith("/"))Z="/"+Z;if(Z.endsWith("/"))Z=Z.slice(0,-1);let _=`${Z}/${X}/${Y}`,$=new URL(_,window.location.origin).href;console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${$}`);try{let x=new Worker($,{type:"module"});return console.log(`[worker-helper] Successfully created worker with assetPath: ${$}`),x}catch(x){throw console.error(`[worker-helper] Failed to load worker from assetPath URL: ${$}`,x),Error(`Worker failed to load from ${$}: ${x instanceof Error?x.message:String(x)}`)}}let I=[`../../${X}/dist/${Y}`,`../../../node_modules/@squoosh-kit/${X}/dist/${Y}`,`../../../${X}/dist/${Y}`],S=null;for(let Z of I){console.log("relPath:",Z),console.log("import.meta.url:",import.meta.url);try{let _=new URL(Z,import.meta.url);console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${_.href}`);let $=new Worker(_,{type:"module"});return console.log(`[worker-helper] Successfully created worker with URL: ${_.href}`),$}catch(_){console.warn(`[worker-helper] Path strategy failed for ${Z}:`,_),S=_ instanceof Error?_:Error(String(_))}}if(S)throw console.error("[worker-helper] All path strategies failed.",S),S;throw Error(`Could not resolve worker ${H} using any available path strategy`)}let V=N()?".bun.js":".node.mjs",K=H.replace(".js",""),O=J.package.includes("resize")?`../../resize/src/${K}.ts`:`../../webp/src/${K}.ts`;console.log("srcRelPath:",O),console.log("import.meta.url:",import.meta.url);try{return new Worker(new URL(O,import.meta.url),{type:"module"})}catch{let X=J.package.includes("resize")?`../../resize/dist/${K}.${V.slice(1)}`:`../../webp/dist/${K}.${V.slice(1)}`;console.log("distRelPath:",X),console.log("import.meta.url:",import.meta.url);try{return new Worker(new URL(X,import.meta.url),{type:"module"})}catch{if(typeof import.meta.resolve==="function")try{let Y=import.meta.resolve(`${J.package}/${J.specifier}`);return console.log("resolved:",Y),new Worker(Y,{type:"module"})}catch{}}}throw Error(`Failed to create worker from ${H}. Tried TypeScript source, dist output, and import.meta.resolve. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`)}catch(V){let K=V instanceof Error?V.message:String(V);throw Error(`Failed to create worker from ${H}: ${K}. Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. If you're using Vite, ensure the worker files are not being optimized as dependencies.`)}}function U(G,L,H=1e4){return new Promise((Q,J)=>{let V=setTimeout(()=>{J(Error(`Worker initialization timeout after ${H}ms. Worker file: ${G}`))},H),K;try{K=F(G,L)}catch(I){clearTimeout(V),J(I);return}let O=(I)=>{if(I.data?.type==="worker:ready")clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),Q(K)},X=(I)=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker failed to start: ${I?.message||"Unknown error"}. Worker file: ${G}`))},Y=()=>{clearTimeout(V),K.removeEventListener("message",O),K.removeEventListener("error",X),K.removeEventListener("messageerror",Y),J(Error(`Worker message error during initialization. Worker file: ${G}`))};K.addEventListener("message",O),K.addEventListener("error",X),K.addEventListener("messageerror",Y),K.postMessage({type:"worker:ping"})})}class E{async encode(G,L,H){let J=(await import("./chunk-74bcayvr.js")).webpEncodeClient;return J(G,L,H)}async terminate(){}}class M{worker=null;workerReady=null;options;constructor(G){console.log("[webp/bridge] WebpWorkerBridge constructor called with options:",G),this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return console.log("[webp/bridge] createWorker called. Creating ready worker..."),this.worker=await U("webp.worker.js",this.options),console.log("[webp/bridge] createWorker: Ready worker created successfully."),this.worker}async encode(G,L,H){let Q=await this.getWorker();return T(G),D(Q,"webp:encode",{image:G,options:L},H)}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function q(G,L){if(console.log(`[webp/bridge] createBridge called with mode: ${G}`),G==="worker")return new M(L);return new E}var R=null;async function w(G,L,H){if(!R)R=q("worker");return R.encode(G,L,H)}function p(G="worker",L){let H=q(G,L);return Object.assign((Q,J,V)=>{return H.encode(Q,J,V)},{terminate:async()=>{await H.terminate()}})}class B{async resize(G,L,H){let J=(await import("./chunk-5d1w8na7.js")).resizeClient;return J(G,L,H)}async terminate(){}}class P{worker=null;workerReady=null;options;constructor(G){this.options=G}async getWorker(){if(!this.workerReady)this.workerReady=this.createWorker();return this.workerReady}async createWorker(){return this.worker=await U("resize.worker.js",this.options),this.worker}async resize(G,L,H){let Q=await this.getWorker();T(G);try{return await D(Q,"resize:run",{image:G,options:L},H)}catch(J){throw console.error("Resize error:",J),J}}async terminate(){if(this.worker)this.worker.terminate(),this.worker=null,this.workerReady=null}}function A(G,L){if(G==="worker")return new P(L);return new B}var y=null;async function s(G,L,H){if(!y)y=A("worker");return y.resize(G,L,H)}function n(G="worker",L){let H=A(G,L);return Object.assign((Q,J,V)=>{return H.resize(Q,J,V)},{terminate:async()=>{await H.terminate()}})}export{s as resize,w as encode,p as createWebpEncoder,n as createResizer};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=1C1FB27EA90E895D64756E2164756E21
|