@squoosh-kit/resize 0.0.4 → 0.0.6
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/README.md +338 -45
- package/dist/bridge.browser.mjs +4 -0
- package/dist/bridge.browser.mjs.map +13 -0
- package/dist/bridge.bun.js +5 -0
- package/dist/bridge.bun.js.map +13 -0
- package/dist/bridge.d.ts +2 -1
- package/dist/bridge.d.ts.map +1 -1
- package/dist/bridge.node.cjs +3 -0
- package/dist/bridge.node.cjs.map +13 -0
- package/dist/bridge.node.mjs +4 -0
- package/dist/bridge.node.mjs.map +13 -0
- package/dist/chunk-djaabg7r.js +3 -0
- package/dist/chunk-djaabg7r.js.map +9 -0
- package/dist/index.browser.mjs +3 -0
- package/dist/index.browser.mjs.map +10 -0
- package/dist/index.bun.js +4 -0
- package/dist/index.bun.js.map +10 -0
- package/dist/index.d.ts +37 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.node.cjs +3 -0
- package/dist/index.node.cjs.map +10 -0
- package/dist/index.node.mjs +3 -0
- package/dist/index.node.mjs.map +10 -0
- package/dist/resize.worker.browser.mjs +4 -0
- package/dist/resize.worker.browser.mjs.map +13 -0
- package/dist/resize.worker.bun.js +5 -0
- package/dist/resize.worker.bun.js.map +13 -0
- package/dist/resize.worker.d.ts +2 -2
- package/dist/resize.worker.d.ts.map +1 -1
- package/dist/resize.worker.node.cjs +3 -0
- package/dist/resize.worker.node.cjs.map +13 -0
- package/dist/resize.worker.node.mjs +4 -0
- package/dist/resize.worker.node.mjs.map +13 -0
- package/dist/types.browser.mjs +2 -0
- package/dist/types.browser.mjs.map +9 -0
- package/dist/types.bun.js +3 -0
- package/dist/types.bun.js.map +9 -0
- package/dist/types.d.ts +27 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.node.cjs +3 -0
- package/dist/types.node.cjs.map +9 -0
- package/dist/types.node.mjs +2 -0
- package/dist/types.node.mjs.map +9 -0
- package/package.json +11 -5
- package/dist/index.js +0 -5
- package/dist/index.js.map +0 -12
- package/dist/resize.worker.js +0 -6
- package/dist/resize.worker.js.map +0 -10
- package/dist/wasm/squoosh_resize.d.ts +0 -34
- package/dist/wasm/squoosh_resize.js +0 -120
- package/dist/wasm/squoosh_resize_bg.wasm +0 -0
- package/dist/wasm/squoosh_resize_bg.wasm.d.ts +0 -7
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/src/wasm-loader.ts", "../../runtime/src/validators.ts", "../wasm/squoosh_resize.js", "../src/resize.worker.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nexport async function loadWasmBinary(\n relativePath: string\n): Promise<ArrayBuffer> {\n try {\n // Strategy 1: Try Node.js fs first (most reliable)\n if (typeof process !== 'undefined' && process.versions?.node) {\n const fsModule = await import('fs/promises');\n const fileUrl = new URL(relativePath, import.meta.url);\n const filePath = fileUrl.pathname;\n const buffer = await fsModule.readFile(filePath);\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n }\n } catch (e) {\n // Fall through to fetch strategy\n }\n\n // Strategy 2: Fallback to fetch (works in browsers and workers)\n try {\n const url = new URL(relativePath, import.meta.url);\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch WASM binary: ${response.status} ${response.statusText}`\n );\n }\n return response.arrayBuffer();\n } catch (error) {\n throw new Error(\n `Failed to load WASM binary from \"${relativePath}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(modulePath);\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n return await import(resolvedPath);\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(modulePath, import.meta.url);\n return await import(url.href);\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`\n );\n }\n}\n",
|
|
6
|
+
"import type { ImageInput } from './types.js';\n\nexport function validateArrayBuffer(\n buffer: unknown\n): asserts buffer is ArrayBuffer {\n if (buffer instanceof SharedArrayBuffer) {\n throw new Error(\n 'SharedArrayBuffer is not supported. ' +\n 'Use regular ArrayBuffer or Uint8Array instead.'\n );\n }\n\n if (!(buffer instanceof ArrayBuffer)) {\n throw new TypeError('image.data.buffer must be an ArrayBuffer');\n }\n}\n\nexport function validateImageInput(\n image: unknown\n): asserts image is ImageInput {\n if (!image || typeof image !== 'object') {\n throw new TypeError('image must be an object');\n }\n\n const imageObj = image as Record<string, unknown>;\n\n if (!('data' in imageObj)) {\n throw new TypeError('image.data is required');\n }\n\n const { data } = imageObj;\n if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {\n throw new TypeError('image.data must be Uint8Array or Uint8ClampedArray');\n }\n\n if (!('width' in imageObj) || !('height' in imageObj)) {\n throw new TypeError('image.width and image.height are required');\n }\n\n const { width, height } = imageObj;\n\n if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {\n throw new RangeError(\n `image.width must be a positive integer, got ${width}`\n );\n }\n\n if (typeof height !== 'number' || !Number.isInteger(height) || height <= 0) {\n throw new RangeError(\n `image.height must be a positive integer, got ${height}`\n );\n }\n\n const expectedSize = width * height * 4;\n if (data.length < expectedSize) {\n throw new RangeError(\n `image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`\n );\n }\n}\n\nexport 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\nexport function validateWebpOptions(options: unknown): asserts options is {\n quality?: number;\n lossless?: boolean;\n nearLossless?: boolean;\n} {\n if (\n options !== undefined &&\n (typeof options !== 'object' || options === null)\n ) {\n throw new TypeError('options must be an object or undefined');\n }\n\n if (options === undefined) {\n return;\n }\n\n const opts = options as Record<string, unknown>;\n\n if (opts.quality !== undefined) {\n if (\n typeof opts.quality !== 'number' ||\n !Number.isInteger(opts.quality) ||\n opts.quality < 0 ||\n opts.quality > 100\n ) {\n throw new RangeError(\n `options.quality must be an integer between 0 and 100, got ${opts.quality}`\n );\n }\n }\n\n if (opts.lossless !== undefined && typeof opts.lossless !== 'boolean') {\n throw new TypeError(\n `options.lossless must be boolean, got ${typeof opts.lossless}`\n );\n }\n\n if (\n opts.nearLossless !== undefined &&\n typeof opts.nearLossless !== 'boolean'\n ) {\n throw new TypeError(\n `options.nearLossless must be boolean, got ${typeof opts.nearLossless}`\n );\n }\n}\n",
|
|
7
|
+
"\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",
|
|
8
|
+
"/**\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 validateResizeOptions,\n} from '@squoosh-kit/runtime';\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 const wasmBuffer = await loadWasmBinary(\n new URL('../wasm/squoosh_resize_bg.wasm', import.meta.url).href\n );\n\n // Initialize WASM module with the binary buffer\n await squoosh_resize_module.default(wasmBuffer);\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 ?? 'mitchell'] ?? 2;\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 const transferable = resultImage.data.buffer;\n if (transferable) {\n self.postMessage(response, [transferable as ArrayBuffer]);\n } else {\n self.postMessage(response);\n }\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"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,MAAQ,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACtE,KAAK,YAAY,CAAQ",
|
|
11
|
+
"debugId": "96BDB17FE3161C3D64756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -3,23 +3,46 @@
|
|
|
3
3
|
*/
|
|
4
4
|
/**
|
|
5
5
|
* Options for resizing an image.
|
|
6
|
+
* All WASM parameters are fully exposed through this interface.
|
|
6
7
|
*/
|
|
7
8
|
export type ResizeOptions = {
|
|
8
9
|
/**
|
|
9
|
-
*
|
|
10
|
+
* Target width of the resized image.
|
|
11
|
+
* If only width is specified, height is calculated to maintain aspect ratio.
|
|
12
|
+
* If both are specified, image is resized to exact dimensions.
|
|
13
|
+
* Must be a positive integer (>= 1). Aspect ratio calculations will always preserve
|
|
14
|
+
* at least 1 pixel for the missing dimension.
|
|
15
|
+
* @default original image width
|
|
10
16
|
*/
|
|
11
17
|
width?: number;
|
|
12
18
|
/**
|
|
13
|
-
*
|
|
19
|
+
* Target height of the resized image.
|
|
20
|
+
* If only height is specified, width is calculated to maintain aspect ratio.
|
|
21
|
+
* If both are specified, image is resized to exact dimensions.
|
|
22
|
+
* Must be a positive integer (>= 1). Aspect ratio calculations will always preserve
|
|
23
|
+
* at least 1 pixel for the missing dimension.
|
|
24
|
+
* @default original image height
|
|
14
25
|
*/
|
|
15
26
|
height?: number;
|
|
16
27
|
/**
|
|
17
|
-
*
|
|
28
|
+
* Resize algorithm to use - controls quality vs speed trade-off.
|
|
29
|
+
* Maps directly to Squoosh WASM typ_idx parameter (0-3).
|
|
30
|
+
* @default 'mitchell' - provides sensible balance between quality and performance
|
|
31
|
+
*/
|
|
32
|
+
method?: 'triangular' | 'catrom' | 'mitchell' | 'lanczos3';
|
|
33
|
+
/**
|
|
34
|
+
* Pre-multiply alpha channel before resizing.
|
|
35
|
+
* When true, alpha is multiplied into RGB values before the resize operation,
|
|
36
|
+
* which can improve the quality of images with transparency.
|
|
37
|
+
* Maps directly to WASM premultiply parameter.
|
|
18
38
|
* @default false
|
|
19
39
|
*/
|
|
20
40
|
premultiply?: boolean;
|
|
21
41
|
/**
|
|
22
|
-
* Use
|
|
42
|
+
* Use linear RGB color space for resizing instead of sRGB.
|
|
43
|
+
* When true, applies proper color space conversion for more mathematically
|
|
44
|
+
* accurate resizing of colors.
|
|
45
|
+
* Maps directly to WASM color_space_conversion parameter.
|
|
23
46
|
* @default false
|
|
24
47
|
*/
|
|
25
48
|
linearRGB?: boolean;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,MAAM,CAAC,EAAE,YAAY,GAAG,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAC;IAC3D;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@squoosh-kit/resize",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Image resize module for squoosh-kit.",
|
|
6
6
|
"author": "Bartosz Nowak <bnowak008@gmail.com>",
|
|
@@ -20,10 +20,16 @@
|
|
|
20
20
|
"exports": {
|
|
21
21
|
".": {
|
|
22
22
|
"types": "./dist/index.d.ts",
|
|
23
|
-
"
|
|
23
|
+
"bun": "./dist/index.bun.js",
|
|
24
|
+
"import": "./dist/index.node.mjs",
|
|
25
|
+
"require": "./dist/index.node.cjs",
|
|
26
|
+
"browser": "./dist/index.browser.mjs"
|
|
24
27
|
},
|
|
25
28
|
"./resize.worker.js": {
|
|
26
|
-
"
|
|
29
|
+
"bun": "./dist/resize.worker.bun.js",
|
|
30
|
+
"import": "./dist/resize.worker.node.mjs",
|
|
31
|
+
"require": "./dist/resize.worker.node.cjs",
|
|
32
|
+
"browser": "./dist/resize.worker.browser.mjs"
|
|
27
33
|
}
|
|
28
34
|
},
|
|
29
35
|
"files": [
|
|
@@ -32,12 +38,12 @@
|
|
|
32
38
|
],
|
|
33
39
|
"sideEffects": false,
|
|
34
40
|
"scripts": {
|
|
35
|
-
"build": "bun run
|
|
41
|
+
"build": "bun run build.ts",
|
|
36
42
|
"clean:local": "rm -rf dist *.tsbuildinfo",
|
|
37
43
|
"prepack": "bun run build && bun test",
|
|
38
44
|
"test": "bun test"
|
|
39
45
|
},
|
|
40
46
|
"dependencies": {
|
|
41
|
-
"@squoosh-kit/runtime": "0.0.
|
|
47
|
+
"@squoosh-kit/runtime": "0.0.5"
|
|
42
48
|
}
|
|
43
49
|
}
|
package/dist/index.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{a as o}from"./resize.worker.js";var G=0;async function U(i,m,z,u,g){return new Promise((R,W)=>{let P=++G;if(u?.aborted){W(new DOMException("Aborted","AbortError"));return}let c=(B)=>{let I=B.data;if(I.id!==P)return;if(console.log("\uD83D\uDD27 Worker call: Response received",I),t(),I.ok&&I.data!==void 0)console.log("\uD83D\uDD27 Worker call: Response data",I.data),R(I.data);else console.log("\uD83D\uDD27 Worker call: Response error",I.error),W(Error(I.error||"Unknown worker error"))},f=(B)=>{t(),W(Error(`Worker error: ${B.message}`))},x=()=>{t(),W(new DOMException("Aborted","AbortError"))},t=()=>{i.removeEventListener("message",c),i.removeEventListener("error",f),u?.removeEventListener("abort",x)};i.addEventListener("message",c),i.addEventListener("error",f),u?.addEventListener("abort",x);let A={type:m,id:P,payload:z};if(g&&g.length>0)i.postMessage(A,g);else i.postMessage(A)})}class k{async resize(i,m,z){return o(i,m,z)}}class F{worker=null;async getWorker(){if(!this.worker){let i=await import.meta.resolve("@squoosh-kit/resize/resize.worker.js");this.worker=new Worker(i,{type:"module"})}return this.worker}async resize(i,m,z){let u=await this.getWorker();console.log("worker",u);let g=m.data.buffer;console.log("buffer",g);try{let R=await U(u,"resize:run",{image:m,options:z},i,[g]);return console.log("result",R),R}catch(R){throw console.error("error",R),R}}}function O(i){return i==="client"?new k:new F}async function Q(i,m,z){return O("worker").resize(i,m,z)}function S(i="worker"){let m=O(i);return m.resize.bind(m)}export{o as resizeClient,Q as resize,S as createResizer};
|
|
3
|
-
|
|
4
|
-
//# debugId=59DDCB371911476764756E2164756E21
|
|
5
|
-
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../runtime/src/worker-call.ts", "../src/bridge.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
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 console.log('🔧 Worker call: Response received', response);\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n console.log('🔧 Worker call: Response data', response.data);\n resolve(response.data);\n } else {\n console.log('🔧 Worker call: Response error', response.error);\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",
|
|
6
|
-
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport { callWorker, type ImageInput } from '@squoosh-kit/runtime';\nimport { resizeClient } from './resize.worker.ts';\nimport type { ResizeOptions } from './types.ts';\n\ninterface ResizeBridge {\n resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput> {\n return resizeClient(signal, image, options);\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private async getWorker(): Promise<Worker> {\n if (!this.worker) {\n const workerUrl = await import.meta.resolve(\n '@squoosh-kit/resize/resize.worker.js'\n );\n this.worker = new Worker(workerUrl, { type: 'module' });\n }\n return this.worker;\n }\n async resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n console.log('worker', worker);\n const buffer = image.data.buffer;\n console.log('buffer', buffer);\n\n try {\n const result = await callWorker<{ image: ImageInput; options: ResizeOptions }, ImageInput>(worker, 'resize:run', { image, options }, signal, [\n buffer as ArrayBuffer,\n ]);\n \n console.log('result', result);\n\n return result;\n } catch (error) {\n console.error('error', error);\n throw error;\n }\n }\n}\n\nexport function createBridge(mode: 'worker' | 'client'): ResizeBridge {\n return mode === 'client'\n ? new ResizeClientBridge()\n : new ResizeWorkerBridge();\n}\n",
|
|
7
|
-
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge';\nimport type { ResizeOptions } from './types';\n\nexport type { ImageInput, ResizeOptions };\n\n/**\n * Resizes an image. Defaults to 'worker' mode.\n *\n * @param signal - An AbortSignal to cancel the resizing operation.\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @returns A Promise resolving to the resized image data.\n */\nexport async function resize(\n signal: AbortSignal,\n imageData: ImageInput,\n options: ResizeOptions\n): Promise<ImageInput> {\n // Always use a worker for a single, one-off call for best performance.\n const bridge = createBridge('worker');\n return bridge.resize(signal, imageData, options);\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.\n */\nexport function createResizer(mode: 'worker' | 'client' = 'worker') {\n const bridge = createBridge(mode);\n return bridge.resize.bind(bridge);\n}\n\n// Export the client-side implementation for direct use by the bridge.\n// This is not intended for public consumption.\nexport { resizeClient } from './resize.worker';\n"
|
|
8
|
-
],
|
|
9
|
-
"mappings": ";uCAiBA,IAAI,EAAY,EAYhB,eAAsB,CAA+B,CACnD,EACA,EACA,EACA,EACA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AI,OAAO,EAAW,CAAE,KAAM,QAAS,CAAC,EAExD,OAAO,KAAK,YAER,OAAM,CACV,EACA,EACA,EACqB,CACrB,IAAM,EAAS,MAAM,KAAK,UAAU,EACpC,QAAQ,IAAI,SAAU,CAAM,EAC5B,IAAM,EAAS,EAAM,KAAK,OAC1B,QAAQ,IAAI,SAAU,CAAM,EAE5B,GAAI,CACF,IAAM,EAAS,MAAM,EAAsE,EAAQ,aAAc,CAAE,QAAO,SAAQ,EAAG,EAAQ,CAC3I,CACF,CAAC,EAID,OAFA,QAAQ,IAAI,SAAU,CAAM,EAErB,EACP,MAAO,EAAO,CAEd,MADA,QAAQ,MAAM,QAAS,CAAK,EACtB,GAGZ,CAEO,SAAS,CAAY,CAAC,EAAyC,CACpE,OAAO,IAAS,SACZ,IAAI,EACJ,IAAI,EC/CV,eAAsB,CAAM,CAC1B,EACA,EACA,EACqB,CAGrB,OADe,EAAa,QAAQ,EACtB,OAAO,EAAQ,EAAW,CAAO,EAS1C,SAAS,CAAa,CAAC,EAA4B,SAAU,CAClE,IAAM,EAAS,EAAa,CAAI,EAChC,OAAO,EAAO,OAAO,KAAK,CAAM",
|
|
10
|
-
"debugId": "59DDCB371911476764756E2164756E21",
|
|
11
|
-
"names": []
|
|
12
|
-
}
|
package/dist/resize.worker.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
var K=null;async function O(){if(K)return;let F="./wasm/resize",j=await import.meta.resolve(`${F}/squoosh_resize.js`),x=await import(j);await x.default(fetch(new URL(`${F}/squoosh_resize_bg.wasm`,j))),K=x.resize}async function L(F,j){if(await O(),!K)throw Error("Resize module not initialized");let{data:x,width:G,height:B}=F,E=j.width??G,J=j.height??B;if(j.width&&!j.height)J=Math.round(B*j.width/G);else if(j.height&&!j.width)E=Math.round(G*j.height/B);if(E<=0||J<=0)throw Error("Invalid output dimensions");let N=x instanceof Uint8ClampedArray?new Uint8Array(x):x;return{data:K(N,G,B,E,J,Q(),j.premultiply?1:0,j.linearRGB?1:0),width:E,height:J}}async function T(F,j,x){if(F.aborted)throw new DOMException("Aborted","AbortError");return L(j,x)}function Q(){return 3}if(typeof self<"u")self.onmessage=async(F)=>{let{id:j,type:x,payload:G}=F.data,B={id:j,ok:!1};try{if(x!=="resize:run")throw Error(`Unknown message type: ${x}`);let E=await L(G.image,G.options);B.ok=!0,B.data=E;let J=E.data.buffer;if(J)self.postMessage(B,[J]);else self.postMessage(B)}catch(E){B.error=E instanceof Error?E.message:String(E),self.postMessage(B)}};export{T as resizeClient};
|
|
3
|
-
export{T as a};
|
|
4
|
-
|
|
5
|
-
//# debugId=2E07CB4CD56250F364756E2164756E21
|
|
6
|
-
//# sourceMappingURL=resize.worker.js.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/resize.worker.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n hasImageData,\n type WorkerRequest,\n type WorkerResponse,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\n// Define the type locally to avoid module resolution issues with the linter\ntype SquooshWasmResize = (\n data: Uint8Array,\n input_width: number,\n input_height: number,\n output_width: number,\n output_height: number,\n typ_idx: number,\n premultiply: number,\n color_space_conversion: number,\n) => Uint8Array;\n\nlet wasmResize: SquooshWasmResize | null = null;\n\nasync function init(): Promise<void> {\n if (wasmResize) {\n return;\n }\n\n const wasmDirectory = './wasm/resize';\n const modulePath = await import.meta.resolve(\n `${wasmDirectory}/squoosh_resize.js`,\n );\n const module = await import(modulePath);\n\n // Squoosh's WASM modules expect to be initialized with promises\n await module.default(\n fetch(new URL(`${wasmDirectory}/squoosh_resize_bg.wasm`, modulePath)),\n );\n wasmResize = module.resize;\n}\n\nasync function _resizeCore(\n image: ImageInput,\n options: ResizeOptions,\n): Promise<ImageInput> {\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.round((inputHeight * options.width) / inputWidth);\n } else if (options.height && !options.width) {\n outputWidth = Math.round((inputWidth * options.height) / inputHeight);\n }\n\n if (outputWidth <= 0 || outputHeight <= 0) {\n throw new Error('Invalid output dimensions');\n }\n\n const dataArray =\n data instanceof Uint8ClampedArray ? new Uint8Array(data) : data;\n\n const result = wasmResize(\n dataArray,\n inputWidth,\n inputHeight,\n outputWidth,\n outputHeight,\n getResizeMethod(),\n options.premultiply ? 1 : 0,\n options.linearRGB ? 1 : 0,\n );\n\n return {\n data: result,\n width: outputWidth,\n height: outputHeight,\n };\n}\n\nexport async function resizeClient(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions,\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 to the typ_idx parameter for the resize function\n * 0: Triangular, 1: Catrom, 2: Mitchell, 3: Lanczos3\n */\nfunction getResizeMethod(): number {\n // Default to Lanczos3 (highest quality)\n return 3;\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (\n event: MessageEvent<\n WorkerRequest<{ image: ImageInput; options: ResizeOptions }>\n >,\n ) => {\n const { id, type, payload } = event.data;\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 const transferable = resultImage.data.buffer;\n if (transferable) {\n self.postMessage(response, [transferable as ArrayBuffer]);\n } else {\n self.postMessage(response);\n }\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
|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MAAU,MAAM,yBAAyB,GAAM,EAGjD,IAAM,EAAc,MAAM,EAAY,EAAQ,MAAO,EAAQ,OAAO,EAEpE,EAAS,GAAK,GACd,EAAS,KAAO,EAEhB,IAAM,EAAe,EAAY,KAAK,OACtC,GAAI,EACF,KAAK,YAAY,EAAU,CAAC,CAA2B,CAAC,EAExD,UAAK,YAAY,CAAQ,EAE3B,MAAO,EAAO,CACd,EAAS,MAAQ,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACtE,KAAK,YAAY,CAAQ",
|
|
8
|
-
"debugId": "2E07CB4CD56250F364756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/* tslint:disable */
|
|
2
|
-
/* eslint-disable */
|
|
3
|
-
/**
|
|
4
|
-
* @param {Uint8Array} input_image
|
|
5
|
-
* @param {number} input_width
|
|
6
|
-
* @param {number} input_height
|
|
7
|
-
* @param {number} output_width
|
|
8
|
-
* @param {number} output_height
|
|
9
|
-
* @param {number} typ_idx
|
|
10
|
-
* @param {boolean} premultiply
|
|
11
|
-
* @param {boolean} color_space_conversion
|
|
12
|
-
* @returns {Uint8ClampedArray}
|
|
13
|
-
*/
|
|
14
|
-
export function resize(input_image: Uint8Array, input_width: number, input_height: number, output_width: number, output_height: number, typ_idx: number, premultiply: boolean, color_space_conversion: boolean): Uint8ClampedArray;
|
|
15
|
-
|
|
16
|
-
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
17
|
-
|
|
18
|
-
export interface InitOutput {
|
|
19
|
-
readonly memory: WebAssembly.Memory;
|
|
20
|
-
readonly resize: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number) => void;
|
|
21
|
-
readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
|
|
22
|
-
readonly __wbindgen_malloc: (a: number) => number;
|
|
23
|
-
readonly __wbindgen_free: (a: number, b: number) => void;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
|
|
28
|
-
* for everything else, calls `WebAssembly.instantiate` directly.
|
|
29
|
-
*
|
|
30
|
-
* @param {InitInput | Promise<InitInput>} module_or_path
|
|
31
|
-
*
|
|
32
|
-
* @returns {Promise<InitOutput>}
|
|
33
|
-
*/
|
|
34
|
-
export default function init (module_or_path?: InitInput | Promise<InitInput>): Promise<InitOutput>;
|
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
let wasm;
|
|
3
|
-
|
|
4
|
-
let cachegetUint8Memory0 = null;
|
|
5
|
-
function getUint8Memory0() {
|
|
6
|
-
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
|
|
7
|
-
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
|
|
8
|
-
}
|
|
9
|
-
return cachegetUint8Memory0;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
let WASM_VECTOR_LEN = 0;
|
|
13
|
-
|
|
14
|
-
function passArray8ToWasm0(arg, malloc) {
|
|
15
|
-
const ptr = malloc(arg.length * 1);
|
|
16
|
-
getUint8Memory0().set(arg, ptr / 1);
|
|
17
|
-
WASM_VECTOR_LEN = arg.length;
|
|
18
|
-
return ptr;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
let cachegetInt32Memory0 = null;
|
|
22
|
-
function getInt32Memory0() {
|
|
23
|
-
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
|
|
24
|
-
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
|
|
25
|
-
}
|
|
26
|
-
return cachegetInt32Memory0;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
let cachegetUint8ClampedMemory0 = null;
|
|
30
|
-
function getUint8ClampedMemory0() {
|
|
31
|
-
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
|
|
32
|
-
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
|
|
33
|
-
}
|
|
34
|
-
return cachegetUint8ClampedMemory0;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function getClampedArrayU8FromWasm0(ptr, len) {
|
|
38
|
-
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* @param {Uint8Array} input_image
|
|
42
|
-
* @param {number} input_width
|
|
43
|
-
* @param {number} input_height
|
|
44
|
-
* @param {number} output_width
|
|
45
|
-
* @param {number} output_height
|
|
46
|
-
* @param {number} typ_idx
|
|
47
|
-
* @param {boolean} premultiply
|
|
48
|
-
* @param {boolean} color_space_conversion
|
|
49
|
-
* @returns {Uint8ClampedArray}
|
|
50
|
-
*/
|
|
51
|
-
export function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {
|
|
52
|
-
try {
|
|
53
|
-
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
54
|
-
var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);
|
|
55
|
-
var len0 = WASM_VECTOR_LEN;
|
|
56
|
-
wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);
|
|
57
|
-
var r0 = getInt32Memory0()[retptr / 4 + 0];
|
|
58
|
-
var r1 = getInt32Memory0()[retptr / 4 + 1];
|
|
59
|
-
var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();
|
|
60
|
-
wasm.__wbindgen_free(r0, r1 * 1);
|
|
61
|
-
return v1;
|
|
62
|
-
} finally {
|
|
63
|
-
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function load(module, imports) {
|
|
68
|
-
if (typeof Response === 'function' && module instanceof Response) {
|
|
69
|
-
if (typeof WebAssembly.instantiateStreaming === 'function') {
|
|
70
|
-
try {
|
|
71
|
-
return await WebAssembly.instantiateStreaming(module, imports);
|
|
72
|
-
|
|
73
|
-
} catch (e) {
|
|
74
|
-
if (module.headers.get('Content-Type') != 'application/wasm') {
|
|
75
|
-
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);
|
|
76
|
-
|
|
77
|
-
} else {
|
|
78
|
-
throw e;
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const bytes = await module.arrayBuffer();
|
|
84
|
-
return await WebAssembly.instantiate(bytes, imports);
|
|
85
|
-
|
|
86
|
-
} else {
|
|
87
|
-
const instance = await WebAssembly.instantiate(module, imports);
|
|
88
|
-
|
|
89
|
-
if (instance instanceof WebAssembly.Instance) {
|
|
90
|
-
return { instance, module };
|
|
91
|
-
|
|
92
|
-
} else {
|
|
93
|
-
return instance;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
async function init(input) {
|
|
99
|
-
if (typeof input === 'undefined') {
|
|
100
|
-
input = new URL('squoosh_resize_bg.wasm', import.meta.url);
|
|
101
|
-
}
|
|
102
|
-
const imports = {};
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
|
|
106
|
-
input = fetch(input);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const { instance, module } = await load(await input, imports);
|
|
112
|
-
|
|
113
|
-
wasm = instance.exports;
|
|
114
|
-
init.__wbindgen_wasm_module = module;
|
|
115
|
-
|
|
116
|
-
return wasm;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export default init;
|
|
120
|
-
|
|
Binary file
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/* tslint:disable */
|
|
2
|
-
/* eslint-disable */
|
|
3
|
-
export const memory: WebAssembly.Memory;
|
|
4
|
-
export function resize(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number): void;
|
|
5
|
-
export function __wbindgen_add_to_stack_pointer(a: number): number;
|
|
6
|
-
export function __wbindgen_malloc(a: number): number;
|
|
7
|
-
export function __wbindgen_free(a: number, b: number): void;
|