@keeratita/heic-converter 0.5.0 → 0.5.2

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/index.d.ts CHANGED
@@ -346,8 +346,60 @@ interface WorkerResultMessage {
346
346
  error?: string;
347
347
  }
348
348
  /**
349
- * Converts a HEIC image inside a Web Worker so the main thread stays
350
- * responsive during the (potentially slow) WASM decode.
349
+ * Options for {@link convertManyInWorker}: the {@link convertHeicInWorker}
350
+ * worker options plus the batch semantics of `convertMany`.
351
+ */
352
+ interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
353
+ /**
354
+ * Per-item progress callback: receives the 0-based item index and its
355
+ * progress percentage (normalized 0–100). Fires only for successful items.
356
+ */
357
+ onProgress?: (index: number, percent: number) => void;
358
+ /**
359
+ * Resolve with per-item results instead of rejecting the batch on the
360
+ * first failure; all items run to completion (see
361
+ * `ConvertManyOptions.continueOnError`).
362
+ * @default false
363
+ */
364
+ continueOnError?: boolean;
365
+ }
366
+
367
+ /**
368
+ * Stable, machine-readable error codes attached to every error the library
369
+ * throws (as `HeicConverterError.code`). Codes are part of the public API:
370
+ * they are additive-only and never repurposed, so callers can branch on
371
+ * `error.code` instead of matching on message strings.
372
+ */
373
+ type HeicConverterErrorCode = 'invalid_input' | 'invalid_quality' | 'invalid_resize' | 'invalid_format' | 'invalid_crop' | 'invalid_concurrency' | 'decoder_init_failed' | 'decode_failed' | 'progress_callback_failed' | 'render_encode_failed' | 'unsupported_environment' | 'format_unsupported' | 'aborted' | 'worker_unsupported' | 'worker_load_failed' | 'worker_create_failed' | 'worker_post_failed' | 'worker_failed' | 'worker_timeout' | 'batch_item_failed';
374
+ /**
375
+ * Error thrown by all first-party code paths. Extends `Error` so existing
376
+ * `instanceof Error` / message-based handling keeps working; the `code`
377
+ * (and, for batch failures, `itemIndex`/`itemTotal`/`failedCount`) fields
378
+ * add a structured discriminator without changing message text.
379
+ */
380
+ declare class HeicConverterError extends Error {
381
+ readonly code: HeicConverterErrorCode;
382
+ /** 0-based index of the failing input. Only set on `batch_item_failed` errors. */
383
+ readonly itemIndex?: number;
384
+ /** Total number of inputs in the batch. Only set on `batch_item_failed` errors. */
385
+ readonly itemTotal?: number;
386
+ /** How many items failed overall. Only set on `batch_item_failed` errors. */
387
+ readonly failedCount?: number;
388
+ constructor(code: HeicConverterErrorCode, message: string, options?: {
389
+ cause?: unknown;
390
+ itemIndex?: number;
391
+ itemTotal?: number;
392
+ failedCount?: number;
393
+ });
394
+ }
395
+
396
+ /**
397
+ * Converts a HEIC image inside a Web Worker so the main thread stays responsive
398
+ * during the (potentially slow) WASM decode. This is the public entry point; the
399
+ * implementation lives in `src/worker.ts` and is fetched as a lazy chunk on the
400
+ * first call, so a deployment missing that chunk rejects with
401
+ * `worker_load_failed` (original failure on `cause`) rather than a raw
402
+ * module-load error.
351
403
  *
352
404
  * The worker script is user-provided and must handle the following message
353
405
  * protocol (types are exported as {@link WorkerProgressMessage} and
@@ -380,14 +432,23 @@ interface WorkerResultMessage {
380
432
  * });
381
433
  * ```
382
434
  *
383
- * Only `progress` and `result` messages are understood; any other message
384
- * type is ignored (the first unknown type is reported in the timeout
385
- * diagnostic). Use `workerType: 'module'` when the script uses ES module
386
- * imports (as in the example above); `'classic'` scripts must be
387
- * pre-bundled, since static ES imports are not supported there.
435
+ * Only `progress` and `result` messages are understood; any other message type
436
+ * is ignored (the first unknown type is reported in the timeout diagnostic).
437
+ * Use `workerType: 'module'` when the script uses ES module imports (as above);
438
+ * `'classic'` scripts must be pre-bundled, since static ES imports are not
439
+ * supported there.
388
440
  *
389
- * The `decoder` option is rejected: class instances cannot cross the
390
- * worker boundary; the worker creates its own decoder.
441
+ * Notes that are easy to trip over:
442
+ * - `decoder` is rejected — class instances cannot cross the worker boundary,
443
+ * so the worker creates its own.
444
+ * - `timeoutMs` is a per-call deadline that **includes queueing** for a free
445
+ * worker slot, not just the conversion itself.
446
+ * - An error raised *inside* the worker comes back stringified under
447
+ * `worker_failed`: the numeric `code` does not survive the boundary, so match
448
+ * on the message. Option validation happens here instead, so an invalid
449
+ * option keeps its own code.
450
+ * - Workers are pooled per `workerUrl`, so concurrent callers to the same URL
451
+ * share one bounded set rather than spawning unbounded workers.
391
452
  *
392
453
  * @param input HEIC image as a Blob, File, ArrayBuffer, or Uint8Array.
393
454
  * @param options Conversion options plus the worker script URL.
@@ -398,33 +459,16 @@ declare function convertHeicInWorker<S extends OutputShape = 'blob'>(input: Heic
398
459
  output?: S;
399
460
  }): Promise<ConvertResult<S>>;
400
461
  /**
401
- * Options for {@link convertManyInWorker}: the {@link convertHeicInWorker}
402
- * worker options plus the batch semantics of `convertMany`.
403
- */
404
- interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
405
- /**
406
- * Per-item progress callback: receives the 0-based item index and its
407
- * progress percentage (normalized 0–100). Fires only for successful items.
408
- */
409
- onProgress?: (index: number, percent: number) => void;
410
- /**
411
- * Resolve with per-item results instead of rejecting the batch on the
412
- * first failure; all items run to completion (see
413
- * `ConvertManyOptions.continueOnError`).
414
- * @default false
415
- */
416
- continueOnError?: boolean;
417
- }
418
- /**
419
- * Converts multiple HEIC images inside Web Workers, mirroring
420
- * {@link convertMany} semantics (input order, bounded concurrency,
421
- * `batch_item_failed` aggregation or `continueOnError` per-item results).
422
- * Concurrency is bounded by `maxConcurrentWorkers` (default
423
- * `navigator.hardwareConcurrency` clamped to 1–8): items queue behind the
424
- * worker semaphore, so a large batch never exhausts memory or the browser's
425
- * worker limit. Each item runs in its own worker instance via
426
- * {@link convertHeicInWorker}, which means `decoder` cannot be injected and
427
- * `workerUrl` is required.
462
+ * Converts multiple HEIC images inside Web Workers, mirroring {@link convertMany}
463
+ * semantics (input order, bounded concurrency, `batch_item_failed` aggregation
464
+ * or `continueOnError` per-item results). Concurrency is bounded by
465
+ * `maxConcurrentWorkers` (default `navigator.hardwareConcurrency` clamped to
466
+ * 1–8): items queue behind the worker semaphore, so a large batch never
467
+ * exhausts memory or the browser's worker limit. Each item runs in its own
468
+ * worker instance via {@link convertHeicInWorker}, which means `decoder` cannot
469
+ * be injected and `workerUrl` is required. See that function for the worker
470
+ * script protocol and the caveats about `timeoutMs`, the worker boundary, and
471
+ * `worker_load_failed`.
428
472
  *
429
473
  * ```ts
430
474
  * const blobs = await convertManyInWorker(heicFiles, {
@@ -435,6 +479,10 @@ interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
435
479
  * });
436
480
  * ```
437
481
  *
482
+ * Overloads must mirror `convertManyInWorker` in `src/worker.ts`: the deferred
483
+ * call below erases the union, so drift here is a public typing bug that `tsc`,
484
+ * the unit tests and the bundle guard all fail to catch.
485
+ *
438
486
  * @param inputs HEIC images as Blobs, Files, ArrayBuffers, or Uint8Arrays.
439
487
  * @param options Batch + worker conversion options (see {@link WorkerBatchOptions}).
440
488
  * @returns The converted images in input order, or per-item result entries
@@ -453,35 +501,6 @@ declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: Hei
453
501
  continueOnError: boolean;
454
502
  }): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
455
503
 
456
- /**
457
- * Stable, machine-readable error codes attached to every error the library
458
- * throws (as `HeicConverterError.code`). Codes are part of the public API:
459
- * they are additive-only and never repurposed, so callers can branch on
460
- * `error.code` instead of matching on message strings.
461
- */
462
- type HeicConverterErrorCode = 'invalid_input' | 'invalid_quality' | 'invalid_resize' | 'invalid_format' | 'invalid_crop' | 'invalid_concurrency' | 'decoder_init_failed' | 'decode_failed' | 'progress_callback_failed' | 'render_encode_failed' | 'unsupported_environment' | 'format_unsupported' | 'aborted' | 'worker_unsupported' | 'worker_create_failed' | 'worker_post_failed' | 'worker_failed' | 'worker_timeout' | 'batch_item_failed';
463
- /**
464
- * Error thrown by all first-party code paths. Extends `Error` so existing
465
- * `instanceof Error` / message-based handling keeps working; the `code`
466
- * (and, for batch failures, `itemIndex`/`itemTotal`/`failedCount`) fields
467
- * add a structured discriminator without changing message text.
468
- */
469
- declare class HeicConverterError extends Error {
470
- readonly code: HeicConverterErrorCode;
471
- /** 0-based index of the failing input. Only set on `batch_item_failed` errors. */
472
- readonly itemIndex?: number;
473
- /** Total number of inputs in the batch. Only set on `batch_item_failed` errors. */
474
- readonly itemTotal?: number;
475
- /** How many items failed overall. Only set on `batch_item_failed` errors. */
476
- readonly failedCount?: number;
477
- constructor(code: HeicConverterErrorCode, message: string, options?: {
478
- cause?: unknown;
479
- itemIndex?: number;
480
- itemTotal?: number;
481
- failedCount?: number;
482
- });
483
- }
484
-
485
504
  /**
486
505
  * Releases any cached decoder resources.
487
506
  *
package/dist/index.js CHANGED
@@ -1,3 +1 @@
1
- 'use strict';var s={QualityInvalid:e=>`Quality must be a number between 0.0 and 1.0, got: ${e}`,ApplyOrientationInvalid:e=>`applyOrientation must be a boolean, got: ${e}`,UnsupportedInputType:e=>`Unsupported input type. Expected Blob, File, ArrayBuffer, or Uint8Array. Got: ${e}`,DecoderInitFailed:e=>`Failed to initialize HEIC decoder: ${e} \u2014 verify heic-decoder.wasm is served (dist/heic-decoder.wasm; see the README "Serving and Locating WASM" section / locateFile option) and that your CSP allows 'wasm-unsafe-eval'`,RenderEncodeFailed:(e,r)=>`Failed to render and encode image as ${e}: ${r}`,ConcurrencyInvalid:e=>`Concurrency must be a positive integer, got: ${e}`,MaxConcurrentWorkersInvalid:e=>`maxConcurrentWorkers must be a positive integer, got: ${e}`,TimeoutInvalid:e=>`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${e}`,InputsMustBeArray:"Inputs must be an array of HEIC images",OutputShapeInvalid:e=>`output must be one of 'blob', 'dataUrl', 'arrayBuffer', got: ${e}`,ReuseDecodersInvalid:e=>`reuseDecoders must be a boolean, got: ${e}`,ContinueOnErrorInvalid:e=>`continueOnError must be a boolean, got: ${e}`,PreserveExifInvalid:e=>`preserveExif must be a boolean, got: ${e}`,SignalInvalid:e=>`signal must be an AbortSignal, got: ${e}`,Aborted:"Conversion aborted (AbortSignal was aborted)",ConvertManyItemFailed:(e,r,t)=>`Conversion of item ${e} of ${r} failed: ${t}`,ConvertManyExtraFailures:(e,r)=>` (${e} of ${r} items failed in total)`,ConvertManyOtherErrors:e=>`; other errors: ${e.join(" | ")}`,BatchItemProducedNoResult:e=>`Item ${String(e)} produced no result`,BatchEndedWithoutResult:"Batch ended without a result",ScaleInvalid:e=>`Scale must be a positive finite number, got: ${e}`,MaxWidthInvalid:e=>`maxWidth must be a positive finite number, got: ${e}`,MaxHeightInvalid:e=>`maxHeight must be a positive finite number, got: ${e}`,TargetSizeTooLarge:(e,r,t)=>`Target image size ${e}x${r} exceeds the maximum supported dimension of ${t}px`,BlobToBase64Failed:"Failed to convert Blob to base64 string",BlobToBase64FailedWithCause:e=>`Failed to convert Blob to base64 string: ${e}`,CanvasToBlobFailed:e=>`Failed to convert canvas to blob (type: ${e})`,CanvasUnsupported:"Canvas is not supported in the current environment. In a browser this requires OffscreenCanvas or HTMLCanvasElement. In Node.js there is no canvas: decode raw RGBA with LibheifDecoder and encode externally (see the Node.js section of the README).",InvalidDimensions:(e,r)=>`Invalid image dimensions: ${e}x${r}. Width and height must be positive integers.`,DataLengthMismatch:(e,r,t,n)=>`Image data length mismatch. Expected ${e} bytes for ${r}x${t}, got ${n}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' \u2014 canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,r)=>`crop.${e} must be ${e==="width"||e==="height"?"a positive integer":"a non-negative integer"}, got: ${r}`,CropOutOfBounds:(e,r,t,n,o,i)=>`crop ${t}x${n} at (${e}, ${r}) exceeds the ${o}x${i} image (crop coordinates are in post-orientation display pixels)`,DecoderFreedDuringDecode:"Decoder was freed before decoding completed; call initialize() again.",DecodeInputAllocFailed:e=>`Failed to allocate ${e} bytes in the WASM heap for decode input`,DecodeFailed:e=>`HEIC decoding failed (no result returned; input: ${e} bytes \u2014 is the file truncated or empty?)`,DecodeFailedWithDetail:(e,r)=>`HEIC decoding failed: ${e} (input: ${r} bytes)`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`,WorkerUnsupported:"Web Worker is not supported in the current environment",WorkerCreateFailed:e=>`Failed to create Web Worker: ${e}`,WorkerPostFailed:e=>`Failed to post message to Web Worker: ${e}`,WorkerConversionFailed:"Worker conversion failed",WorkerDecoderUnsupported:"The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",WorkerFailed:e=>"Worker failed"+(e!==void 0?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:""),WorkerTimeout:(e,r)=>{let t=[`${r.progressMessages} progress message(s) received`];return r.lastPercent!==void 0&&t.push(`last percent ${r.lastPercent}`),r.unknownType!==void 0&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),r.workerUrl!==void 0&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`}};function T(e){let r=Number(e);return Number.isFinite(r)?Math.min(100,Math.max(0,r)):0}var a=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(r,t,n){super(t,{cause:n?.cause}),this.name="HeicConverterError",this.code=r,n?.itemIndex!==void 0&&(this.itemIndex=n.itemIndex),n?.itemTotal!==void 0&&(this.itemTotal=n.itemTotal),n?.failedCount!==void 0&&(this.failedCount=n.failedCount);}};var _=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(r){this.options=r;}async initialize(){if(!this.initPromise){let r=++this.initGeneration,t={};this.options?.moduleOverrides&&Object.assign(t,this.options.moduleOverrides),this.options?.locateFile&&(t.locateFile=this.options.locateFile),this.options?.wasmBinary&&(t.wasmBinary=this.options.wasmBinary);let n=import('./heic-decoder-7BA7NJOA.js').then(({default:o})=>o(t)).then(o=>{let i=new o.HeicDecoder;return r!==this.initGeneration?(i.delete(),null):(this.module=o,this.decoderInstance=i,o)}).catch(o=>{throw this.initPromise===n&&(this.initPromise=null),o});this.initPromise=n;}await this.initPromise;}async decode(r,t){if((!this.module||!this.decoderInstance)&&await this.initialize(),!this.module||!this.decoderInstance)throw new a("decode_failed",s.DecoderFreedDuringDecode);let n,o=t?O=>{try{t(T(O));}catch(k){n=n??k;}}:null,i=this.module,c=this.decoderInstance,u;if(typeof c.decodeFromPointer=="function"&&typeof i._malloc=="function"&&typeof i._free=="function"&&i.HEAPU8 instanceof Uint8Array&&r.buffer!==i.HEAPU8.buffer){let O=i._malloc(r.byteLength);if(O===0)throw new a("decode_failed",s.DecodeInputAllocFailed(r.byteLength));try{i.HEAPU8.set(r,O),u=c.decodeFromPointer(O,r.byteLength,o);}finally{i._free(O);}}else u=c.decode(r,o);if(typeof u=="string")throw new a("decode_failed",s.DecodeFailedWithDetail(u,r.byteLength));if(!u)throw new a("decode_failed",s.DecodeFailed(r.byteLength));if(n!==void 0)throw new a("progress_callback_failed",s.ProgressCallbackThrew(n instanceof Error?n.message:String(n)),{cause:n});let d=u.width,l=u.height,m=u.orientation,y=typeof m=="number"&&Number.isInteger(m)&&m>=1&&m<=8?m:1,h=i.HEAPU8 instanceof Uint8Array?i.HEAPU8.buffer:void 0,w=h!==void 0&&u.data.buffer!==h?new Uint8ClampedArray(u.data.buffer,u.data.byteOffset,u.data.byteLength):new Uint8ClampedArray(u.data),g={width:d,height:l,data:w};y>1&&(g.orientation=y);let p=u.exif;return p instanceof Uint8Array&&p.length>=14&&(g.exif=h!==void 0&&p.buffer!==h?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):new Uint8Array(p)),g}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,this.initPromise=null;}};var ie=["jpeg","jpg","png","svg","webp","avif"],Se=.92;function R(e){$(e?.to??"jpeg"),e?.quality!==void 0&&ke(e.quality),Ae(e?.applyOrientation),_e(e?.output),Te(e?.signal),X(e?.crop),Me(e?.preserveExif),Q(e?.maxWidth!==void 0||e?.maxHeight!==void 0||e?.scale!==void 0?e:void 0);}function ae(e){Y(e?.continueOnError),Pe(e?.reuseDecoders);}function ke(e){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)throw new a("invalid_quality",s.QualityInvalid(e))}function Ae(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ApplyOrientationInvalid(e))}function _e(e){if(e!==void 0&&e!=="blob"&&e!=="dataUrl"&&e!=="arrayBuffer")throw new a("invalid_input",s.OutputShapeInvalid(e))}function Pe(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ReuseDecodersInvalid(e))}function Y(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ContinueOnErrorInvalid(e))}function Me(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.PreserveExifInvalid(e))}function Te(e){if(e!==void 0&&(typeof e!="object"||e===null||typeof e.addEventListener!="function"))throw new a("invalid_input",s.SignalInvalid(e))}function U(e){if(e?.aborted)throw new a("aborted",s.Aborted)}function $(e){let r=String(e).toLowerCase();if(!ie.includes(r))throw new a("invalid_format",s.UnsupportedFormat(String(e)))}function Q(e){if(!e)return;let{maxWidth:r,maxHeight:t,scale:n}=e;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))throw new a("invalid_resize",s.ScaleInvalid(n));if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<=0))throw new a("invalid_resize",s.MaxWidthInvalid(r));if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<=0))throw new a("invalid_resize",s.MaxHeightInvalid(t))}function X(e){if(!e)return;let{x:r=0,y:t=0,width:n,height:o}=e;if(!Number.isInteger(n)||n<=0)throw new a("invalid_crop",s.CropInvalid("width",n));if(!Number.isInteger(o)||o<=0)throw new a("invalid_crop",s.CropInvalid("height",o));if(!Number.isInteger(r)||r<0)throw new a("invalid_crop",s.CropInvalid("x",r));if(!Number.isInteger(t)||t<0)throw new a("invalid_crop",s.CropInvalid("y",t))}function J(e){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new a("invalid_concurrency",s.MaxConcurrentWorkersInvalid(e))}function K(e){if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0))throw new a("invalid_input",s.TimeoutInvalid(e))}var B=new Uint8Array([69,120,105,102,0,0]),se=new Uint8Array([137,80,78,71,13,10,26,10]);function Z(e){if(e.length<B.length+8)return false;for(let r=0;r<B.length;r++)if(e[r]!==B[r])return false;return Re(e,B.length)}function Re(e,r){if(r+8>e.length)return false;let t=e[r]===73&&e[r+1]===73,n=e[r]===77&&e[r+1]===77;return !t&&!n?false:(t?e[r+2]|e[r+3]<<8:e[r+2]<<8|e[r+3])===42}function Ue(e,r){return e[r]<<8|e[r+1]}function ue(e,r){return (e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0}function de(e){try{if(!Z(e))return e;let r=B.length,t=e[r]===73,n=d=>t?e[d]|e[d+1]<<8:e[d]<<8|e[d+1],o=d=>t?(e[d+3]<<24|e[d+2]<<16|e[d+1]<<8|e[d])>>>0:(e[d]<<24|e[d+1]<<16|e[d+2]<<8|e[d+3])>>>0,i=o(r+4);if(i<8||r+i+2>e.length)return e;let c=r+i,u=n(c);for(let d=0;d<u;d++){let l=c+2+d*12;if(l+12>e.length)return e;if(n(l)!==274)continue;let m=n(l+2),y=o(l+4);if(m!==3||y!==1||(t?e[l+8]|e[l+9]<<8:e[l+8]<<8|e[l+9])===1)return e;let w=e.slice();return w[l+8]=t?1:0,w[l+9]=t?0:1,w[l+10]=0,w[l+11]=0,w}return e}catch{return e}}function ce(e,r){try{if(e.length<4||e[0]!==255||e[1]!==216||!Z(r))return e;let t=r.length+2;if(t>65535)return e;let n=2;for(;n<e.length;){if(n+4>e.length||e[n]!==255)return e;let i=e[n+1];if(i===255){n+=1;continue}if(!(i>=224&&i<=239||i===254))break;let u=Ue(e,n+2);if(u<2||n+2+u>e.length)return e;n+=2+u;}let o=new Uint8Array(e.length+4+r.length);return o.set(e.subarray(0,n),0),o[n]=255,o[n+1]=225,o[n+2]=t>>8&255,o[n+3]=t&255,o.set(r,n+4),o.set(e.subarray(n),n+4+r.length),o}catch{return e}}var L;function Be(){if(!L){L=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let t=0;t<8;t++)r=r&1?3988292384^r>>>1:r>>>1;L[e]=r>>>0;}}return L}function Fe(e){let r=Be(),t=4294967295;for(let n=0;n<e.length;n++)t=r[(t^e[n])&255]^t>>>8;return (t^4294967295)>>>0}function N(e,r,t){return e[r]===t.charCodeAt(0)&&e[r+1]===t.charCodeAt(1)&&e[r+2]===t.charCodeAt(2)&&e[r+3]===t.charCodeAt(3)}function le(e,r){try{if(e.length<33)return e;for(let u=0;u<se.length;u++)if(e[u]!==se[u])return e;if(ue(e,8)!==13||!N(e,12,"IHDR")||!Z(r))return e;let t=r.subarray(B.length),n=33;for(;n+8<=e.length;){let u=ue(e,n);if(u>e.length||n+12+u>e.length)return e;if(N(e,n+4,"IDAT")||N(e,n+4,"IEND"))break;if(N(e,n+4,"eXIf"))return e;n+=12+u;}let o=new Uint8Array(12+t.length);o[0]=t.length>>>24&255,o[1]=t.length>>>16&255,o[2]=t.length>>>8&255,o[3]=t.length&255,o.set([101,88,73,102],4),o.set(t,8);let i=Fe(o.subarray(4,8+t.length));o[8+t.length]=i>>>24&255,o[9+t.length]=i>>>16&255,o[10+t.length]=i>>>8&255,o[11+t.length]=i&255;let c=new Uint8Array(e.length+o.length);return c.set(e.subarray(0,n),0),c.set(o,n),c.set(e.subarray(n),n+o.length),c}catch{return e}}var j=16384;function re(){if(typeof OffscreenCanvas>"u"&&typeof document>"u")throw new a("unsupported_environment",s.CanvasUnsupported)}var z=null,De=5e3;async function We(){let e=ee(1,1),r=F(e,"image/avif"),t,n=new Promise(o=>{t=setTimeout(()=>o("timeout"),De);});try{let o=await Promise.race([r,n]);return o==="timeout"?(z=null,!1):o.type==="image/avif"&&o.size>0}finally{t!==void 0&&clearTimeout(t),P(e);}}function ge(){return z===null&&(z=We().catch(()=>false)),z}async function ne(e){if($(e),String(e).toLowerCase()==="avif"&&!await ge())throw new a("format_unsupported",s.FormatUnsupported("avif"))}function He(e,r,t){if(Q(t),!t)return {width:e,height:r};let{maxWidth:n,maxHeight:o,scale:i}=t;if(i!==void 0){let l=Math.max(1,Math.round(e*i)),m=Math.max(1,Math.round(r*i));return fe(l,m),{width:l,height:m}}if(n===void 0&&o===void 0)return {width:e,height:r};let c=Math.min(n!==void 0?n/e:Number.POSITIVE_INFINITY,o!==void 0?o/r:Number.POSITIVE_INFINITY);if(c>=1)return {width:e,height:r};let u=Math.min(Math.max(1,Math.round(e*c)),n!==void 0?Math.floor(n):Number.POSITIVE_INFINITY),d=Math.min(Math.max(1,Math.round(r*c)),o!==void 0?Math.floor(o):Number.POSITIVE_INFINITY);return fe(u,d),{width:u,height:d}}function fe(e,r){if(!Number.isFinite(e)||!Number.isFinite(r)||e>j||r>j)throw new a("invalid_resize",s.TargetSizeTooLarge(e,r,j))}async function te(e){if(typeof FileReader<"u")return new Promise((r,t)=>{let n=new FileReader;n.onloadend=()=>{typeof n.result=="string"?r(n.result):t(new a("render_encode_failed",s.BlobToBase64Failed));},n.onerror=()=>t(new a("render_encode_failed",s.BlobToBase64FailedWithCause(n.error?.message??"FileReader failed"),{cause:n.error??void 0})),n.readAsDataURL(e);});try{let r=await e.arrayBuffer(),t=new Uint8Array(r),n="",o=32768;for(let c=0;c<t.length;c+=o)n+=String.fromCharCode(...t.subarray(c,c+o));let i=btoa(n);return `data:${e.type};base64,${i}`}catch(r){throw new a("render_encode_failed",s.BlobToBase64FailedWithCause(r instanceof Error?r.message:String(r)),{cause:r})}}function F(e,r,t){return "convertToBlob"in e?e.convertToBlob({type:r,quality:t}):new Promise((n,o)=>{e.toBlob(i=>{i?n(i):o(new a("render_encode_failed",s.CanvasToBlobFailed(r)));},r,t);})}function ee(e,r){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,r);if(typeof document<"u"){let t=document.createElement("canvas");return t.width=e,t.height=r,t}throw new a("unsupported_environment",s.CanvasUnsupported)}function P(e){let r=e;typeof r.close=="function"?r.close():e.width=0;}function me(e,r,t,n){if(typeof ImageData<"u")e.putImageData(new ImageData(r,t,n),0,0);else {let o=e.createImageData(t,n);o.data.set(r),e.putImageData(o,0,0);}}function $e(e,r,t){switch(e){case 2:return [-1,0,0,1,r,0];case 3:return [-1,0,0,-1,r,t];case 4:return [1,0,0,-1,0,t];case 5:return [0,1,1,0,0,0];case 6:return [0,1,-1,0,t,0];case 7:return [0,-1,-1,0,t,r];case 8:return [0,-1,1,0,0,r];default:return null}}function Le(e,r){return !r||typeof e!="number"||!Number.isInteger(e)?1:e>=1&&e<=8?e:1}async function pe(e,r,t,n,o){let i=r.exif;if(!t||!i||i.length===0)return e;let c=o?de(i):i,u=new Uint8Array(await e.arrayBuffer()),d=n==="jpeg"?ce(u,c):le(u,c);return d===u?e:new Blob([d.buffer],{type:e.type})}async function he(e,r,t,n,o=true,i,c=false){$(r),X(i);let u=r.toLowerCase();if(u==="avif"&&!await ge())throw new a("format_unsupported",s.FormatUnsupported("avif"));let{width:d,height:l,data:m}=e;if(!Number.isInteger(d)||d<=0||!Number.isInteger(l)||l<=0)throw new a("render_encode_failed",s.InvalidDimensions(d,l));let y=d*l*4;if(m.length!==y)throw new a("render_encode_failed",s.DataLengthMismatch(y,d,l,m.length));let h=Le(e.orientation,o),g=!(e.orientation!==void 0&&e.orientation>=2&&e.orientation<=8)||o,p=$e(h,d,l),O=h>=5,k=O?l:d,M=O?d:l,A=i?.x??0,v=i?.y??0,b=i?i.width:k,E=i?i.height:M;if(i&&(A+b>k||v+E>M))throw new a("invalid_crop",s.CropOutOfBounds(A,v,b,E,k,M));let C=He(b,E,n),q=C.width!==b||C.height!==E,I=p!==null||i!==void 0,f=ee(C.width,C.height),S=f.getContext("2d");if(!S)throw new a("render_encode_failed",s.ContextUnavailable);if(I||q){let x=ee(d,l),H=x.getContext("2d");if(!H)throw new a("render_encode_failed",s.ContextUnavailable);if(me(H,m,d,l),I){let D=C.width/b,W=C.height/E,ye=p?p[0]:1,xe=p?p[1]:0,Ce=p?p[2]:0,Ie=p?p[3]:1,Oe=p?p[4]:0,Ee=p?p[5]:0;S.setTransform(ye*D,xe*W,Ce*D,Ie*W,D*(Oe-A),W*(Ee-v)),S.drawImage(x,0,0);}else S.drawImage(x,0,0,C.width,C.height);P(x);}else me(S,m,d,l);if(u==="png"){let x=await F(f,"image/png");return P(f),pe(x,e,c,"png",g)}if(u==="jpeg"||u==="jpg"){let x=await F(f,"image/jpeg",t);return P(f),pe(x,e,c,"jpeg",g)}if(u==="webp"){let x=await F(f,"image/webp",t);return P(f),x}if(u==="avif"){let x=await F(f,"image/avif",t);if(P(f),x.type!=="image/avif")throw new a("format_unsupported",s.FormatUnsupported("avif"));return x}if(u==="svg"){let x=await F(f,"image/png");P(f);let H=await te(x),D=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${C.width} ${C.height}" width="${C.width}" height="${C.height}">
2
- <image width="${C.width}" height="${C.height}" href="`,W=`" />
3
- </svg>`;return new Blob([D,H,W],{type:"image/svg+xml"})}throw new a("invalid_format",s.UnsupportedFormat(String(r)))}async function V(e,r,t,n){let o=n?.continueOnError===true,i=n?.signal,c=new Array(e.length),u=0,d=false,l=0,m=null,y=-1,h=0,w=[],g,p=new Promise(v=>{g=v;}),O=()=>g?.();i&&!o&&i.addEventListener("abort",O,{once:true});let k=async()=>{for(;!d&&!i?.aborted||o;){let v=u;if(u+=1,v>=e.length)return;if(o&&i?.aborted){let b=new a("aborted",s.Aborted);for(let E=v;E<e.length;E++)c[E]={index:E,ok:false,error:b};u=e.length;return}try{let b=await t(e[v],v);c[v]={index:v,ok:!0,result:b},l+=1;}catch(b){if(h+=1,o){c[v]={index:v,ok:false,error:b instanceof Error?b:new Error(String(b))};continue}d?w.length<2&&w.push(b instanceof Error?b.message:String(b)):(d=true,m=b,y=v,g?.());}}},M=Math.min(r,e.length),A=Array.from({length:M},()=>k());try{if(o)return await Promise.all(A),c;if(await Promise.race([Promise.all(A),p]),l===e.length)return c.map(v=>{if(!v||!v.ok)throw new a("batch_item_failed",s.BatchItemProducedNoResult(v?.index));return v.result});if(i?.aborted)throw new a("aborted",s.Aborted);if(d){let v=m instanceof Error?m.message:String(m),b=s.ConvertManyItemFailed(y+1,e.length,v);throw h>1&&(b+=s.ConvertManyExtraFailures(h,e.length),w.length>0&&(b+=s.ConvertManyOtherErrors(w))),new a("batch_item_failed",b,{cause:m,itemIndex:y,itemTotal:e.length,failedCount:h})}throw new a("batch_item_failed",s.BatchEndedWithoutResult)}finally{i?.removeEventListener("abort",O);}}function Ne(){let e=typeof navigator<"u"&&typeof navigator.hardwareConcurrency=="number"?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var G=new Map;function ze(e,r,t){let n=G.get(e);n||(n={active:0,waiters:[]},G.set(e,n));let o={granted:false,released:false},i=()=>{let d=n.waiters.shift();d?d():n.active===0&&n.waiters.length===0&&G.delete(e);},c=()=>{if(!o.released)if(o.released=true,o.granted)o.granted=false,n.active-=1,i();else {let d=n.waiters.indexOf(u);d!==-1&&n.waiters.splice(d,1),n.active===0&&n.waiters.length===0&&G.delete(e);}},u=()=>{o.released||(o.granted=true,n.active+=1,t(c));};return n.active<r?u():n.waiters.push(u),c}function ve(e){return new a("progress_callback_failed",s.ProgressCallbackThrew(e instanceof Error?e.message:String(e)),{cause:e})}function be(e,r){return new Promise((t,n)=>{if(typeof Worker>"u"){n(new a("worker_unsupported",s.WorkerUnsupported));return}if(r.decoder!==void 0){n(new a("invalid_input",s.WorkerDecoderUnsupported));return}try{R(r),J(r?.maxConcurrentWorkers),K(r?.timeoutMs);}catch(I){n(I);return}if(r.signal?.aborted){n(new a("aborted",s.Aborted));return}let o={progressMessages:0},i,c=false,u,d,l=()=>{c||(c=true,u!==void 0&&clearTimeout(u),r.signal?.removeEventListener("abort",m),i&&(i.removeEventListener("message",h),i.removeEventListener("messageerror",g),i.removeEventListener("error",w),i.terminate()),d?.());},m=()=>{l(),n(new a("aborted",s.Aborted));};r.signal?.addEventListener("abort",m,{once:true});let y=r.timeoutMs??6e4;y>0&&(u=setTimeout(()=>{l(),n(new a("worker_timeout",s.WorkerTimeout(y,{progressMessages:o.progressMessages,lastPercent:o.lastPercent,unknownType:o.unknownType,workerUrl:r.workerUrl})));},y));let h=I=>{let f=I.data;if(f?.type==="progress"){o.progressMessages+=1;let S=T(f.percent);if(o.lastPercent=S,S>=100)return;try{r.onProgress?.(S);}catch(x){l(),n(ve(x));}return}if(f?.type!=="result"){typeof f?.type=="string"&&(o.unknownType=f.type);return}if(l(),f.ok&&f.blob!==void 0){try{r.onProgress?.(100);}catch(S){n(ve(S));return}t(f.blob);}else n(new a("worker_failed",f.error??s.WorkerConversionFailed));},w=I=>{l();let f=I.filename?` (${I.filename}:${I.lineno})`:"";n(new a("worker_failed",`${I.message||s.WorkerFailed(r.workerUrl)}${f}`));},g=I=>{l();let f=I.data;n(new a("worker_failed",f instanceof Error?f.message:f!==void 0?String(f):s.WorkerFailed(r.workerUrl),{cause:f}));},{workerUrl:p,onProgress:O,timeoutMs:k,workerType:M,maxConcurrentWorkers:A,signal:v,...b}=r,E=I=>{if(d=I,!c){try{i=new Worker(p,r.workerType==="module"?{type:"module"}:void 0);}catch(f){l(),n(new a("worker_create_failed",s.WorkerCreateFailed(f instanceof Error?f.message:String(f)),{cause:f}));return}i.addEventListener("message",h),i.addEventListener("messageerror",g),i.addEventListener("error",w);try{i.postMessage({input:e,options:b});}catch(f){l(),n(new a("worker_post_failed",s.WorkerPostFailed(f instanceof Error?f.message:String(f)),{cause:f}));}}},C=`${String(p)}|${r.workerType??"classic"}`,q=we(r.maxConcurrentWorkers);d=ze(C,q,E);})}function we(e){return typeof e=="number"&&Number.isInteger(e)?Math.max(1,e):Ne()}async function Ve(e,r){if(!Array.isArray(e))throw new a("invalid_input",s.InputsMustBeArray);if(typeof Worker>"u")throw new a("worker_unsupported",s.WorkerUnsupported);if(r.decoder!==void 0)throw new a("invalid_input",s.WorkerDecoderUnsupported);R(r),Y(r?.continueOnError),J(r?.maxConcurrentWorkers),K(r?.timeoutMs);let{onProgress:t,continueOnError:n,...o}=r??{};return V(e,we(r?.maxConcurrentWorkers),(i,c)=>be(i,{...o,...t!==void 0?{onProgress:u=>t(c,u)}:{}}),{continueOnError:r?.continueOnError===true,signal:r?.signal})}function _r(){}async function Ge(e,r){return r==="dataUrl"?await te(e):r==="arrayBuffer"?await e.arrayBuffer():e}async function qe(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<"u"&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e!==null&&typeof e=="object"&&typeof e.arrayBuffer=="function"){let r=await e.arrayBuffer();if(r instanceof ArrayBuffer)return new Uint8Array(r)}if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}throw new a("invalid_input",s.UnsupportedInputType(Object.prototype.toString.call(e)))}function Ye(e){if(typeof e!="function")return;let r=false,t,n=o=>{try{e(o);}catch(i){throw new a("progress_callback_failed",s.ProgressCallbackThrew(i instanceof Error?i.message:String(i)),{cause:i})}};return {report:o=>{if(r)return;let i=T(o);if(!(i>=100))try{e(i);}catch(c){t=t??c;}},complete:()=>{if(!r){if(r=true,t!==void 0)throw new a("progress_callback_failed",s.ProgressCallbackThrew(t instanceof Error?t.message:String(t)),{cause:t});n(100);}}}}async function Qe(e,r){let t=r?.to??"jpeg";R(r),re(),await ne(t);let n=r?.signal;U(n);let o=r?.maxWidth!==void 0||r?.maxHeight!==void 0||r?.scale!==void 0?r:void 0,i=await qe(e);U(n);let c=r?.decoder??new _,u=!r?.decoder,d=false,l=()=>{if(!(!u||d)){d=true;try{c.free();}catch{}}};try{try{await c.initialize();}catch(g){throw new a("decoder_init_failed",s.DecoderInitFailed(g instanceof Error?g.message:String(g)),{cause:g})}U(n);let m=Ye(r?.onProgress),y=await c.decode(i,m?m.report:void 0);l(),U(n);let h=r?.quality!==void 0?r.quality:.92,w;try{w=await he(y,t,h,o,r?.applyOrientation??!0,r?.crop,r?.preserveExif??!1);}catch(g){throw g instanceof a?g:new a("render_encode_failed",s.RenderEncodeFailed(t,g instanceof Error?g.message:String(g)),{cause:g})}return U(n),m?.complete(),Ge(w,r?.output??"blob")}finally{l();}}var oe=class{max;idle=[];waiters=[];leasedCount=0;disposed=false;constructor(r){this.max=Math.max(1,r);}async acquire(){let r=this.idle.pop();return r||(this.leasedCount<this.max?(this.leasedCount+=1,new _):new Promise(t=>this.waiters.push(t)))}release(r){if(this.disposed){try{r.free();}catch{}return}let t=this.waiters.shift();t?t(r):this.idle.push(r);}dispose(){this.disposed=true;for(let r of this.idle)try{r.free();}catch{}this.idle.length=0;for(let r of this.waiters.splice(0))r(new _);}};async function Pr(e,r){if(!Array.isArray(e))throw new a("invalid_input",s.InputsMustBeArray);let t=r?.concurrency??4;if(!Number.isInteger(t)||t<1)throw new a("invalid_concurrency",s.ConcurrencyInvalid(t));R(r),ae(r),re(),await ne(r?.to??"jpeg");let{concurrency:n,onProgress:o,continueOnError:i,reuseDecoders:c,...u}=r??{},l=c===true&&r?.decoder===void 0?new oe(Math.min(t,e.length)):null;try{return await V(e,t,async(m,y)=>{let h=l?await l.acquire():null;try{return await Qe(m,{...u,...h?{decoder:h}:{},onProgress:o!==void 0?w=>o(y,w):void 0})}finally{h&&l.release(h);}},{continueOnError:r?.continueOnError===!0,signal:r?.signal})}finally{l?.dispose();}}exports.DEFAULT_QUALITY=Se;exports.HeicConverterError=a;exports.LibheifDecoder=_;exports.SUPPORTED_FORMATS=ie;exports.convertHeic=Qe;exports.convertHeicInWorker=be;exports.convertMany=Pr;exports.convertManyInWorker=Ve;exports.freeSharedDecoder=_r;
1
+ var e=require("./chunk-FKEXCXR4.js"),t=new WeakSet,r=/[\u0000-\u001f\u007f-\u009f]+/g,n=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const e=++this.initGeneration,t={};this.options?.moduleOverrides&&Object.assign(t,this.options.moduleOverrides),this.options?.locateFile&&(t.locateFile=this.options.locateFile),this.options?.wasmBinary&&(t.wasmBinary=this.options.wasmBinary);const r=import("./heic-decoder-RXDCJDOS.js").then(({default:e})=>e(t)).then(t=>{const r=new t.HeicDecoder;return e!==this.initGeneration?(r.delete(),null):(this.module=t,this.decoderInstance=r,t)}).catch(e=>{throw this.initPromise===r&&(this.initPromise=null),e});this.initPromise=r}await this.initPromise}async decode(n,i){if(this.module&&this.decoderInstance||await this.initialize(),!this.module||!this.decoderInstance)throw new e.HeicConverterError("decode_failed",e.Messages.DecoderFreedDuringDecode);let o;const a=i?t=>{try{i(e.clampPercent(t))}catch(e){o=o??e}}:null,s=this.module,c=this.decoderInstance;let d;try{if("function"==typeof c.decodeFromPointer&&"function"==typeof s._malloc&&"function"==typeof s._free&&s.HEAPU8 instanceof Uint8Array&&n.buffer!==s.HEAPU8.buffer){const t=s._malloc(n.byteLength);if(0===t)throw new e.HeicConverterError("decode_failed",e.Messages.DecodeInputAllocFailed(n.byteLength));try{s.HEAPU8.set(n,t),d=c.decodeFromPointer(t,n.byteLength,a)}finally{s._free(t)}}else d=c.decode(n,a)}catch(r){if(r instanceof e.HeicConverterError)throw r;throw t.add(this),new e.HeicConverterError("decode_failed",e.Messages.DecodeFaulted(n.byteLength),{cause:r})}if("string"==typeof d)throw new e.HeicConverterError("decode_failed",e.Messages.DecodeFailedWithDetail(function(e){const t=e.replace(r," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(d),n.byteLength));if(!d)throw new e.HeicConverterError("decode_failed",e.Messages.DecodeFailed(n.byteLength));if(void 0!==o)throw new e.HeicConverterError("progress_callback_failed",e.Messages.ProgressCallbackThrew(o instanceof Error?o.message:String(o)),{cause:o});const f=d.width,u=d.height,l=d.orientation,h="number"==typeof l&&Number.isInteger(l)&&l>=1&&l<=8?l:1,w=s.HEAPU8 instanceof Uint8Array?s.HEAPU8.buffer:void 0,g={width:f,height:u,data:void 0!==w&&d.data.buffer!==w?new Uint8ClampedArray(d.data.buffer,d.data.byteOffset,d.data.byteLength):new Uint8ClampedArray(d.data)};h>1&&(g.orientation=h);const p=d.exif;return p instanceof Uint8Array&&p.length>=14&&(g.exif=void 0!==w&&p.buffer!==w?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):new Uint8Array(p)),g}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,t.delete(this),this.initPromise=null}},i=16384;function o(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new e.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}var a=null;function s(){if(null===a){const e=async function(){let e;try{e=l(1,1)}catch{return}const t=u(e,"image/avif");let r;const n=new Promise(e=>{r=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,n]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==r&&clearTimeout(r),h(e)}}().catch(()=>!1);a=e,e.then(t=>{void 0===t&&a===e&&(a=null)})}return a}async function c(t){if(e.validateFormat(t),"avif"===String(t).toLowerCase()&&!1===await s())throw new e.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"))}function d(t,r){if(!Number.isFinite(t)||!Number.isFinite(r)||t>i||r>i)throw new e.HeicConverterError("invalid_resize",e.Messages.TargetSizeTooLarge(t,r,i))}async function f(t){if("undefined"!=typeof FileReader)return new Promise((r,n)=>{const i=new FileReader;i.onloadend=()=>{"string"==typeof i.result?r(i.result):n(new e.HeicConverterError("render_encode_failed",e.Messages.BlobToBase64Failed))},i.onerror=()=>n(new e.HeicConverterError("render_encode_failed",e.Messages.BlobToBase64FailedWithCause(i.error?.message??"FileReader failed"),{cause:i.error??void 0})),i.readAsDataURL(t)});try{const e=await t.arrayBuffer(),r=new Uint8Array(e);let n="";const i=32768;for(let e=0;e<r.length;e+=i)n+=String.fromCharCode(...r.subarray(e,e+i));const o=btoa(n);return`data:${t.type};base64,${o}`}catch(t){throw new e.HeicConverterError("render_encode_failed",e.Messages.BlobToBase64FailedWithCause(t instanceof Error?t.message:String(t)),{cause:t})}}function u(t,r,n){return"convertToBlob"in t?t.convertToBlob({type:r,quality:n}):new Promise((i,o)=>{t.toBlob(t=>{t?i(t):o(new e.HeicConverterError("render_encode_failed",e.Messages.CanvasToBlobFailed(r)))},r,n)})}function l(t,r){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,r);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=t,e.height=r,e}throw new e.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}function h(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function w(e,t,r,n){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,r,n),0,0);else{const i=e.createImageData(r,n);i.data.set(t),e.putImageData(i,0,0)}}var g=!1;async function p(e,t,r,n,i){const o=t.exif;if(!r||!o||0===o.length)return e;const a=await import("./exif-H2Q7BO7Y.js").catch(()=>null);if(!a)return g||(g=!0,console.warn("@keeratita/heic-converter: the EXIF injector chunk could not be loaded — converted without metadata; serve every file in dist/ together, with dist/exif-*.mjs as JavaScript.")),e;const{injectExifIntoJpeg:s,injectExifIntoPng:c,normalizeOrientationTag:d}=a,f=i?d(o):o,u=new Uint8Array(await e.arrayBuffer()),l="jpeg"===n?s(u,f):c(u,f);return l===u?e:new Blob([l.buffer],{type:e.type})}function v(){return import("./worker-Z3UQ6WL7.js").catch(t=>{const r=t instanceof Error?t.message:String(t);throw new e.HeicConverterError("worker_load_failed",e.Messages.WorkerChunkLoadFailed(r),{cause:t})})}async function m(t,r){const i=r?.to??"jpeg";e.validateConvertOptions(r),o(),await c(i);const a=r?.signal;e.throwIfAborted(a);const g=void 0!==r?.maxWidth||void 0!==r?.maxHeight||void 0!==r?.scale?r:void 0,v=await async function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if("undefined"!=typeof Blob&&t instanceof Blob)return new Uint8Array(await t.arrayBuffer());if(null!==t&&"object"==typeof t&&"function"==typeof t.arrayBuffer){const e=await t.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new e.HeicConverterError("invalid_input",e.Messages.UnsupportedInputType(Object.prototype.toString.call(t)))}(t);e.throwIfAborted(a);const m=r?.decoder??new n,y=!r?.decoder;let b=!1;const C=()=>{if(y&&!b){b=!0;try{m.free()}catch{}}};try{try{await m.initialize()}catch(t){throw new e.HeicConverterError("decoder_init_failed",e.Messages.DecoderInitFailed(t instanceof Error?t.message:String(t)),{cause:t})}e.throwIfAborted(a);const t=function(t){if("function"!=typeof t)return;let r,n=!1;return{report:i=>{if(n)return;const o=e.clampPercent(i);if(!(o>=100))try{t(o)}catch(e){r=r??e}},complete:()=>{if(!n){if(n=!0,void 0!==r)throw new e.HeicConverterError("progress_callback_failed",e.Messages.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r});(()=>{try{t(100)}catch(t){throw new e.HeicConverterError("progress_callback_failed",e.Messages.ProgressCallbackThrew(t instanceof Error?t.message:String(t)),{cause:t})}})()}}}}(r?.onProgress),n=await m.decode(v,t?t.report:void 0);C(),e.throwIfAborted(a);const o=void 0!==r?.quality?r.quality:e.DEFAULT_QUALITY;let c;try{c=await async function(t,r,n,i,o=!0,a,c=!1){e.validateFormat(r),e.validateCrop(a);const g=r.toLowerCase();if("avif"===g&&!1===await s())throw new e.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));const{width:v,height:m,data:y}=t;if(!Number.isInteger(v)||v<=0||!Number.isInteger(m)||m<=0)throw new e.HeicConverterError("render_encode_failed",e.Messages.InvalidDimensions(v,m));const b=v*m*4;if(y.length!==b)throw new e.HeicConverterError("render_encode_failed",e.Messages.DataLengthMismatch(b,v,m,y.length));const C=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(t.orientation,o),E=!(void 0!==t.orientation&&t.orientation>=2&&t.orientation<=8)||o,I=function(e,t,r){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,r];case 4:return[1,0,0,-1,0,r];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,r,0];case 7:return[0,-1,-1,0,r,t];case 8:return[0,-1,1,0,0,t];default:return null}}(C,v,m),_=C>=5,M=_?m:v,H=_?v:m,A=a?.x??0,F=a?.y??0,P=a?a.width:M,U=a?a.height:H;if(a&&(A+P>M||F+U>H))throw new e.HeicConverterError("invalid_crop",e.Messages.CropOutOfBounds(A,F,P,U,M,H));const x=function(t,r,n){if(e.validateResize(n),!n)return{width:t,height:r};const{maxWidth:i,maxHeight:o,scale:a}=n;if(void 0!==a){const e=Math.max(1,Math.round(t*a)),n=Math.max(1,Math.round(r*a));return d(e,n),{width:e,height:n}}if(void 0===i&&void 0===o)return{width:t,height:r};const s=Math.min(void 0!==i?i/t:Number.POSITIVE_INFINITY,void 0!==o?o/r:Number.POSITIVE_INFINITY);if(s>=1)return{width:t,height:r};const c=Math.min(Math.max(1,Math.round(t*s)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),f=Math.min(Math.max(1,Math.round(r*s)),void 0!==o?Math.floor(o):Number.POSITIVE_INFINITY);return d(c,f),{width:c,height:f}}(P,U,i),B=x.width!==P||x.height!==U,T=null!==I||void 0!==a,O=l(x.width,x.height),D=O.getContext("2d");if(!D)throw new e.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(T||B){const t=l(v,m),r=t.getContext("2d");if(!r)throw new e.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(w(r,y,v,m),T){const e=x.width/P,r=x.height/U,n=I?I[0]:1,i=I?I[1]:0,o=I?I[2]:0,a=I?I[3]:1,s=I?I[4]:0,c=I?I[5]:0;D.setTransform(n*e,i*r,o*e,a*r,e*(s-A),r*(c-F)),D.drawImage(t,0,0)}else D.drawImage(t,0,0,x.width,x.height);h(t)}else w(D,y,v,m);if("png"===g){const e=await u(O,"image/png");return h(O),p(e,t,c,"png",E)}if("jpeg"===g||"jpg"===g){const e=await u(O,"image/jpeg",n);return h(O),p(e,t,c,"jpeg",E)}if("webp"===g){const e=await u(O,"image/webp",n);return h(O),e}if("avif"===g){const t=await u(O,"image/avif",n);if(h(O),"image/avif"!==t.type)throw new e.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));return t}if("svg"===g){const e=await u(O,"image/png");h(O);const t=await f(e),r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${x.width} ${x.height}" width="${x.width}" height="${x.height}">\n <image width="${x.width}" height="${x.height}" href="`;return new Blob([r,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new e.HeicConverterError("invalid_format",e.Messages.UnsupportedFormat(String(r)))}(n,i,o,g,r?.applyOrientation??!0,r?.crop,r?.preserveExif??!1)}catch(t){if(t instanceof e.HeicConverterError)throw t;throw new e.HeicConverterError("render_encode_failed",e.Messages.RenderEncodeFailed(i,t instanceof Error?t.message:String(t)),{cause:t})}return e.throwIfAborted(a),t?.complete(),async function(e,t){return"dataUrl"===t?await f(e):"arrayBuffer"===t?await e.arrayBuffer():e}(c,r?.output??"blob")}finally{C()}}var y=class{max;idle=[];waiters=[];leasedCount=0;disposed=!1;constructor(e){this.max=Math.max(1,e)}async acquire(){return this.idle.pop()||(this.leasedCount<this.max?(this.leasedCount+=1,new n):new Promise(e=>this.waiters.push(e)))}release(e){if(this.disposed){try{e.free()}catch{}return}if(function(e){return t.has(e)}(e)){this.leasedCount-=1;try{e.free()}catch{}const t=this.waiters.shift();return void(t&&(this.leasedCount+=1,t(new n)))}const r=this.waiters.shift();r?r(e):this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0;for(const e of this.waiters.splice(0))e(new n)}};Object.defineProperty(exports,"DEFAULT_QUALITY",{enumerable:!0,get:function(){return e.DEFAULT_QUALITY}}),Object.defineProperty(exports,"HeicConverterError",{enumerable:!0,get:function(){return e.HeicConverterError}}),Object.defineProperty(exports,"SUPPORTED_FORMATS",{enumerable:!0,get:function(){return e.SUPPORTED_FORMATS}}),exports.LibheifDecoder=n,exports.convertHeic=m,exports.convertHeicInWorker=function(e,t){return v().then(r=>r.convertHeicInWorker(e,t))},exports.convertMany=async function(t,r){if(!Array.isArray(t))throw new e.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);const n=r?.concurrency??4;e.validateConcurrency(n),e.validateConvertOptions(r),e.validateBatchOptions(r),o(),await c(r?.to??"jpeg");const{concurrency:i,onProgress:a,continueOnError:s,reuseDecoders:d,...f}=r??{},u=!0===d&&void 0===r?.decoder?new y(e.runnerCountFor(n,t.length)):null;try{return await e.runBoundedBatch(t,n,async(e,t)=>{const r=u?await u.acquire():null;try{return await m(e,{...f,...r?{decoder:r}:{},onProgress:void 0!==a?e=>a(t,e):void 0})}finally{r&&u.release(r)}},{continueOnError:!0===r?.continueOnError,signal:r?.signal})}finally{u?.dispose()}},exports.convertManyInWorker=function(e,t){return v().then(r=>r.convertManyInWorker(e,t))},exports.freeSharedDecoder=function(){};
package/dist/index.mjs CHANGED
@@ -1,3 +1 @@
1
- var s={QualityInvalid:e=>`Quality must be a number between 0.0 and 1.0, got: ${e}`,ApplyOrientationInvalid:e=>`applyOrientation must be a boolean, got: ${e}`,UnsupportedInputType:e=>`Unsupported input type. Expected Blob, File, ArrayBuffer, or Uint8Array. Got: ${e}`,DecoderInitFailed:e=>`Failed to initialize HEIC decoder: ${e} \u2014 verify heic-decoder.wasm is served (dist/heic-decoder.wasm; see the README "Serving and Locating WASM" section / locateFile option) and that your CSP allows 'wasm-unsafe-eval'`,RenderEncodeFailed:(e,r)=>`Failed to render and encode image as ${e}: ${r}`,ConcurrencyInvalid:e=>`Concurrency must be a positive integer, got: ${e}`,MaxConcurrentWorkersInvalid:e=>`maxConcurrentWorkers must be a positive integer, got: ${e}`,TimeoutInvalid:e=>`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${e}`,InputsMustBeArray:"Inputs must be an array of HEIC images",OutputShapeInvalid:e=>`output must be one of 'blob', 'dataUrl', 'arrayBuffer', got: ${e}`,ReuseDecodersInvalid:e=>`reuseDecoders must be a boolean, got: ${e}`,ContinueOnErrorInvalid:e=>`continueOnError must be a boolean, got: ${e}`,PreserveExifInvalid:e=>`preserveExif must be a boolean, got: ${e}`,SignalInvalid:e=>`signal must be an AbortSignal, got: ${e}`,Aborted:"Conversion aborted (AbortSignal was aborted)",ConvertManyItemFailed:(e,r,t)=>`Conversion of item ${e} of ${r} failed: ${t}`,ConvertManyExtraFailures:(e,r)=>` (${e} of ${r} items failed in total)`,ConvertManyOtherErrors:e=>`; other errors: ${e.join(" | ")}`,BatchItemProducedNoResult:e=>`Item ${String(e)} produced no result`,BatchEndedWithoutResult:"Batch ended without a result",ScaleInvalid:e=>`Scale must be a positive finite number, got: ${e}`,MaxWidthInvalid:e=>`maxWidth must be a positive finite number, got: ${e}`,MaxHeightInvalid:e=>`maxHeight must be a positive finite number, got: ${e}`,TargetSizeTooLarge:(e,r,t)=>`Target image size ${e}x${r} exceeds the maximum supported dimension of ${t}px`,BlobToBase64Failed:"Failed to convert Blob to base64 string",BlobToBase64FailedWithCause:e=>`Failed to convert Blob to base64 string: ${e}`,CanvasToBlobFailed:e=>`Failed to convert canvas to blob (type: ${e})`,CanvasUnsupported:"Canvas is not supported in the current environment. In a browser this requires OffscreenCanvas or HTMLCanvasElement. In Node.js there is no canvas: decode raw RGBA with LibheifDecoder and encode externally (see the Node.js section of the README).",InvalidDimensions:(e,r)=>`Invalid image dimensions: ${e}x${r}. Width and height must be positive integers.`,DataLengthMismatch:(e,r,t,n)=>`Image data length mismatch. Expected ${e} bytes for ${r}x${t}, got ${n}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' \u2014 canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,r)=>`crop.${e} must be ${e==="width"||e==="height"?"a positive integer":"a non-negative integer"}, got: ${r}`,CropOutOfBounds:(e,r,t,n,o,i)=>`crop ${t}x${n} at (${e}, ${r}) exceeds the ${o}x${i} image (crop coordinates are in post-orientation display pixels)`,DecoderFreedDuringDecode:"Decoder was freed before decoding completed; call initialize() again.",DecodeInputAllocFailed:e=>`Failed to allocate ${e} bytes in the WASM heap for decode input`,DecodeFailed:e=>`HEIC decoding failed (no result returned; input: ${e} bytes \u2014 is the file truncated or empty?)`,DecodeFailedWithDetail:(e,r)=>`HEIC decoding failed: ${e} (input: ${r} bytes)`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`,WorkerUnsupported:"Web Worker is not supported in the current environment",WorkerCreateFailed:e=>`Failed to create Web Worker: ${e}`,WorkerPostFailed:e=>`Failed to post message to Web Worker: ${e}`,WorkerConversionFailed:"Worker conversion failed",WorkerDecoderUnsupported:"The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",WorkerFailed:e=>"Worker failed"+(e!==void 0?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:""),WorkerTimeout:(e,r)=>{let t=[`${r.progressMessages} progress message(s) received`];return r.lastPercent!==void 0&&t.push(`last percent ${r.lastPercent}`),r.unknownType!==void 0&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),r.workerUrl!==void 0&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`}};function T(e){let r=Number(e);return Number.isFinite(r)?Math.min(100,Math.max(0,r)):0}var a=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(r,t,n){super(t,{cause:n?.cause}),this.name="HeicConverterError",this.code=r,n?.itemIndex!==void 0&&(this.itemIndex=n.itemIndex),n?.itemTotal!==void 0&&(this.itemTotal=n.itemTotal),n?.failedCount!==void 0&&(this.failedCount=n.failedCount);}};var _=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(r){this.options=r;}async initialize(){if(!this.initPromise){let r=++this.initGeneration,t={};this.options?.moduleOverrides&&Object.assign(t,this.options.moduleOverrides),this.options?.locateFile&&(t.locateFile=this.options.locateFile),this.options?.wasmBinary&&(t.wasmBinary=this.options.wasmBinary);let n=import('./heic-decoder-WNTZ4MAN.mjs').then(({default:o})=>o(t)).then(o=>{let i=new o.HeicDecoder;return r!==this.initGeneration?(i.delete(),null):(this.module=o,this.decoderInstance=i,o)}).catch(o=>{throw this.initPromise===n&&(this.initPromise=null),o});this.initPromise=n;}await this.initPromise;}async decode(r,t){if((!this.module||!this.decoderInstance)&&await this.initialize(),!this.module||!this.decoderInstance)throw new a("decode_failed",s.DecoderFreedDuringDecode);let n,o=t?O=>{try{t(T(O));}catch(k){n=n??k;}}:null,i=this.module,c=this.decoderInstance,u;if(typeof c.decodeFromPointer=="function"&&typeof i._malloc=="function"&&typeof i._free=="function"&&i.HEAPU8 instanceof Uint8Array&&r.buffer!==i.HEAPU8.buffer){let O=i._malloc(r.byteLength);if(O===0)throw new a("decode_failed",s.DecodeInputAllocFailed(r.byteLength));try{i.HEAPU8.set(r,O),u=c.decodeFromPointer(O,r.byteLength,o);}finally{i._free(O);}}else u=c.decode(r,o);if(typeof u=="string")throw new a("decode_failed",s.DecodeFailedWithDetail(u,r.byteLength));if(!u)throw new a("decode_failed",s.DecodeFailed(r.byteLength));if(n!==void 0)throw new a("progress_callback_failed",s.ProgressCallbackThrew(n instanceof Error?n.message:String(n)),{cause:n});let d=u.width,l=u.height,m=u.orientation,y=typeof m=="number"&&Number.isInteger(m)&&m>=1&&m<=8?m:1,h=i.HEAPU8 instanceof Uint8Array?i.HEAPU8.buffer:void 0,w=h!==void 0&&u.data.buffer!==h?new Uint8ClampedArray(u.data.buffer,u.data.byteOffset,u.data.byteLength):new Uint8ClampedArray(u.data),g={width:d,height:l,data:w};y>1&&(g.orientation=y);let p=u.exif;return p instanceof Uint8Array&&p.length>=14&&(g.exif=h!==void 0&&p.buffer!==h?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):new Uint8Array(p)),g}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,this.initPromise=null;}};var ie=["jpeg","jpg","png","svg","webp","avif"],Se=.92;function R(e){$(e?.to??"jpeg"),e?.quality!==void 0&&ke(e.quality),Ae(e?.applyOrientation),_e(e?.output),Te(e?.signal),X(e?.crop),Me(e?.preserveExif),Q(e?.maxWidth!==void 0||e?.maxHeight!==void 0||e?.scale!==void 0?e:void 0);}function ae(e){Y(e?.continueOnError),Pe(e?.reuseDecoders);}function ke(e){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)throw new a("invalid_quality",s.QualityInvalid(e))}function Ae(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ApplyOrientationInvalid(e))}function _e(e){if(e!==void 0&&e!=="blob"&&e!=="dataUrl"&&e!=="arrayBuffer")throw new a("invalid_input",s.OutputShapeInvalid(e))}function Pe(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ReuseDecodersInvalid(e))}function Y(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.ContinueOnErrorInvalid(e))}function Me(e){if(e!==void 0&&typeof e!="boolean")throw new a("invalid_input",s.PreserveExifInvalid(e))}function Te(e){if(e!==void 0&&(typeof e!="object"||e===null||typeof e.addEventListener!="function"))throw new a("invalid_input",s.SignalInvalid(e))}function U(e){if(e?.aborted)throw new a("aborted",s.Aborted)}function $(e){let r=String(e).toLowerCase();if(!ie.includes(r))throw new a("invalid_format",s.UnsupportedFormat(String(e)))}function Q(e){if(!e)return;let{maxWidth:r,maxHeight:t,scale:n}=e;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))throw new a("invalid_resize",s.ScaleInvalid(n));if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<=0))throw new a("invalid_resize",s.MaxWidthInvalid(r));if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<=0))throw new a("invalid_resize",s.MaxHeightInvalid(t))}function X(e){if(!e)return;let{x:r=0,y:t=0,width:n,height:o}=e;if(!Number.isInteger(n)||n<=0)throw new a("invalid_crop",s.CropInvalid("width",n));if(!Number.isInteger(o)||o<=0)throw new a("invalid_crop",s.CropInvalid("height",o));if(!Number.isInteger(r)||r<0)throw new a("invalid_crop",s.CropInvalid("x",r));if(!Number.isInteger(t)||t<0)throw new a("invalid_crop",s.CropInvalid("y",t))}function J(e){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new a("invalid_concurrency",s.MaxConcurrentWorkersInvalid(e))}function K(e){if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0))throw new a("invalid_input",s.TimeoutInvalid(e))}var B=new Uint8Array([69,120,105,102,0,0]),se=new Uint8Array([137,80,78,71,13,10,26,10]);function Z(e){if(e.length<B.length+8)return false;for(let r=0;r<B.length;r++)if(e[r]!==B[r])return false;return Re(e,B.length)}function Re(e,r){if(r+8>e.length)return false;let t=e[r]===73&&e[r+1]===73,n=e[r]===77&&e[r+1]===77;return !t&&!n?false:(t?e[r+2]|e[r+3]<<8:e[r+2]<<8|e[r+3])===42}function Ue(e,r){return e[r]<<8|e[r+1]}function ue(e,r){return (e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0}function de(e){try{if(!Z(e))return e;let r=B.length,t=e[r]===73,n=d=>t?e[d]|e[d+1]<<8:e[d]<<8|e[d+1],o=d=>t?(e[d+3]<<24|e[d+2]<<16|e[d+1]<<8|e[d])>>>0:(e[d]<<24|e[d+1]<<16|e[d+2]<<8|e[d+3])>>>0,i=o(r+4);if(i<8||r+i+2>e.length)return e;let c=r+i,u=n(c);for(let d=0;d<u;d++){let l=c+2+d*12;if(l+12>e.length)return e;if(n(l)!==274)continue;let m=n(l+2),y=o(l+4);if(m!==3||y!==1||(t?e[l+8]|e[l+9]<<8:e[l+8]<<8|e[l+9])===1)return e;let w=e.slice();return w[l+8]=t?1:0,w[l+9]=t?0:1,w[l+10]=0,w[l+11]=0,w}return e}catch{return e}}function ce(e,r){try{if(e.length<4||e[0]!==255||e[1]!==216||!Z(r))return e;let t=r.length+2;if(t>65535)return e;let n=2;for(;n<e.length;){if(n+4>e.length||e[n]!==255)return e;let i=e[n+1];if(i===255){n+=1;continue}if(!(i>=224&&i<=239||i===254))break;let u=Ue(e,n+2);if(u<2||n+2+u>e.length)return e;n+=2+u;}let o=new Uint8Array(e.length+4+r.length);return o.set(e.subarray(0,n),0),o[n]=255,o[n+1]=225,o[n+2]=t>>8&255,o[n+3]=t&255,o.set(r,n+4),o.set(e.subarray(n),n+4+r.length),o}catch{return e}}var L;function Be(){if(!L){L=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let t=0;t<8;t++)r=r&1?3988292384^r>>>1:r>>>1;L[e]=r>>>0;}}return L}function Fe(e){let r=Be(),t=4294967295;for(let n=0;n<e.length;n++)t=r[(t^e[n])&255]^t>>>8;return (t^4294967295)>>>0}function N(e,r,t){return e[r]===t.charCodeAt(0)&&e[r+1]===t.charCodeAt(1)&&e[r+2]===t.charCodeAt(2)&&e[r+3]===t.charCodeAt(3)}function le(e,r){try{if(e.length<33)return e;for(let u=0;u<se.length;u++)if(e[u]!==se[u])return e;if(ue(e,8)!==13||!N(e,12,"IHDR")||!Z(r))return e;let t=r.subarray(B.length),n=33;for(;n+8<=e.length;){let u=ue(e,n);if(u>e.length||n+12+u>e.length)return e;if(N(e,n+4,"IDAT")||N(e,n+4,"IEND"))break;if(N(e,n+4,"eXIf"))return e;n+=12+u;}let o=new Uint8Array(12+t.length);o[0]=t.length>>>24&255,o[1]=t.length>>>16&255,o[2]=t.length>>>8&255,o[3]=t.length&255,o.set([101,88,73,102],4),o.set(t,8);let i=Fe(o.subarray(4,8+t.length));o[8+t.length]=i>>>24&255,o[9+t.length]=i>>>16&255,o[10+t.length]=i>>>8&255,o[11+t.length]=i&255;let c=new Uint8Array(e.length+o.length);return c.set(e.subarray(0,n),0),c.set(o,n),c.set(e.subarray(n),n+o.length),c}catch{return e}}var j=16384;function re(){if(typeof OffscreenCanvas>"u"&&typeof document>"u")throw new a("unsupported_environment",s.CanvasUnsupported)}var z=null,De=5e3;async function We(){let e=ee(1,1),r=F(e,"image/avif"),t,n=new Promise(o=>{t=setTimeout(()=>o("timeout"),De);});try{let o=await Promise.race([r,n]);return o==="timeout"?(z=null,!1):o.type==="image/avif"&&o.size>0}finally{t!==void 0&&clearTimeout(t),P(e);}}function ge(){return z===null&&(z=We().catch(()=>false)),z}async function ne(e){if($(e),String(e).toLowerCase()==="avif"&&!await ge())throw new a("format_unsupported",s.FormatUnsupported("avif"))}function He(e,r,t){if(Q(t),!t)return {width:e,height:r};let{maxWidth:n,maxHeight:o,scale:i}=t;if(i!==void 0){let l=Math.max(1,Math.round(e*i)),m=Math.max(1,Math.round(r*i));return fe(l,m),{width:l,height:m}}if(n===void 0&&o===void 0)return {width:e,height:r};let c=Math.min(n!==void 0?n/e:Number.POSITIVE_INFINITY,o!==void 0?o/r:Number.POSITIVE_INFINITY);if(c>=1)return {width:e,height:r};let u=Math.min(Math.max(1,Math.round(e*c)),n!==void 0?Math.floor(n):Number.POSITIVE_INFINITY),d=Math.min(Math.max(1,Math.round(r*c)),o!==void 0?Math.floor(o):Number.POSITIVE_INFINITY);return fe(u,d),{width:u,height:d}}function fe(e,r){if(!Number.isFinite(e)||!Number.isFinite(r)||e>j||r>j)throw new a("invalid_resize",s.TargetSizeTooLarge(e,r,j))}async function te(e){if(typeof FileReader<"u")return new Promise((r,t)=>{let n=new FileReader;n.onloadend=()=>{typeof n.result=="string"?r(n.result):t(new a("render_encode_failed",s.BlobToBase64Failed));},n.onerror=()=>t(new a("render_encode_failed",s.BlobToBase64FailedWithCause(n.error?.message??"FileReader failed"),{cause:n.error??void 0})),n.readAsDataURL(e);});try{let r=await e.arrayBuffer(),t=new Uint8Array(r),n="",o=32768;for(let c=0;c<t.length;c+=o)n+=String.fromCharCode(...t.subarray(c,c+o));let i=btoa(n);return `data:${e.type};base64,${i}`}catch(r){throw new a("render_encode_failed",s.BlobToBase64FailedWithCause(r instanceof Error?r.message:String(r)),{cause:r})}}function F(e,r,t){return "convertToBlob"in e?e.convertToBlob({type:r,quality:t}):new Promise((n,o)=>{e.toBlob(i=>{i?n(i):o(new a("render_encode_failed",s.CanvasToBlobFailed(r)));},r,t);})}function ee(e,r){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,r);if(typeof document<"u"){let t=document.createElement("canvas");return t.width=e,t.height=r,t}throw new a("unsupported_environment",s.CanvasUnsupported)}function P(e){let r=e;typeof r.close=="function"?r.close():e.width=0;}function me(e,r,t,n){if(typeof ImageData<"u")e.putImageData(new ImageData(r,t,n),0,0);else {let o=e.createImageData(t,n);o.data.set(r),e.putImageData(o,0,0);}}function $e(e,r,t){switch(e){case 2:return [-1,0,0,1,r,0];case 3:return [-1,0,0,-1,r,t];case 4:return [1,0,0,-1,0,t];case 5:return [0,1,1,0,0,0];case 6:return [0,1,-1,0,t,0];case 7:return [0,-1,-1,0,t,r];case 8:return [0,-1,1,0,0,r];default:return null}}function Le(e,r){return !r||typeof e!="number"||!Number.isInteger(e)?1:e>=1&&e<=8?e:1}async function pe(e,r,t,n,o){let i=r.exif;if(!t||!i||i.length===0)return e;let c=o?de(i):i,u=new Uint8Array(await e.arrayBuffer()),d=n==="jpeg"?ce(u,c):le(u,c);return d===u?e:new Blob([d.buffer],{type:e.type})}async function he(e,r,t,n,o=true,i,c=false){$(r),X(i);let u=r.toLowerCase();if(u==="avif"&&!await ge())throw new a("format_unsupported",s.FormatUnsupported("avif"));let{width:d,height:l,data:m}=e;if(!Number.isInteger(d)||d<=0||!Number.isInteger(l)||l<=0)throw new a("render_encode_failed",s.InvalidDimensions(d,l));let y=d*l*4;if(m.length!==y)throw new a("render_encode_failed",s.DataLengthMismatch(y,d,l,m.length));let h=Le(e.orientation,o),g=!(e.orientation!==void 0&&e.orientation>=2&&e.orientation<=8)||o,p=$e(h,d,l),O=h>=5,k=O?l:d,M=O?d:l,A=i?.x??0,v=i?.y??0,b=i?i.width:k,E=i?i.height:M;if(i&&(A+b>k||v+E>M))throw new a("invalid_crop",s.CropOutOfBounds(A,v,b,E,k,M));let C=He(b,E,n),q=C.width!==b||C.height!==E,I=p!==null||i!==void 0,f=ee(C.width,C.height),S=f.getContext("2d");if(!S)throw new a("render_encode_failed",s.ContextUnavailable);if(I||q){let x=ee(d,l),H=x.getContext("2d");if(!H)throw new a("render_encode_failed",s.ContextUnavailable);if(me(H,m,d,l),I){let D=C.width/b,W=C.height/E,ye=p?p[0]:1,xe=p?p[1]:0,Ce=p?p[2]:0,Ie=p?p[3]:1,Oe=p?p[4]:0,Ee=p?p[5]:0;S.setTransform(ye*D,xe*W,Ce*D,Ie*W,D*(Oe-A),W*(Ee-v)),S.drawImage(x,0,0);}else S.drawImage(x,0,0,C.width,C.height);P(x);}else me(S,m,d,l);if(u==="png"){let x=await F(f,"image/png");return P(f),pe(x,e,c,"png",g)}if(u==="jpeg"||u==="jpg"){let x=await F(f,"image/jpeg",t);return P(f),pe(x,e,c,"jpeg",g)}if(u==="webp"){let x=await F(f,"image/webp",t);return P(f),x}if(u==="avif"){let x=await F(f,"image/avif",t);if(P(f),x.type!=="image/avif")throw new a("format_unsupported",s.FormatUnsupported("avif"));return x}if(u==="svg"){let x=await F(f,"image/png");P(f);let H=await te(x),D=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${C.width} ${C.height}" width="${C.width}" height="${C.height}">
2
- <image width="${C.width}" height="${C.height}" href="`,W=`" />
3
- </svg>`;return new Blob([D,H,W],{type:"image/svg+xml"})}throw new a("invalid_format",s.UnsupportedFormat(String(r)))}async function V(e,r,t,n){let o=n?.continueOnError===true,i=n?.signal,c=new Array(e.length),u=0,d=false,l=0,m=null,y=-1,h=0,w=[],g,p=new Promise(v=>{g=v;}),O=()=>g?.();i&&!o&&i.addEventListener("abort",O,{once:true});let k=async()=>{for(;!d&&!i?.aborted||o;){let v=u;if(u+=1,v>=e.length)return;if(o&&i?.aborted){let b=new a("aborted",s.Aborted);for(let E=v;E<e.length;E++)c[E]={index:E,ok:false,error:b};u=e.length;return}try{let b=await t(e[v],v);c[v]={index:v,ok:!0,result:b},l+=1;}catch(b){if(h+=1,o){c[v]={index:v,ok:false,error:b instanceof Error?b:new Error(String(b))};continue}d?w.length<2&&w.push(b instanceof Error?b.message:String(b)):(d=true,m=b,y=v,g?.());}}},M=Math.min(r,e.length),A=Array.from({length:M},()=>k());try{if(o)return await Promise.all(A),c;if(await Promise.race([Promise.all(A),p]),l===e.length)return c.map(v=>{if(!v||!v.ok)throw new a("batch_item_failed",s.BatchItemProducedNoResult(v?.index));return v.result});if(i?.aborted)throw new a("aborted",s.Aborted);if(d){let v=m instanceof Error?m.message:String(m),b=s.ConvertManyItemFailed(y+1,e.length,v);throw h>1&&(b+=s.ConvertManyExtraFailures(h,e.length),w.length>0&&(b+=s.ConvertManyOtherErrors(w))),new a("batch_item_failed",b,{cause:m,itemIndex:y,itemTotal:e.length,failedCount:h})}throw new a("batch_item_failed",s.BatchEndedWithoutResult)}finally{i?.removeEventListener("abort",O);}}function Ne(){let e=typeof navigator<"u"&&typeof navigator.hardwareConcurrency=="number"?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var G=new Map;function ze(e,r,t){let n=G.get(e);n||(n={active:0,waiters:[]},G.set(e,n));let o={granted:false,released:false},i=()=>{let d=n.waiters.shift();d?d():n.active===0&&n.waiters.length===0&&G.delete(e);},c=()=>{if(!o.released)if(o.released=true,o.granted)o.granted=false,n.active-=1,i();else {let d=n.waiters.indexOf(u);d!==-1&&n.waiters.splice(d,1),n.active===0&&n.waiters.length===0&&G.delete(e);}},u=()=>{o.released||(o.granted=true,n.active+=1,t(c));};return n.active<r?u():n.waiters.push(u),c}function ve(e){return new a("progress_callback_failed",s.ProgressCallbackThrew(e instanceof Error?e.message:String(e)),{cause:e})}function be(e,r){return new Promise((t,n)=>{if(typeof Worker>"u"){n(new a("worker_unsupported",s.WorkerUnsupported));return}if(r.decoder!==void 0){n(new a("invalid_input",s.WorkerDecoderUnsupported));return}try{R(r),J(r?.maxConcurrentWorkers),K(r?.timeoutMs);}catch(I){n(I);return}if(r.signal?.aborted){n(new a("aborted",s.Aborted));return}let o={progressMessages:0},i,c=false,u,d,l=()=>{c||(c=true,u!==void 0&&clearTimeout(u),r.signal?.removeEventListener("abort",m),i&&(i.removeEventListener("message",h),i.removeEventListener("messageerror",g),i.removeEventListener("error",w),i.terminate()),d?.());},m=()=>{l(),n(new a("aborted",s.Aborted));};r.signal?.addEventListener("abort",m,{once:true});let y=r.timeoutMs??6e4;y>0&&(u=setTimeout(()=>{l(),n(new a("worker_timeout",s.WorkerTimeout(y,{progressMessages:o.progressMessages,lastPercent:o.lastPercent,unknownType:o.unknownType,workerUrl:r.workerUrl})));},y));let h=I=>{let f=I.data;if(f?.type==="progress"){o.progressMessages+=1;let S=T(f.percent);if(o.lastPercent=S,S>=100)return;try{r.onProgress?.(S);}catch(x){l(),n(ve(x));}return}if(f?.type!=="result"){typeof f?.type=="string"&&(o.unknownType=f.type);return}if(l(),f.ok&&f.blob!==void 0){try{r.onProgress?.(100);}catch(S){n(ve(S));return}t(f.blob);}else n(new a("worker_failed",f.error??s.WorkerConversionFailed));},w=I=>{l();let f=I.filename?` (${I.filename}:${I.lineno})`:"";n(new a("worker_failed",`${I.message||s.WorkerFailed(r.workerUrl)}${f}`));},g=I=>{l();let f=I.data;n(new a("worker_failed",f instanceof Error?f.message:f!==void 0?String(f):s.WorkerFailed(r.workerUrl),{cause:f}));},{workerUrl:p,onProgress:O,timeoutMs:k,workerType:M,maxConcurrentWorkers:A,signal:v,...b}=r,E=I=>{if(d=I,!c){try{i=new Worker(p,r.workerType==="module"?{type:"module"}:void 0);}catch(f){l(),n(new a("worker_create_failed",s.WorkerCreateFailed(f instanceof Error?f.message:String(f)),{cause:f}));return}i.addEventListener("message",h),i.addEventListener("messageerror",g),i.addEventListener("error",w);try{i.postMessage({input:e,options:b});}catch(f){l(),n(new a("worker_post_failed",s.WorkerPostFailed(f instanceof Error?f.message:String(f)),{cause:f}));}}},C=`${String(p)}|${r.workerType??"classic"}`,q=we(r.maxConcurrentWorkers);d=ze(C,q,E);})}function we(e){return typeof e=="number"&&Number.isInteger(e)?Math.max(1,e):Ne()}async function Ve(e,r){if(!Array.isArray(e))throw new a("invalid_input",s.InputsMustBeArray);if(typeof Worker>"u")throw new a("worker_unsupported",s.WorkerUnsupported);if(r.decoder!==void 0)throw new a("invalid_input",s.WorkerDecoderUnsupported);R(r),Y(r?.continueOnError),J(r?.maxConcurrentWorkers),K(r?.timeoutMs);let{onProgress:t,continueOnError:n,...o}=r??{};return V(e,we(r?.maxConcurrentWorkers),(i,c)=>be(i,{...o,...t!==void 0?{onProgress:u=>t(c,u)}:{}}),{continueOnError:r?.continueOnError===true,signal:r?.signal})}function _r(){}async function Ge(e,r){return r==="dataUrl"?await te(e):r==="arrayBuffer"?await e.arrayBuffer():e}async function qe(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<"u"&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e!==null&&typeof e=="object"&&typeof e.arrayBuffer=="function"){let r=await e.arrayBuffer();if(r instanceof ArrayBuffer)return new Uint8Array(r)}if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}throw new a("invalid_input",s.UnsupportedInputType(Object.prototype.toString.call(e)))}function Ye(e){if(typeof e!="function")return;let r=false,t,n=o=>{try{e(o);}catch(i){throw new a("progress_callback_failed",s.ProgressCallbackThrew(i instanceof Error?i.message:String(i)),{cause:i})}};return {report:o=>{if(r)return;let i=T(o);if(!(i>=100))try{e(i);}catch(c){t=t??c;}},complete:()=>{if(!r){if(r=true,t!==void 0)throw new a("progress_callback_failed",s.ProgressCallbackThrew(t instanceof Error?t.message:String(t)),{cause:t});n(100);}}}}async function Qe(e,r){let t=r?.to??"jpeg";R(r),re(),await ne(t);let n=r?.signal;U(n);let o=r?.maxWidth!==void 0||r?.maxHeight!==void 0||r?.scale!==void 0?r:void 0,i=await qe(e);U(n);let c=r?.decoder??new _,u=!r?.decoder,d=false,l=()=>{if(!(!u||d)){d=true;try{c.free();}catch{}}};try{try{await c.initialize();}catch(g){throw new a("decoder_init_failed",s.DecoderInitFailed(g instanceof Error?g.message:String(g)),{cause:g})}U(n);let m=Ye(r?.onProgress),y=await c.decode(i,m?m.report:void 0);l(),U(n);let h=r?.quality!==void 0?r.quality:.92,w;try{w=await he(y,t,h,o,r?.applyOrientation??!0,r?.crop,r?.preserveExif??!1);}catch(g){throw g instanceof a?g:new a("render_encode_failed",s.RenderEncodeFailed(t,g instanceof Error?g.message:String(g)),{cause:g})}return U(n),m?.complete(),Ge(w,r?.output??"blob")}finally{l();}}var oe=class{max;idle=[];waiters=[];leasedCount=0;disposed=false;constructor(r){this.max=Math.max(1,r);}async acquire(){let r=this.idle.pop();return r||(this.leasedCount<this.max?(this.leasedCount+=1,new _):new Promise(t=>this.waiters.push(t)))}release(r){if(this.disposed){try{r.free();}catch{}return}let t=this.waiters.shift();t?t(r):this.idle.push(r);}dispose(){this.disposed=true;for(let r of this.idle)try{r.free();}catch{}this.idle.length=0;for(let r of this.waiters.splice(0))r(new _);}};async function Pr(e,r){if(!Array.isArray(e))throw new a("invalid_input",s.InputsMustBeArray);let t=r?.concurrency??4;if(!Number.isInteger(t)||t<1)throw new a("invalid_concurrency",s.ConcurrencyInvalid(t));R(r),ae(r),re(),await ne(r?.to??"jpeg");let{concurrency:n,onProgress:o,continueOnError:i,reuseDecoders:c,...u}=r??{},l=c===true&&r?.decoder===void 0?new oe(Math.min(t,e.length)):null;try{return await V(e,t,async(m,y)=>{let h=l?await l.acquire():null;try{return await Qe(m,{...u,...h?{decoder:h}:{},onProgress:o!==void 0?w=>o(y,w):void 0})}finally{h&&l.release(h);}},{continueOnError:r?.continueOnError===!0,signal:r?.signal})}finally{l?.dispose();}}export{Se as DEFAULT_QUALITY,a as HeicConverterError,_ as LibheifDecoder,ie as SUPPORTED_FORMATS,Qe as convertHeic,be as convertHeicInWorker,Pr as convertMany,Ve as convertManyInWorker,_r as freeSharedDecoder};
1
+ import{HeicConverterError as e,Messages as t,validateConvertOptions as n,throwIfAborted as i,DEFAULT_QUALITY as r,validateConcurrency as o,validateBatchOptions as a,runnerCountFor as s,runBoundedBatch as c,clampPercent as d,validateFormat as f,validateCrop as u,validateResize as h}from"./chunk-PTRQ7ZFB.mjs";export{DEFAULT_QUALITY,HeicConverterError,SUPPORTED_FORMATS}from"./chunk-PTRQ7ZFB.mjs";var l=new WeakSet,w=/[\u0000-\u001f\u007f-\u009f]+/g,m=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const e=++this.initGeneration,t={};this.options?.moduleOverrides&&Object.assign(t,this.options.moduleOverrides),this.options?.locateFile&&(t.locateFile=this.options.locateFile),this.options?.wasmBinary&&(t.wasmBinary=this.options.wasmBinary);const n=import("./heic-decoder-43VH2M3C.mjs").then(({default:e})=>e(t)).then(t=>{const n=new t.HeicDecoder;return e!==this.initGeneration?(n.delete(),null):(this.module=t,this.decoderInstance=n,t)}).catch(e=>{throw this.initPromise===n&&(this.initPromise=null),e});this.initPromise=n}await this.initPromise}async decode(n,i){if(this.module&&this.decoderInstance||await this.initialize(),!this.module||!this.decoderInstance)throw new e("decode_failed",t.DecoderFreedDuringDecode);let r;const o=i?e=>{try{i(d(e))}catch(e){r=r??e}}:null,a=this.module,s=this.decoderInstance;let c;try{if("function"==typeof s.decodeFromPointer&&"function"==typeof a._malloc&&"function"==typeof a._free&&a.HEAPU8 instanceof Uint8Array&&n.buffer!==a.HEAPU8.buffer){const i=a._malloc(n.byteLength);if(0===i)throw new e("decode_failed",t.DecodeInputAllocFailed(n.byteLength));try{a.HEAPU8.set(n,i),c=s.decodeFromPointer(i,n.byteLength,o)}finally{a._free(i)}}else c=s.decode(n,o)}catch(i){if(i instanceof e)throw i;throw l.add(this),new e("decode_failed",t.DecodeFaulted(n.byteLength),{cause:i})}if("string"==typeof c)throw new e("decode_failed",t.DecodeFailedWithDetail(function(e){const t=e.replace(w," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(c),n.byteLength));if(!c)throw new e("decode_failed",t.DecodeFailed(n.byteLength));if(void 0!==r)throw new e("progress_callback_failed",t.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r});const f=c.width,u=c.height,h=c.orientation,m="number"==typeof h&&Number.isInteger(h)&&h>=1&&h<=8?h:1,g=a.HEAPU8 instanceof Uint8Array?a.HEAPU8.buffer:void 0,p={width:f,height:u,data:void 0!==g&&c.data.buffer!==g?new Uint8ClampedArray(c.data.buffer,c.data.byteOffset,c.data.byteLength):new Uint8ClampedArray(c.data)};m>1&&(p.orientation=m);const y=c.exif;return y instanceof Uint8Array&&y.length>=14&&(p.exif=void 0!==g&&y.buffer!==g?new Uint8Array(y.buffer,y.byteOffset,y.byteLength):new Uint8Array(y)),p}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,l.delete(this),this.initPromise=null}},g=16384;function p(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new e("unsupported_environment",t.CanvasUnsupported)}var y=null;function v(){if(null===y){const e=async function(){let e;try{e=P(1,1)}catch{return}const t=F(e,"image/avif");let n;const i=new Promise(e=>{n=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,i]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==n&&clearTimeout(n),B(e)}}().catch(()=>!1);y=e,e.then(t=>{void 0===t&&y===e&&(y=null)})}return y}async function b(n){if(f(n),"avif"===String(n).toLowerCase()&&!1===await v())throw new e("format_unsupported",t.FormatUnsupported("avif"))}function _(n,i){if(!Number.isFinite(n)||!Number.isFinite(i)||n>g||i>g)throw new e("invalid_resize",t.TargetSizeTooLarge(n,i,g))}async function I(n){if("undefined"!=typeof FileReader)return new Promise((i,r)=>{const o=new FileReader;o.onloadend=()=>{"string"==typeof o.result?i(o.result):r(new e("render_encode_failed",t.BlobToBase64Failed))},o.onerror=()=>r(new e("render_encode_failed",t.BlobToBase64FailedWithCause(o.error?.message??"FileReader failed"),{cause:o.error??void 0})),o.readAsDataURL(n)});try{const e=await n.arrayBuffer(),t=new Uint8Array(e);let i="";const r=32768;for(let e=0;e<t.length;e+=r)i+=String.fromCharCode(...t.subarray(e,e+r));const o=btoa(i);return`data:${n.type};base64,${o}`}catch(n){throw new e("render_encode_failed",t.BlobToBase64FailedWithCause(n instanceof Error?n.message:String(n)),{cause:n})}}function F(n,i,r){return"convertToBlob"in n?n.convertToBlob({type:i,quality:r}):new Promise((o,a)=>{n.toBlob(n=>{n?o(n):a(new e("render_encode_failed",t.CanvasToBlobFailed(i)))},i,r)})}function P(n,i){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(n,i);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=n,e.height=i,e}throw new e("unsupported_environment",t.CanvasUnsupported)}function B(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function U(e,t,n,i){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,n,i),0,0);else{const r=e.createImageData(n,i);r.data.set(t),e.putImageData(r,0,0)}}var x=!1;async function A(e,t,n,i,r){const o=t.exif;if(!n||!o||0===o.length)return e;const a=await import("./exif-MBEKII5G.mjs").catch(()=>null);if(!a)return x||(x=!0,console.warn("@keeratita/heic-converter: the EXIF injector chunk could not be loaded — converted without metadata; serve every file in dist/ together, with dist/exif-*.mjs as JavaScript.")),e;const{injectExifIntoJpeg:s,injectExifIntoPng:c,normalizeOrientationTag:d}=a,f=r?d(o):o,u=new Uint8Array(await e.arrayBuffer()),h="jpeg"===i?s(u,f):c(u,f);return h===u?e:new Blob([h.buffer],{type:e.type})}function C(){return import("./worker-FNMN2SJV.mjs").catch(n=>{const i=n instanceof Error?n.message:String(n);throw new e("worker_load_failed",t.WorkerChunkLoadFailed(i),{cause:n})})}function T(e,t){return C().then(n=>n.convertHeicInWorker(e,t))}function E(e,t){return C().then(n=>n.convertManyInWorker(e,t))}function O(){}async function D(o,a){const s=a?.to??"jpeg";n(a),p(),await b(s);const c=a?.signal;i(c);const l=void 0!==a?.maxWidth||void 0!==a?.maxHeight||void 0!==a?.scale?a:void 0,w=await async function(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if("undefined"!=typeof Blob&&n instanceof Blob)return new Uint8Array(await n.arrayBuffer());if(null!==n&&"object"==typeof n&&"function"==typeof n.arrayBuffer){const e=await n.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(n)){const e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new e("invalid_input",t.UnsupportedInputType(Object.prototype.toString.call(n)))}(o);i(c);const g=a?.decoder??new m,y=!a?.decoder;let x=!1;const C=()=>{if(y&&!x){x=!0;try{g.free()}catch{}}};try{try{await g.initialize()}catch(n){throw new e("decoder_init_failed",t.DecoderInitFailed(n instanceof Error?n.message:String(n)),{cause:n})}i(c);const n=function(n){if("function"!=typeof n)return;let i,r=!1;return{report:e=>{if(r)return;const t=d(e);if(!(t>=100))try{n(t)}catch(e){i=i??e}},complete:()=>{if(!r){if(r=!0,void 0!==i)throw new e("progress_callback_failed",t.ProgressCallbackThrew(i instanceof Error?i.message:String(i)),{cause:i});(()=>{try{n(100)}catch(n){throw new e("progress_callback_failed",t.ProgressCallbackThrew(n instanceof Error?n.message:String(n)),{cause:n})}})()}}}}(a?.onProgress),o=await g.decode(w,n?n.report:void 0);C(),i(c);const m=void 0!==a?.quality?a.quality:r;let p;try{p=await async function(n,i,r,o,a=!0,s,c=!1){f(i),u(s);const d=i.toLowerCase();if("avif"===d&&!1===await v())throw new e("format_unsupported",t.FormatUnsupported("avif"));const{width:l,height:w,data:m}=n;if(!Number.isInteger(l)||l<=0||!Number.isInteger(w)||w<=0)throw new e("render_encode_failed",t.InvalidDimensions(l,w));const g=l*w*4;if(m.length!==g)throw new e("render_encode_failed",t.DataLengthMismatch(g,l,w,m.length));const p=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(n.orientation,a),y=!(void 0!==n.orientation&&n.orientation>=2&&n.orientation<=8)||a,b=function(e,t,n){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return null}}(p,l,w),x=p>=5,C=x?w:l,T=x?l:w,E=s?.x??0,O=s?.y??0,D=s?s.width:C,M=s?s.height:T;if(s&&(E+D>C||O+M>T))throw new e("invalid_crop",t.CropOutOfBounds(E,O,D,M,C,T));const S=function(e,t,n){if(h(n),!n)return{width:e,height:t};const{maxWidth:i,maxHeight:r,scale:o}=n;if(void 0!==o){const n=Math.max(1,Math.round(e*o)),i=Math.max(1,Math.round(t*o));return _(n,i),{width:n,height:i}}if(void 0===i&&void 0===r)return{width:e,height:t};const a=Math.min(void 0!==i?i/e:Number.POSITIVE_INFINITY,void 0!==r?r/t:Number.POSITIVE_INFINITY);if(a>=1)return{width:e,height:t};const s=Math.min(Math.max(1,Math.round(e*a)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),c=Math.min(Math.max(1,Math.round(t*a)),void 0!==r?Math.floor(r):Number.POSITIVE_INFINITY);return _(s,c),{width:s,height:c}}(D,M,o),N=S.width!==D||S.height!==M,j=null!==b||void 0!==s,k=P(S.width,S.height),L=k.getContext("2d");if(!L)throw new e("render_encode_failed",t.ContextUnavailable);if(j||N){const n=P(l,w),i=n.getContext("2d");if(!i)throw new e("render_encode_failed",t.ContextUnavailable);if(U(i,m,l,w),j){const e=S.width/D,t=S.height/M,i=b?b[0]:1,r=b?b[1]:0,o=b?b[2]:0,a=b?b[3]:1,s=b?b[4]:0,c=b?b[5]:0;L.setTransform(i*e,r*t,o*e,a*t,e*(s-E),t*(c-O)),L.drawImage(n,0,0)}else L.drawImage(n,0,0,S.width,S.height);B(n)}else U(L,m,l,w);if("png"===d){const e=await F(k,"image/png");return B(k),A(e,n,c,"png",y)}if("jpeg"===d||"jpg"===d){const e=await F(k,"image/jpeg",r);return B(k),A(e,n,c,"jpeg",y)}if("webp"===d){const e=await F(k,"image/webp",r);return B(k),e}if("avif"===d){const n=await F(k,"image/avif",r);if(B(k),"image/avif"!==n.type)throw new e("format_unsupported",t.FormatUnsupported("avif"));return n}if("svg"===d){const e=await F(k,"image/png");B(k);const t=await I(e),n=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${S.width} ${S.height}" width="${S.width}" height="${S.height}">\n <image width="${S.width}" height="${S.height}" href="`;return new Blob([n,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new e("invalid_format",t.UnsupportedFormat(String(i)))}(o,s,m,l,a?.applyOrientation??!0,a?.crop,a?.preserveExif??!1)}catch(n){if(n instanceof e)throw n;throw new e("render_encode_failed",t.RenderEncodeFailed(s,n instanceof Error?n.message:String(n)),{cause:n})}return i(c),n?.complete(),async function(e,t){return"dataUrl"===t?await I(e):"arrayBuffer"===t?await e.arrayBuffer():e}(p,a?.output??"blob")}finally{C()}}var M=class{max;idle=[];waiters=[];leasedCount=0;disposed=!1;constructor(e){this.max=Math.max(1,e)}async acquire(){return this.idle.pop()||(this.leasedCount<this.max?(this.leasedCount+=1,new m):new Promise(e=>this.waiters.push(e)))}release(e){if(this.disposed){try{e.free()}catch{}return}if(function(e){return l.has(e)}(e)){this.leasedCount-=1;try{e.free()}catch{}const t=this.waiters.shift();return void(t&&(this.leasedCount+=1,t(new m)))}const t=this.waiters.shift();t?t(e):this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0;for(const e of this.waiters.splice(0))e(new m)}};async function S(i,r){if(!Array.isArray(i))throw new e("invalid_input",t.InputsMustBeArray);const d=r?.concurrency??4;o(d),n(r),a(r),p(),await b(r?.to??"jpeg");const{concurrency:f,onProgress:u,continueOnError:h,reuseDecoders:l,...w}=r??{},m=!0===l&&void 0===r?.decoder?new M(s(d,i.length)):null;try{return await c(i,d,async(e,t)=>{const n=m?await m.acquire():null;try{return await D(e,{...w,...n?{decoder:n}:{},onProgress:void 0!==u?e=>u(t,e):void 0})}finally{n&&m.release(n)}},{continueOnError:!0===r?.continueOnError,signal:r?.signal})}finally{m?.dispose()}}export{m as LibheifDecoder,D as convertHeic,T as convertHeicInWorker,S as convertMany,E as convertManyInWorker,O as freeSharedDecoder};
@@ -0,0 +1 @@
1
+ import{HeicConverterError as e,validateConvertOptions as r,Messages as t,validateContinueOnError as o,runBoundedBatch as n,clampPercent as s}from"./chunk-PTRQ7ZFB.mjs";var i="Web Worker is not supported in the current environment",a="The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",u=e=>"Worker failed"+(void 0!==e?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:"");function c(r){if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new e("invalid_concurrency",`maxConcurrentWorkers must be a positive integer, got: ${r}`)}function d(r){if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0))throw new e("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${r}`)}function l(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var p=new Map;function w(e,r,t){let o=p.get(e);o||(o={active:0,waiters:[]},p.set(e,o));const n={granted:!1,released:!1},s=()=>{if(!n.released)if(n.released=!0,n.granted)n.granted=!1,o.active-=1,(()=>{const r=o.waiters.shift();r?r():0===o.active&&0===o.waiters.length&&p.delete(e)})();else{const r=o.waiters.indexOf(i);-1!==r&&o.waiters.splice(r,1),0===o.active&&0===o.waiters.length&&p.delete(e)}},i=()=>{n.released||(n.granted=!0,o.active+=1,t(s))};return o.active<r?i():o.waiters.push(i),s}function m(r){return new e("progress_callback_failed",t.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r})}var g={reserveWorkerSlot:w,workerSlots:p,defaultMaxWorkers:l};function v(o,n){return new Promise((l,p)=>{if("undefined"==typeof Worker)return void p(new e("worker_unsupported",i));if(void 0!==n.decoder)return void p(new e("invalid_input",a));try{r(n),c(n?.maxConcurrentWorkers),d(n?.timeoutMs)}catch(e){return void p(e)}if(n.signal?.aborted)return void p(new e("aborted",t.Aborted));const g={progressMessages:0};let v,k,h,y=!1;const b=()=>{y||(y=!0,void 0!==k&&clearTimeout(k),n.signal?.removeEventListener("abort",W),v&&(v.removeEventListener("message",E),v.removeEventListener("messageerror",x),v.removeEventListener("error",T),v.terminate()),h?.())},W=()=>{b(),p(new e("aborted",t.Aborted))};n.signal?.addEventListener("abort",W,{once:!0});const M=n.timeoutMs??6e4,$=Date.now();let _;M>0&&(k=setTimeout(()=>{b(),p(new e("worker_timeout",((e,r)=>{if(void 0===r.startedAt)return`Web Worker conversion timed out after ${e}ms before a worker slot was granted — the deadline was spent waiting behind other conversions (timeoutMs includes queue wait). Raise maxConcurrentWorkers or timeoutMs, or set timeoutMs to 0 to disable the timeout.`;const t=[`${r.progressMessages} progress message(s) received`];return void 0!==r.queueWaitMs&&r.queueWaitMs>0&&t.unshift(`started after ${r.queueWaitMs}ms queued`),void 0!==r.lastPercent&&t.push(`last percent ${r.lastPercent}`),void 0!==r.unknownType&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),void 0!==r.workerUrl&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`})(M,{progressMessages:g.progressMessages,lastPercent:g.lastPercent,unknownType:g.unknownType,workerUrl:n.workerUrl,startedAt:_,queueWaitMs:void 0===_?void 0:_-$})))},M));const E=r=>{const t=r.data;if("progress"===t?.type){g.progressMessages+=1;const e=s(t.percent);if(g.lastPercent=e,e>=100)return;try{n.onProgress?.(e)}catch(e){b(),p(m(e))}return}if("result"===t?.type)if(b(),t.ok&&void 0!==t.blob){try{n.onProgress?.(100)}catch(e){return void p(m(e))}l(t.blob)}else p(new e("worker_failed",t.error??"Worker conversion failed"));else"string"==typeof t?.type&&(g.unknownType=t.type)},T=r=>{b();const t=r.filename?` (${r.filename}:${r.lineno})`:"";p(new e("worker_failed",`${r.message||u(n.workerUrl)}${t}`))},x=r=>{b();const t=r.data;p(new e("worker_failed",t instanceof Error?t.message:void 0!==t?String(t):u(n.workerUrl),{cause:t}))},{workerUrl:P,onProgress:C,timeoutMs:S,workerType:L,maxConcurrentWorkers:U,signal:A,...q}=n,I=`${String(P)}|${n.workerType??"classic"}`,O=f(n.maxConcurrentWorkers);h=w(I,O,r=>{if(h=r,!y){_=Date.now();try{v=new Worker(P,"module"===n.workerType?{type:"module"}:void 0)}catch(r){return b(),void p(new e("worker_create_failed",(t=r instanceof Error?r.message:String(r),`Failed to create Web Worker: ${t}`),{cause:r}))}v.addEventListener("message",E),v.addEventListener("messageerror",x),v.addEventListener("error",T);try{v.postMessage({input:o,options:q})}catch(r){b(),p(new e("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(r instanceof Error?r.message:String(r)),{cause:r}))}}var t})})}function f(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):l()}async function k(s,u){if(!Array.isArray(s))throw new e("invalid_input",t.InputsMustBeArray);if("undefined"==typeof Worker)throw new e("worker_unsupported",i);if(void 0!==u.decoder)throw new e("invalid_input",a);r(u),o(u?.continueOnError),c(u?.maxConcurrentWorkers),d(u?.timeoutMs);const{onProgress:l,continueOnError:p,...w}=u??{};return n(s,f(u?.maxConcurrentWorkers),(e,r)=>v(e,{...w,...void 0!==l?{onProgress:e=>l(r,e)}:{}}),{continueOnError:!0===u?.continueOnError,signal:u?.signal})}export{g as __semaphoreTestHooks,v as convertHeicInWorker,k as convertManyInWorker};
@@ -0,0 +1 @@
1
+ var e=require("./chunk-FKEXCXR4.js"),r="Web Worker is not supported in the current environment",t="The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",o=e=>"Worker failed"+(void 0!==e?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:"");function n(r){if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new e.HeicConverterError("invalid_concurrency",`maxConcurrentWorkers must be a positive integer, got: ${r}`)}function s(r){if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0))throw new e.HeicConverterError("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${r}`)}function i(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var a=new Map;function c(e,r,t){let o=a.get(e);o||(o={active:0,waiters:[]},a.set(e,o));const n={granted:!1,released:!1},s=()=>{if(!n.released)if(n.released=!0,n.granted)n.granted=!1,o.active-=1,(()=>{const r=o.waiters.shift();r?r():0===o.active&&0===o.waiters.length&&a.delete(e)})();else{const r=o.waiters.indexOf(i);-1!==r&&o.waiters.splice(r,1),0===o.active&&0===o.waiters.length&&a.delete(e)}},i=()=>{n.released||(n.granted=!0,o.active+=1,t(s))};return o.active<r?i():o.waiters.push(i),s}function u(r){return new e.HeicConverterError("progress_callback_failed",e.Messages.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r})}var d={reserveWorkerSlot:c,workerSlots:a,defaultMaxWorkers:i};function v(i,a){return new Promise((d,v)=>{if("undefined"==typeof Worker)return void v(new e.HeicConverterError("worker_unsupported",r));if(void 0!==a.decoder)return void v(new e.HeicConverterError("invalid_input",t));try{e.validateConvertOptions(a),n(a?.maxConcurrentWorkers),s(a?.timeoutMs)}catch(e){return void v(e)}if(a.signal?.aborted)return void v(new e.HeicConverterError("aborted",e.Messages.Aborted));const p={progressMessages:0};let w,g,m,f=!1;const k=()=>{f||(f=!0,void 0!==g&&clearTimeout(g),a.signal?.removeEventListener("abort",h),w&&(w.removeEventListener("message",C),w.removeEventListener("messageerror",W),w.removeEventListener("error",M),w.terminate()),m?.())},h=()=>{k(),v(new e.HeicConverterError("aborted",e.Messages.Aborted))};a.signal?.addEventListener("abort",h,{once:!0});const y=a.timeoutMs??6e4,b=Date.now();let E;y>0&&(g=setTimeout(()=>{k(),v(new e.HeicConverterError("worker_timeout",((e,r)=>{if(void 0===r.startedAt)return`Web Worker conversion timed out after ${e}ms before a worker slot was granted — the deadline was spent waiting behind other conversions (timeoutMs includes queue wait). Raise maxConcurrentWorkers or timeoutMs, or set timeoutMs to 0 to disable the timeout.`;const t=[`${r.progressMessages} progress message(s) received`];return void 0!==r.queueWaitMs&&r.queueWaitMs>0&&t.unshift(`started after ${r.queueWaitMs}ms queued`),void 0!==r.lastPercent&&t.push(`last percent ${r.lastPercent}`),void 0!==r.unknownType&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),void 0!==r.workerUrl&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`})(y,{progressMessages:p.progressMessages,lastPercent:p.lastPercent,unknownType:p.unknownType,workerUrl:a.workerUrl,startedAt:E,queueWaitMs:void 0===E?void 0:E-b})))},y));const C=r=>{const t=r.data;if("progress"===t?.type){p.progressMessages+=1;const r=e.clampPercent(t.percent);if(p.lastPercent=r,r>=100)return;try{a.onProgress?.(r)}catch(e){k(),v(u(e))}return}if("result"===t?.type)if(k(),t.ok&&void 0!==t.blob){try{a.onProgress?.(100)}catch(e){return void v(u(e))}d(t.blob)}else v(new e.HeicConverterError("worker_failed",t.error??"Worker conversion failed"));else"string"==typeof t?.type&&(p.unknownType=t.type)},M=r=>{k();const t=r.filename?` (${r.filename}:${r.lineno})`:"";v(new e.HeicConverterError("worker_failed",`${r.message||o(a.workerUrl)}${t}`))},W=r=>{k();const t=r.data;v(new e.HeicConverterError("worker_failed",t instanceof Error?t.message:void 0!==t?String(t):o(a.workerUrl),{cause:t}))},{workerUrl:H,onProgress:$,timeoutMs:_,workerType:x,maxConcurrentWorkers:T,signal:P,...S}=a,L=`${String(H)}|${a.workerType??"classic"}`,O=l(a.maxConcurrentWorkers);m=c(L,O,r=>{if(m=r,!f){E=Date.now();try{w=new Worker(H,"module"===a.workerType?{type:"module"}:void 0)}catch(r){return k(),void v(new e.HeicConverterError("worker_create_failed",(t=r instanceof Error?r.message:String(r),`Failed to create Web Worker: ${t}`),{cause:r}))}w.addEventListener("message",C),w.addEventListener("messageerror",W),w.addEventListener("error",M);try{w.postMessage({input:i,options:S})}catch(r){k(),v(new e.HeicConverterError("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(r instanceof Error?r.message:String(r)),{cause:r}))}}var t})})}function l(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):i()}exports.__semaphoreTestHooks=d,exports.convertHeicInWorker=v,exports.convertManyInWorker=async function(o,i){if(!Array.isArray(o))throw new e.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);if("undefined"==typeof Worker)throw new e.HeicConverterError("worker_unsupported",r);if(void 0!==i.decoder)throw new e.HeicConverterError("invalid_input",t);e.validateConvertOptions(i),e.validateContinueOnError(i?.continueOnError),n(i?.maxConcurrentWorkers),s(i?.timeoutMs);const{onProgress:a,continueOnError:c,...u}=i??{};return e.runBoundedBatch(o,l(i?.maxConcurrentWorkers),(e,r)=>v(e,{...u,...void 0!==a?{onProgress:e=>a(r,e)}:{}}),{continueOnError:!0===i?.continueOnError,signal:i?.signal})};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keeratita/heic-converter",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Convert HEIC images to standard web formats (JPEG, PNG, WebP, AVIF, SVG) without breaking CSP",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -30,25 +30,44 @@
30
30
  "build:wasm": "bash build-scripts/build-wasm.sh",
31
31
  "verify:wasm": "node build-scripts/verify-wasm-artifacts.mjs",
32
32
  "wasm:hashes": "node build-scripts/verify-wasm-artifacts.mjs --write",
33
+ "check:scripts": "node build-scripts/check-install-scripts.mjs",
34
+ "verify:provenance": "node build-scripts/verify-npm-provenance.mjs",
33
35
  "test": "vitest run",
34
36
  "test:watch": "vitest",
35
37
  "test:e2e": "node test/browser/test-playwright.mjs",
36
38
  "test:coverage": "vitest run --coverage",
37
39
  "sandbox": "node test/browser/server.mjs",
38
40
  "lint": "eslint .",
41
+ "typecheck": "tsc --noEmit -p tsconfig.test.json",
39
42
  "sonar": "sonar-scanner",
40
43
  "prepare": "husky",
41
44
  "release": "node build-scripts/release.mjs"
42
45
  },
43
46
  "keywords": [
44
47
  "heic",
45
- "convert",
48
+ "heif",
49
+ "heic-converter",
46
50
  "image",
51
+ "convert",
52
+ "jpeg",
53
+ "png",
54
+ "webp",
55
+ "avif",
56
+ "svg",
47
57
  "csp",
48
- "wasm"
58
+ "wasm",
59
+ "emscripten",
60
+ "exif",
61
+ "orientation"
49
62
  ],
50
63
  "author": "Keerati Tansawatcharoen <keerati.tansawatcharoen@gmail.com>",
51
64
  "license": "MIT",
65
+ "funding": "https://github.com/sponsors/keeratita",
66
+ "publishConfig": {
67
+ "access": "public",
68
+ "registry": "https://registry.npmjs.org/",
69
+ "provenance": true
70
+ },
52
71
  "repository": {
53
72
  "type": "git",
54
73
  "url": "git+https://github.com/keeratita/heic-converter.git"
@@ -59,12 +78,13 @@
59
78
  "homepage": "https://github.com/keeratita/heic-converter#readme",
60
79
  "devDependencies": {
61
80
  "@eslint/js": "^10.0.1",
62
- "@vitest/browser": "^5.0.3",
81
+ "@types/node": "^22.20.5",
63
82
  "@vitest/coverage-v8": "^5.0.3",
64
83
  "eslint": "^10.12.0",
65
84
  "globals": "^17.13.0",
66
85
  "husky": "^9.1.7",
67
86
  "playwright": "^1.63.0",
87
+ "terser": "^5.51.2",
68
88
  "tsup": "^8.0.0",
69
89
  "typescript": "^5.0.0",
70
90
  "typescript-eslint": "^8.71.0",