@squoosh-kit/resize 0.0.41 → 0.0.44

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.
Files changed (62) hide show
  1. package/README.md +0 -34
  2. package/dist/bridge.d.ts +4 -1
  3. package/dist/bridge.d.ts.map +1 -1
  4. package/dist/index.browser.mjs +577 -2
  5. package/dist/index.browser.mjs.map +14 -4
  6. package/dist/index.bun.js +577 -2
  7. package/dist/index.bun.js.map +14 -4
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.node.cjs +599 -2
  11. package/dist/index.node.cjs.map +14 -4
  12. package/dist/index.node.mjs +577 -2
  13. package/dist/index.node.mjs.map +14 -4
  14. package/dist/resize.worker.browser.mjs +503 -2
  15. package/dist/resize.worker.browser.mjs.map +10 -4
  16. package/dist/resize.worker.bun.js +503 -2
  17. package/dist/resize.worker.bun.js.map +10 -4
  18. package/dist/resize.worker.node.cjs +517 -2
  19. package/dist/resize.worker.node.cjs.map +10 -4
  20. package/dist/resize.worker.node.mjs +503 -2
  21. package/dist/resize.worker.node.mjs.map +10 -4
  22. package/package.json +2 -2
  23. package/dist/bridge.browser.mjs +0 -4
  24. package/dist/bridge.browser.mjs.map +0 -13
  25. package/dist/bridge.bun.js +0 -5
  26. package/dist/bridge.bun.js.map +0 -13
  27. package/dist/bridge.node.cjs +0 -3
  28. package/dist/bridge.node.cjs.map +0 -13
  29. package/dist/bridge.node.mjs +0 -4
  30. package/dist/bridge.node.mjs.map +0 -13
  31. package/dist/chunk-5vdxd0v3.js +0 -4
  32. package/dist/chunk-5vdxd0v3.js.map +0 -10
  33. package/dist/chunk-8y42hv65.js +0 -5
  34. package/dist/chunk-8y42hv65.js.map +0 -9
  35. package/dist/chunk-bhj61bkd.js +0 -4
  36. package/dist/chunk-bhj61bkd.js.map +0 -9
  37. package/dist/chunk-c6cx0d7q.js +0 -4
  38. package/dist/chunk-c6cx0d7q.js.map +0 -9
  39. package/dist/chunk-djaabg7r.js +0 -3
  40. package/dist/chunk-djaabg7r.js.map +0 -9
  41. package/dist/chunk-gw29pvyv.js +0 -3
  42. package/dist/chunk-gw29pvyv.js.map +0 -10
  43. package/dist/chunk-q0apy7nk.js +0 -5
  44. package/dist/chunk-q0apy7nk.js.map +0 -10
  45. package/dist/chunk-szbj3b6y.js +0 -4
  46. package/dist/chunk-szbj3b6y.js.map +0 -10
  47. package/dist/types.browser.mjs +0 -2
  48. package/dist/types.browser.mjs.map +0 -9
  49. package/dist/types.bun.js +0 -3
  50. package/dist/types.bun.js.map +0 -9
  51. package/dist/types.node.cjs +0 -3
  52. package/dist/types.node.cjs.map +0 -9
  53. package/dist/types.node.mjs +0 -2
  54. package/dist/types.node.mjs.map +0 -9
  55. package/dist/validators.browser.mjs +0 -4
  56. package/dist/validators.browser.mjs.map +0 -10
  57. package/dist/validators.bun.js +0 -5
  58. package/dist/validators.bun.js.map +0 -10
  59. package/dist/validators.node.cjs +0 -3
  60. package/dist/validators.node.cjs.map +0 -10
  61. package/dist/validators.node.mjs +0 -4
  62. package/dist/validators.node.mjs.map +0 -10
package/README.md CHANGED
@@ -467,40 +467,6 @@ All options map directly to the Squoosh WASM resize function:
467
467
  - **Browsers** - Web Worker support for responsive user interfaces
468
468
  - **TypeScript** - Complete type safety and IntelliSense support
469
469
 
470
- ## Vite Configuration
471
-
472
- If you're using Vite and encounter worker loading errors in production (e.g., "Worker failed to start: Unknown error"), you need to configure Vite to handle this package correctly.
473
-
474
- ### Required Vite Configuration
475
-
476
- Add this to your `vite.config.ts`:
477
-
478
- ```typescript
479
- import { defineConfig } from 'vite';
480
- import react from '@vitejs/plugin-react'; // or your framework plugin
481
-
482
- export default defineConfig({
483
- plugins: [react()],
484
- ssr: {
485
- // Prevent squoosh-kit packages from being treated as external in SSR builds
486
- noExternal: ['@squoosh-kit/resize', '@squoosh-kit/runtime'],
487
- },
488
- optimizeDeps: {
489
- // Include squoosh-kit packages in pre-bundling
490
- include: ['@squoosh-kit/resize', '@squoosh-kit/runtime'],
491
- },
492
- });
493
- ```
494
-
495
- ### Troubleshooting
496
-
497
- If you still see worker loading errors:
498
-
499
- 1. **Clear your build cache**: Delete `dist/` and `.vite/` directories, then rebuild
500
- 2. **Check network tab**: Verify the worker files are being found in the browser DevTools Network tab
501
- 3. **Verify installation**: Ensure the package is installed: `bun install` (or `npm install`)
502
- 4. **Verify files exist**: Confirm worker file exists at `node_modules/@squoosh-kit/resize/dist/resize.worker.browser.mjs`
503
-
504
470
  ## License
505
471
 
506
472
  MIT - resize with confidence
package/dist/bridge.d.ts CHANGED
@@ -3,10 +3,13 @@
3
3
  */
4
4
  import { type ImageInput } from '@squoosh-kit/runtime';
5
5
  import type { ResizeOptions } from './types.ts';
6
+ export type BridgeOptions = {
7
+ assetPath?: string;
8
+ };
6
9
  interface ResizeBridge {
7
10
  resize(image: ImageInput, options: ResizeOptions, signal?: AbortSignal): Promise<ImageInput>;
8
11
  terminate(): Promise<void>;
9
12
  }
10
- export declare function createBridge(mode: 'worker' | 'client'): ResizeBridge;
13
+ export declare function createBridge(mode: 'worker' | 'client', options?: BridgeOptions): ResizeBridge;
11
14
  export {};
12
15
  //# sourceMappingURL=bridge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAGL,KAAK,UAAU,EAChB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,UAAU,YAAY;IACpB,MAAM,CACJ,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,aAAa,EACtB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,CAAC;IACvB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B;AAyED,wBAAgB,YAAY,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,YAAY,CAIpE"}
1
+ {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAGL,KAAK,UAAU,EAChB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,MAAM,MAAM,aAAa,GAAG;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,UAAU,YAAY;IACpB,MAAM,CACJ,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,aAAa,EACtB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,CAAC;IACvB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B;AA2ED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,GAAG,QAAQ,EACzB,OAAO,CAAC,EAAE,aAAa,GACtB,YAAY,CAKd"}
@@ -1,3 +1,578 @@
1
- import{a as E}from"./bridge.browser.mjs";import"./chunk-szbj3b6y.js";import"./chunk-bhj61bkd.js";var y=null;async function I(q,j,v){if(!y)y=E("worker");return y.resize(q,j,v)}function J(q="worker"){let j=E(q);return Object.assign((v,F,G)=>{return j.resize(v,F,G)},{terminate:async()=>{await j.terminate()}})}export{I as resize,J as createResizer};
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
2
12
 
3
- //# debugId=47A764035D06186864756E2164756E21
13
+ // ../runtime/src/env.ts
14
+ function isBun() {
15
+ return typeof Bun !== "undefined";
16
+ }
17
+
18
+ // ../runtime/src/worker-call.ts
19
+ async function callWorker(worker, type, payload, signal, transfer) {
20
+ return new Promise((resolve, reject) => {
21
+ const id = ++requestId;
22
+ if (signal?.aborted) {
23
+ reject(new DOMException("Aborted", "AbortError"));
24
+ return;
25
+ }
26
+ const handleMessage = (event) => {
27
+ const response = event.data;
28
+ if (response.id !== id)
29
+ return;
30
+ cleanup();
31
+ if (response.ok && response.data !== undefined) {
32
+ resolve(response.data);
33
+ } else {
34
+ reject(new Error(response.error || "Unknown worker error"));
35
+ }
36
+ };
37
+ const handleError = (error) => {
38
+ cleanup();
39
+ reject(new Error(`Worker error: ${error.message}`));
40
+ };
41
+ const handleAbort = () => {
42
+ cleanup();
43
+ reject(new DOMException("Aborted", "AbortError"));
44
+ };
45
+ const cleanup = () => {
46
+ worker.removeEventListener("message", handleMessage);
47
+ worker.removeEventListener("error", handleError);
48
+ signal?.removeEventListener("abort", handleAbort);
49
+ };
50
+ worker.addEventListener("message", handleMessage);
51
+ worker.addEventListener("error", handleError);
52
+ signal?.addEventListener("abort", handleAbort);
53
+ const request = { type, id, payload };
54
+ if (transfer && transfer.length > 0) {
55
+ worker.postMessage(request, transfer);
56
+ } else {
57
+ worker.postMessage(request);
58
+ }
59
+ });
60
+ }
61
+ var requestId = 0;
62
+
63
+ // ../runtime/src/worker-helper.ts
64
+ function createCodecWorker(workerFilename, options) {
65
+ const normalizedName = workerFilename.endsWith(".js") ? workerFilename : `${workerFilename}.js`;
66
+ const workerMap = {
67
+ "resize.worker.js": {
68
+ package: "@squoosh-kit/resize",
69
+ specifier: "resize.worker.js"
70
+ },
71
+ "webp.worker.js": {
72
+ package: "@squoosh-kit/webp",
73
+ specifier: "webp.worker.js"
74
+ }
75
+ };
76
+ const workerConfig = workerMap[normalizedName];
77
+ if (!workerConfig) {
78
+ throw new Error(`Unknown worker: ${normalizedName}. ` + `Supported workers: ${Object.keys(workerMap).join(", ")}`);
79
+ }
80
+ try {
81
+ if (typeof window !== "undefined") {
82
+ const packageName = workerConfig.package.split("/")[1];
83
+ const workerFile = normalizedName.replace(".js", ".browser.mjs");
84
+ console.log(`[worker-helper] In browser environment. Trying to create worker:`);
85
+ console.log(`[worker-helper] - Package Name: ${packageName}`);
86
+ console.log(`[worker-helper] - Worker File: ${workerFile}`);
87
+ if (options?.assetPath) {
88
+ const workerUrl = `${window.location.origin}${options.assetPath}${packageName}/${workerFile}`;
89
+ console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`);
90
+ try {
91
+ return new Worker(workerUrl, { type: "module" });
92
+ } catch (e) {
93
+ console.error(`[worker-helper] CRITICAL: new Worker() failed synchronously for URL: ${workerUrl}`, e);
94
+ throw e;
95
+ }
96
+ }
97
+ const pathStrategies = [
98
+ `../../${packageName}/dist/${workerFile}`,
99
+ `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,
100
+ `../../../${packageName}/dist/${workerFile}`
101
+ ];
102
+ let lastError = null;
103
+ for (const relPath of pathStrategies) {
104
+ try {
105
+ const workerUrl = new URL(relPath, import.meta.url);
106
+ console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`);
107
+ const worker = new Worker(workerUrl, {
108
+ type: "module"
109
+ });
110
+ console.log(`[worker-helper] Successfully created worker with URL: ${workerUrl.href}`);
111
+ return worker;
112
+ } catch (error) {
113
+ console.warn(`[worker-helper] Path strategy failed for ${relPath}:`, error);
114
+ lastError = error instanceof Error ? error : new Error(String(error));
115
+ }
116
+ }
117
+ if (lastError) {
118
+ console.error("[worker-helper] All path strategies failed.", lastError);
119
+ throw lastError;
120
+ }
121
+ throw new Error(`Could not resolve worker ${normalizedName} using any available path strategy`);
122
+ }
123
+ const platformExt = isBun() ? ".bun.js" : ".node.mjs";
124
+ const baseName = normalizedName.replace(".js", "");
125
+ const srcRelPath = workerConfig.package.includes("resize") ? `../../resize/src/${baseName}.ts` : `../../webp/src/${baseName}.ts`;
126
+ try {
127
+ return new Worker(new URL(srcRelPath, import.meta.url), {
128
+ type: "module"
129
+ });
130
+ } catch {
131
+ const distRelPath = workerConfig.package.includes("resize") ? `../../resize/dist/${baseName}.${platformExt.slice(1)}` : `../../webp/dist/${baseName}.${platformExt.slice(1)}`;
132
+ try {
133
+ return new Worker(new URL(distRelPath, import.meta.url), {
134
+ type: "module"
135
+ });
136
+ } catch {
137
+ if (typeof import.meta.resolve === "function") {
138
+ try {
139
+ const resolved = import.meta.resolve(`${workerConfig.package}/${workerConfig.specifier}`);
140
+ return new Worker(resolved, { type: "module" });
141
+ } catch {}
142
+ }
143
+ }
144
+ }
145
+ throw new Error(`Failed to create worker from ${normalizedName}. ` + `Tried TypeScript source, dist output, and import.meta.resolve. ` + `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`);
146
+ } catch (error) {
147
+ const errorMessage = error instanceof Error ? error.message : String(error);
148
+ throw new Error(`Failed to create worker from ${normalizedName}: ${errorMessage}. ` + `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.`);
149
+ }
150
+ }
151
+ function createReadyWorker(workerFilename, options, timeoutMs = 1e4) {
152
+ return new Promise((resolve, reject) => {
153
+ const timeout = setTimeout(() => {
154
+ reject(new Error(`Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`));
155
+ }, timeoutMs);
156
+ let worker;
157
+ try {
158
+ worker = createCodecWorker(workerFilename, options);
159
+ } catch (error) {
160
+ clearTimeout(timeout);
161
+ reject(error);
162
+ return;
163
+ }
164
+ const handleMessage = (event) => {
165
+ if (event.data?.type === "worker:ready") {
166
+ clearTimeout(timeout);
167
+ worker.removeEventListener("message", handleMessage);
168
+ worker.removeEventListener("error", handleError);
169
+ worker.removeEventListener("messageerror", handleMessageError);
170
+ resolve(worker);
171
+ }
172
+ };
173
+ const handleError = (event) => {
174
+ clearTimeout(timeout);
175
+ worker.removeEventListener("message", handleMessage);
176
+ worker.removeEventListener("error", handleError);
177
+ worker.removeEventListener("messageerror", handleMessageError);
178
+ reject(new Error(`Worker failed to start: ${event?.message || "Unknown error"}. Worker file: ${workerFilename}`));
179
+ };
180
+ const handleMessageError = () => {
181
+ clearTimeout(timeout);
182
+ worker.removeEventListener("message", handleMessage);
183
+ worker.removeEventListener("error", handleError);
184
+ worker.removeEventListener("messageerror", handleMessageError);
185
+ reject(new Error(`Worker message error during initialization. Worker file: ${workerFilename}`));
186
+ };
187
+ worker.addEventListener("message", handleMessage);
188
+ worker.addEventListener("error", handleError);
189
+ worker.addEventListener("messageerror", handleMessageError);
190
+ worker.postMessage({ type: "worker:ping" });
191
+ });
192
+ }
193
+ var init_worker_helper = () => {};
194
+
195
+ // ../runtime/src/wasm-loader.ts
196
+ async function loadWasmBinary(relativePath, baseUrlOverride) {
197
+ const baseUrl = baseUrlOverride ? typeof baseUrlOverride === "string" ? new URL(".", baseUrlOverride) : new URL(".", baseUrlOverride.href) : new URL(".", import.meta.url);
198
+ const fullUrl = new URL(relativePath, baseUrl);
199
+ console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);
200
+ console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);
201
+ console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);
202
+ try {
203
+ const response = await fetch(fullUrl.href);
204
+ console.log(`[WasmLoader] Fetch response status for ${fullUrl.href}: ${response.status}`);
205
+ if (!response.ok) {
206
+ const responseText = await response.text();
207
+ console.error(`[WasmLoader] Fetch response text (first 500 chars):`, responseText.substring(0, 500));
208
+ throw new Error(`Failed to fetch WASM module at ${fullUrl.href}: ${response.status} ${response.statusText}`);
209
+ }
210
+ const contentType = response.headers.get("content-type");
211
+ console.log(`[WasmLoader] Response Content-Type: ${contentType}`);
212
+ if (!contentType || !contentType.includes("application/wasm")) {
213
+ console.warn(`[WasmLoader] Warning: WASM module at ${fullUrl.href} served with incorrect MIME type: "${contentType}". Should be "application/wasm".`);
214
+ }
215
+ return await response.arrayBuffer();
216
+ } catch (error) {
217
+ console.error(`[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`, error);
218
+ throw error;
219
+ }
220
+ }
221
+
222
+ // ../runtime/src/validators.ts
223
+ function validateImageInput(image) {
224
+ if (!image || typeof image !== "object") {
225
+ throw new TypeError("image must be an object");
226
+ }
227
+ const imageObj = image;
228
+ if (!("data" in imageObj)) {
229
+ throw new TypeError("image.data is required");
230
+ }
231
+ const { data } = imageObj;
232
+ if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {
233
+ throw new TypeError("image.data must be Uint8Array or Uint8ClampedArray");
234
+ }
235
+ if (!("width" in imageObj) || !("height" in imageObj)) {
236
+ throw new TypeError("image.width and image.height are required");
237
+ }
238
+ const { width, height } = imageObj;
239
+ if (typeof width !== "number" || !Number.isInteger(width) || width <= 0) {
240
+ throw new RangeError(`image.width must be a positive integer, got ${width}`);
241
+ }
242
+ if (typeof height !== "number" || !Number.isInteger(height) || height <= 0) {
243
+ throw new RangeError(`image.height must be a positive integer, got ${height}`);
244
+ }
245
+ const expectedSize = width * height * 4;
246
+ if (data.length < expectedSize) {
247
+ throw new RangeError(`image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`);
248
+ }
249
+ }
250
+ // ../runtime/src/simd-detector.ts
251
+ var init_simd_detector = () => {};
252
+
253
+ // ../runtime/src/index.ts
254
+ var init_src = __esm(() => {
255
+ init_worker_helper();
256
+ init_simd_detector();
257
+ });
258
+
259
+ // src/validators.ts
260
+ function validateResizeOptions(options) {
261
+ if (typeof options !== "object" || options === null) {
262
+ throw new TypeError("options must be an object");
263
+ }
264
+ const opts = options;
265
+ if (opts.width !== undefined) {
266
+ if (typeof opts.width !== "number" || !Number.isInteger(opts.width) || opts.width <= 0) {
267
+ throw new RangeError(`options.width must be a positive integer, got ${opts.width}`);
268
+ }
269
+ }
270
+ if (opts.height !== undefined) {
271
+ if (typeof opts.height !== "number" || !Number.isInteger(opts.height) || opts.height <= 0) {
272
+ throw new RangeError(`options.height must be a positive integer, got ${opts.height}`);
273
+ }
274
+ }
275
+ if (opts.method !== undefined) {
276
+ const validMethods = ["triangular", "catrom", "mitchell", "lanczos3"];
277
+ if (!validMethods.includes(opts.method)) {
278
+ throw new TypeError(`options.method must be one of: ${validMethods.join(", ")}, got ${opts.method}`);
279
+ }
280
+ }
281
+ if (opts.premultiply !== undefined && typeof opts.premultiply !== "boolean") {
282
+ throw new TypeError(`options.premultiply must be boolean, got ${typeof opts.premultiply}`);
283
+ }
284
+ if (opts.linearRGB !== undefined && typeof opts.linearRGB !== "boolean") {
285
+ throw new TypeError(`options.linearRGB must be boolean, got ${typeof opts.linearRGB}`);
286
+ }
287
+ }
288
+
289
+ // wasm/squoosh_resize.js
290
+ function getUint8Memory0() {
291
+ if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
292
+ cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
293
+ }
294
+ return cachegetUint8Memory0;
295
+ }
296
+ function passArray8ToWasm0(arg, malloc) {
297
+ const ptr = malloc(arg.length * 1);
298
+ getUint8Memory0().set(arg, ptr / 1);
299
+ WASM_VECTOR_LEN = arg.length;
300
+ return ptr;
301
+ }
302
+ function getInt32Memory0() {
303
+ if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
304
+ cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
305
+ }
306
+ return cachegetInt32Memory0;
307
+ }
308
+ function getUint8ClampedMemory0() {
309
+ if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
310
+ cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
311
+ }
312
+ return cachegetUint8ClampedMemory0;
313
+ }
314
+ function getClampedArrayU8FromWasm0(ptr, len) {
315
+ return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
316
+ }
317
+ function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {
318
+ try {
319
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
320
+ var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);
321
+ var len0 = WASM_VECTOR_LEN;
322
+ wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);
323
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
324
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
325
+ var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();
326
+ wasm.__wbindgen_free(r0, r1 * 1);
327
+ return v1;
328
+ } finally {
329
+ wasm.__wbindgen_add_to_stack_pointer(16);
330
+ }
331
+ }
332
+ async function load(module, imports) {
333
+ if (typeof Response === "function" && module instanceof Response) {
334
+ if (typeof WebAssembly.instantiateStreaming === "function") {
335
+ try {
336
+ return await WebAssembly.instantiateStreaming(module, imports);
337
+ } catch (e) {
338
+ if (module.headers.get("Content-Type") != "application/wasm") {
339
+ 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);
340
+ } else {
341
+ throw e;
342
+ }
343
+ }
344
+ }
345
+ const bytes = await module.arrayBuffer();
346
+ return await WebAssembly.instantiate(bytes, imports);
347
+ } else {
348
+ const instance = await WebAssembly.instantiate(module, imports);
349
+ if (instance instanceof WebAssembly.Instance) {
350
+ return { instance, module };
351
+ } else {
352
+ return instance;
353
+ }
354
+ }
355
+ }
356
+ async function init(input) {
357
+ if (typeof input === "undefined") {
358
+ input = new URL("squoosh_resize_bg.wasm", import.meta.url);
359
+ }
360
+ const imports = {};
361
+ if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
362
+ input = fetch(input);
363
+ }
364
+ const { instance, module } = await load(await input, imports);
365
+ wasm = instance.exports;
366
+ init.__wbindgen_wasm_module = module;
367
+ return wasm;
368
+ }
369
+ var wasm, cachegetUint8Memory0 = null, WASM_VECTOR_LEN = 0, cachegetInt32Memory0 = null, cachegetUint8ClampedMemory0 = null, squoosh_resize_default;
370
+ var init_squoosh_resize = __esm(() => {
371
+ squoosh_resize_default = init;
372
+ });
373
+
374
+ // src/resize.worker.ts
375
+ var exports_resize_worker = {};
376
+ __export(exports_resize_worker, {
377
+ resizeClient: () => resizeClient
378
+ });
379
+ async function init2() {
380
+ if (wasmResize) {
381
+ return;
382
+ }
383
+ if (initPromise) {
384
+ return initPromise;
385
+ }
386
+ initPromise = (async () => {
387
+ try {
388
+ let wasmBuffer = null;
389
+ const pathsToTry = [
390
+ new URL("./wasm/squoosh_resize_bg.wasm", import.meta.url).href,
391
+ new URL("../wasm/squoosh_resize_bg.wasm", import.meta.url).href
392
+ ];
393
+ let lastError = null;
394
+ for (const path of pathsToTry) {
395
+ try {
396
+ wasmBuffer = await loadWasmBinary(path);
397
+ break;
398
+ } catch (error) {
399
+ lastError = error instanceof Error ? error : new Error(String(error));
400
+ }
401
+ }
402
+ if (!wasmBuffer) {
403
+ throw lastError || new Error("Could not load WASM binary from any path");
404
+ }
405
+ try {
406
+ await squoosh_resize_default(wasmBuffer);
407
+ } catch (initError) {
408
+ if (initError instanceof Error && (initError.message.includes("SharedArrayBuffer") || initError.message.includes("first argument must be"))) {
409
+ if (typeof SharedArrayBuffer === "undefined") {
410
+ globalThis.SharedArrayBuffer = ArrayBuffer;
411
+ }
412
+ try {
413
+ await squoosh_resize_default(wasmBuffer);
414
+ } catch (retryError) {
415
+ throw new Error(`WASM module initialization failed even with polyfill: ${retryError instanceof Error ? retryError.message : String(retryError)}`);
416
+ }
417
+ } else {
418
+ throw initError;
419
+ }
420
+ }
421
+ wasmResize = resize;
422
+ } catch (error) {
423
+ initPromise = null;
424
+ throw new Error(`Failed to initialize resize WASM module: ${error instanceof Error ? error.message : String(error)}`);
425
+ }
426
+ })();
427
+ return initPromise;
428
+ }
429
+ async function _resizeCore(image, options) {
430
+ validateImageInput(image);
431
+ validateResizeOptions(options);
432
+ await init2();
433
+ if (!wasmResize) {
434
+ throw new Error("Resize module not initialized");
435
+ }
436
+ const { data, width: inputWidth, height: inputHeight } = image;
437
+ let outputWidth = options.width ?? inputWidth;
438
+ let outputHeight = options.height ?? inputHeight;
439
+ if (options.width && !options.height) {
440
+ outputHeight = Math.max(1, Math.round(inputHeight * options.width / inputWidth));
441
+ } else if (options.height && !options.width) {
442
+ outputWidth = Math.max(1, Math.round(inputWidth * options.height / inputHeight));
443
+ }
444
+ if (outputWidth < 1 || outputHeight < 1) {
445
+ throw new RangeError(`Output dimensions must be at least 1x1, got ${outputWidth}x${outputHeight}`);
446
+ }
447
+ const dataArray = data instanceof Uint8ClampedArray ? new Uint8Array(data.buffer, data.byteOffset, data.length) : new Uint8Array(data.buffer, data.byteOffset, data.length);
448
+ const result = wasmResize(dataArray, inputWidth, inputHeight, outputWidth, outputHeight, getResizeMethod(options), options.premultiply ?? true, options.linearRGB ?? true);
449
+ return {
450
+ data: result,
451
+ width: outputWidth,
452
+ height: outputHeight
453
+ };
454
+ }
455
+ async function resizeClient(image, options, signal) {
456
+ if (signal?.aborted) {
457
+ throw new DOMException("Aborted", "AbortError");
458
+ }
459
+ return _resizeCore(image, options);
460
+ }
461
+ function getResizeMethod(options) {
462
+ const methodMap = {
463
+ triangular: 0,
464
+ catrom: 1,
465
+ mitchell: 2,
466
+ lanczos3: 3
467
+ };
468
+ return methodMap[options?.method ?? "lanczos3"] ?? 3;
469
+ }
470
+ var wasmResize = null, initPromise = null;
471
+ var init_resize_worker = __esm(() => {
472
+ init_src();
473
+ init_squoosh_resize();
474
+ if (typeof self !== "undefined") {
475
+ self.onmessage = async (event) => {
476
+ const data = event.data;
477
+ if (data?.type === "worker:ping") {
478
+ self.postMessage({ type: "worker:ready" });
479
+ return;
480
+ }
481
+ const { id, type, payload } = data;
482
+ const response = { id, ok: false };
483
+ try {
484
+ if (type !== "resize:run") {
485
+ throw new Error(`Unknown message type: ${type}`);
486
+ }
487
+ const resultImage = await _resizeCore(payload.image, payload.options);
488
+ response.ok = true;
489
+ response.data = resultImage;
490
+ self.postMessage(response);
491
+ } catch (error) {
492
+ response.error = error instanceof Error ? error.message : String(error);
493
+ self.postMessage(response);
494
+ }
495
+ };
496
+ }
497
+ });
498
+
499
+ // src/bridge.ts
500
+ init_src();
501
+ init_src();
502
+
503
+ class ResizeClientBridge {
504
+ async resize(image, options, signal) {
505
+ const module = await Promise.resolve().then(() => (init_resize_worker(), exports_resize_worker));
506
+ const resizeClient2 = module.resizeClient;
507
+ return resizeClient2(image, options, signal);
508
+ }
509
+ async terminate() {}
510
+ }
511
+
512
+ class ResizeWorkerBridge {
513
+ worker = null;
514
+ workerReady = null;
515
+ options;
516
+ constructor(options) {
517
+ this.options = options;
518
+ }
519
+ async getWorker() {
520
+ if (!this.workerReady) {
521
+ this.workerReady = this.createWorker();
522
+ }
523
+ return this.workerReady;
524
+ }
525
+ async createWorker() {
526
+ this.worker = await createReadyWorker("resize.worker.js", this.options);
527
+ return this.worker;
528
+ }
529
+ async resize(image, options, signal) {
530
+ const worker = await this.getWorker();
531
+ validateImageInput(image);
532
+ try {
533
+ const result = await callWorker(worker, "resize:run", { image, options }, signal);
534
+ return result;
535
+ } catch (error) {
536
+ console.error("Resize error:", error);
537
+ throw error;
538
+ }
539
+ }
540
+ async terminate() {
541
+ if (this.worker) {
542
+ this.worker.terminate();
543
+ this.worker = null;
544
+ this.workerReady = null;
545
+ }
546
+ }
547
+ }
548
+ function createBridge(mode, options) {
549
+ if (mode === "worker") {
550
+ return new ResizeWorkerBridge(options);
551
+ }
552
+ return new ResizeClientBridge;
553
+ }
554
+
555
+ // src/index.ts
556
+ var globalClientBridge = null;
557
+ async function resize2(imageData, options, signal) {
558
+ if (!globalClientBridge) {
559
+ globalClientBridge = createBridge("worker");
560
+ }
561
+ return globalClientBridge.resize(imageData, options, signal);
562
+ }
563
+ function createResizer(mode = "worker", options) {
564
+ const bridge = createBridge(mode, options);
565
+ return Object.assign((imageData, options2, signal) => {
566
+ return bridge.resize(imageData, options2, signal);
567
+ }, {
568
+ terminate: async () => {
569
+ await bridge.terminate();
570
+ }
571
+ });
572
+ }
573
+ export {
574
+ resize2 as resize,
575
+ createResizer
576
+ };
577
+
578
+ //# debugId=2417787C6196306664756E2164756E21