@squoosh-kit/core 0.0.36 → 0.0.38

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.
@@ -1,12 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../resize/src/validators.ts", "../../resize/wasm/squoosh_resize.js", "../../resize/src/resize.worker.ts"],
4
- "sourcesContent": [
5
- "export function validateResizeOptions(options: unknown): asserts options is {\n width?: number;\n height?: number;\n method?: 'triangular' | 'catrom' | 'mitchell' | 'lanczos3';\n premultiply?: boolean;\n linearRGB?: boolean;\n} {\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('options must be an object');\n }\n\n const opts = options as Record<string, unknown>;\n\n if (opts.width !== undefined) {\n if (\n typeof opts.width !== 'number' ||\n !Number.isInteger(opts.width) ||\n opts.width <= 0\n ) {\n throw new RangeError(\n `options.width must be a positive integer, got ${opts.width}`\n );\n }\n }\n\n if (opts.height !== undefined) {\n if (\n typeof opts.height !== 'number' ||\n !Number.isInteger(opts.height) ||\n opts.height <= 0\n ) {\n throw new RangeError(\n `options.height must be a positive integer, got ${opts.height}`\n );\n }\n }\n\n if (opts.method !== undefined) {\n const validMethods = ['triangular', 'catrom', 'mitchell', 'lanczos3'];\n if (!validMethods.includes(opts.method as string)) {\n throw new TypeError(\n `options.method must be one of: ${validMethods.join(', ')}, got ${opts.method}`\n );\n }\n }\n\n if (opts.premultiply !== undefined && typeof opts.premultiply !== 'boolean') {\n throw new TypeError(\n `options.premultiply must be boolean, got ${typeof opts.premultiply}`\n );\n }\n\n if (opts.linearRGB !== undefined && typeof opts.linearRGB !== 'boolean') {\n throw new TypeError(\n `options.linearRGB must be boolean, got ${typeof opts.linearRGB}`\n );\n }\n}\n",
6
- "\nlet wasm;\n\nlet cachegetUint8Memory0 = null;\nfunction getUint8Memory0() {\n if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {\n cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachegetUint8Memory0;\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1);\n getUint8Memory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nlet cachegetInt32Memory0 = null;\nfunction getInt32Memory0() {\n if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {\n cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);\n }\n return cachegetInt32Memory0;\n}\n\nlet cachegetUint8ClampedMemory0 = null;\nfunction getUint8ClampedMemory0() {\n if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {\n cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);\n }\n return cachegetUint8ClampedMemory0;\n}\n\nfunction getClampedArrayU8FromWasm0(ptr, len) {\n return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n/**\n* @param {Uint8Array} input_image\n* @param {number} input_width\n* @param {number} input_height\n* @param {number} output_width\n* @param {number} output_height\n* @param {number} typ_idx\n* @param {boolean} premultiply\n* @param {boolean} color_space_conversion\n* @returns {Uint8ClampedArray}\n*/\nexport function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);\n var len0 = WASM_VECTOR_LEN;\n wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);\n var r0 = getInt32Memory0()[retptr / 4 + 0];\n var r1 = getInt32Memory0()[retptr / 4 + 1];\n var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\nasync function load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nasync function init(input) {\n if (typeof input === 'undefined') {\n input = new URL('squoosh_resize_bg.wasm', import.meta.url);\n }\n const imports = {};\n\n\n if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {\n input = fetch(input);\n }\n\n\n\n const { instance, module } = await load(await input, imports);\n\n wasm = instance.exports;\n init.__wbindgen_wasm_module = module;\n\n return wasm;\n}\n\nexport default init;\n\n",
7
- "/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n type WorkerRequest,\n type WorkerResponse,\n type ImageInput,\n loadWasmBinary,\n validateImageInput,\n} from '@squoosh-kit/runtime';\nimport { validateResizeOptions } from './validators';\nimport type { ResizeOptions } from './types';\nimport * as squoosh_resize_module from '../wasm/squoosh_resize';\n\n// Define the type locally to avoid module resolution issues with the linter\ntype SquooshWasmResize = (\n input_image: Uint8Array,\n input_width: number,\n input_height: number,\n output_width: number,\n output_height: number,\n typ_idx: number,\n premultiply: boolean,\n color_space_conversion: boolean\n) => Uint8ClampedArray;\n\nlet wasmResize: SquooshWasmResize | null = null;\nlet initPromise: Promise<void> | null = null;\n\nasync function init(): Promise<void> {\n if (wasmResize) {\n return;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n try {\n // Load WASM binary with robust fallback strategies\n // Try multiple paths to support both development (../wasm) and npm installed (./wasm) scenarios\n let wasmBuffer: ArrayBuffer | null = null;\n const pathsToTry = [\n new URL(\n /* @vite-ignore */ './wasm/squoosh_resize_bg.wasm',\n import.meta.url\n ).href,\n new URL(\n /* @vite-ignore */ '../wasm/squoosh_resize_bg.wasm',\n import.meta.url\n ).href,\n ];\n\n let lastError: Error | null = null;\n for (const path of pathsToTry) {\n try {\n wasmBuffer = await loadWasmBinary(path);\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next path\n }\n }\n\n if (!wasmBuffer) {\n throw (\n lastError || new Error('Could not load WASM binary from any path')\n );\n }\n\n // Initialize WASM module with the binary buffer\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (initError: unknown) {\n // If initialization fails due to SharedArrayBuffer issues, try with polyfill\n if (\n initError instanceof Error &&\n (initError.message.includes('SharedArrayBuffer') ||\n initError.message.includes('first argument must be'))\n ) {\n // Apply polyfill and retry\n if (typeof SharedArrayBuffer === 'undefined') {\n (\n globalThis as unknown as Record<string, typeof ArrayBuffer>\n ).SharedArrayBuffer = ArrayBuffer;\n }\n // Reload the module with polyfill in place\n try {\n await squoosh_resize_module.default(wasmBuffer);\n } catch (retryError) {\n throw new Error(\n `WASM module initialization failed even with polyfill: ${retryError instanceof Error ? retryError.message : String(retryError)}`\n );\n }\n } else {\n throw initError;\n }\n }\n // After initialization, the module's exported resize function is ready to use\n wasmResize = squoosh_resize_module.resize as unknown as SquooshWasmResize;\n } catch (error) {\n initPromise = null;\n throw new Error(\n `Failed to initialize resize WASM module: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n })();\n\n return initPromise;\n}\n\nasync function _resizeCore(\n image: ImageInput,\n options: ResizeOptions\n): Promise<ImageInput> {\n validateImageInput(image);\n validateResizeOptions(options);\n\n await init();\n if (!wasmResize) {\n throw new Error('Resize module not initialized');\n }\n\n const { data, width: inputWidth, height: inputHeight } = image;\n\n let outputWidth = options.width ?? inputWidth;\n let outputHeight = options.height ?? inputHeight;\n\n if (options.width && !options.height) {\n outputHeight = Math.max(\n 1,\n Math.round((inputHeight * options.width) / inputWidth)\n );\n } else if (options.height && !options.width) {\n outputWidth = Math.max(\n 1,\n Math.round((inputWidth * options.height) / inputHeight)\n );\n }\n\n if (outputWidth < 1 || outputHeight < 1) {\n throw new RangeError(\n `Output dimensions must be at least 1x1, got ${outputWidth}x${outputHeight}`\n );\n }\n\n // Create a zero-copy Uint8Array view if needed\n // (don't copy the buffer - just create a view on the same memory)\n const dataArray =\n data instanceof Uint8ClampedArray\n ? new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.length)\n : new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.length\n );\n\n const result = wasmResize(\n dataArray,\n inputWidth,\n inputHeight,\n outputWidth,\n outputHeight,\n getResizeMethod(options),\n options.premultiply ?? true,\n options.linearRGB ?? true\n );\n\n return {\n data: result,\n width: outputWidth,\n height: outputHeight,\n };\n}\n\nexport async function resizeClient(\n image: ImageInput,\n options: ResizeOptions,\n signal?: AbortSignal\n): Promise<ImageInput> {\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n return _resizeCore(image, options);\n}\n\n/**\n * Map ResizeOptions method to WASM typ_idx parameter\n * typ_idx values (from Squoosh):\n * 0: Triangular - fastest, lowest quality\n * 1: Catrom - medium quality and speed\n * 2: Mitchell - good balance (default)\n * 3: Lanczos3 - highest quality, slowest\n */\nfunction getResizeMethod(options?: ResizeOptions): number {\n const methodMap: Record<string, number> = {\n triangular: 0,\n catrom: 1,\n mitchell: 2,\n lanczos3: 3,\n };\n return methodMap[options?.method ?? 'lanczos3'] ?? 3;\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const { id, type, payload } = data as WorkerRequest<{\n image: ImageInput;\n options: ResizeOptions;\n }>;\n\n const response: WorkerResponse<ImageInput> = { id, ok: false };\n\n try {\n if (type !== 'resize:run') {\n throw new Error(`Unknown message type: ${type}`);\n }\n\n const resultImage = await _resizeCore(payload.image, payload.options);\n\n response.ok = true;\n response.data = resultImage;\n\n // Post the response without transferring - the ImageInput with data will be cloned\n // Transfer is only used for incoming requests (image.data buffer from client)\n self.postMessage(response);\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
8
- ],
9
- "mappings": ";sFAAO,GAAS,CAAqB,CAAC,EAMpC,CACA,GAAI,OAAO,IAAY,UAAY,IAAY,KAC7C,MAAU,UAAU,2BAA2B,EAGjD,IAAM,EAAO,EAEb,GAAI,EAAK,QAAU,QACjB,GACE,OAAO,EAAK,QAAU,UACtB,CAAC,OAAO,UAAU,EAAK,KAAK,GAC5B,EAAK,OAAS,EAEd,MAAU,WACR,iDAAiD,EAAK,OACxD,EAIJ,GAAI,EAAK,SAAW,QAClB,GACE,OAAO,EAAK,SAAW,UACvB,CAAC,OAAO,UAAU,EAAK,MAAM,GAC7B,EAAK,QAAU,EAEf,MAAU,WACR,kDAAkD,EAAK,QACzD,EAIJ,GAAI,EAAK,SAAW,OAAW,CAC7B,IAAM,EAAe,CAAC,aAAc,SAAU,WAAY,UAAU,EACpE,GAAI,CAAC,EAAa,SAAS,EAAK,MAAgB,EAC9C,MAAU,UACR,kCAAkC,EAAa,KAAK,IAAI,UAAU,EAAK,QACzE,EAIJ,GAAI,EAAK,cAAgB,QAAa,OAAO,EAAK,cAAgB,UAChE,MAAU,UACR,4CAA4C,OAAO,EAAK,aAC1D,EAGF,GAAI,EAAK,YAAc,QAAa,OAAO,EAAK,YAAc,UAC5D,MAAU,UACR,0CAA0C,OAAO,EAAK,WACxD,ECtDJ,IAAI,EAEA,EAAuB,KAC3B,SAAS,CAAe,EAAG,CACvB,GAAI,IAAyB,MAAQ,EAAqB,SAA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