@keeratita/heic-converter 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -20
- package/dist/batch.d.ts +27 -0
- package/dist/chunk-AROQBV5T.mjs +1 -0
- package/dist/chunk-BTAX2PFV.mjs +1 -0
- package/dist/chunk-N2LCVW2Q.js +1 -0
- package/dist/chunk-TND3VERK.js +1 -0
- package/dist/errors.d.ts +28 -0
- package/dist/heic-decoder.wasm +0 -0
- package/dist/heic-decoder.wasm.br +0 -0
- package/dist/heic-decoder.wasm.gz +0 -0
- package/dist/index.d.ts +42 -423
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/messages/core.d.ts +60 -0
- package/dist/messages/worker.d.ts +33 -0
- package/dist/native-IGARV2W7.mjs +1 -0
- package/dist/native-JFFONPCS.js +1 -0
- package/dist/progress.d.ts +39 -0
- package/dist/render/canvas.d.ts +71 -0
- package/dist/render/exif.d.ts +37 -0
- package/dist/types.d.ts +257 -0
- package/dist/validate.d.ts +59 -0
- package/dist/wasm/fault.d.ts +3 -0
- package/dist/wasm/index.d.ts +1 -0
- package/dist/wasm/native.d.ts +46 -0
- package/dist/wasm/wrapper.d.ts +62 -0
- package/dist/worker-DISSAV3W.js +1 -0
- package/dist/worker-VA6WQF25.mjs +1 -0
- package/dist/worker.d.ts +128 -0
- package/package.json +7 -6
- package/dist/chunk-FKEXCXR4.js +0 -1
- package/dist/chunk-PTRQ7ZFB.mjs +0 -1
- package/dist/index.d.mts +0 -565
- package/dist/worker-FNMN2SJV.mjs +0 -1
- package/dist/worker-Z3UQ6WL7.js +0 -1
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { DecodedImage, IHeicDecoder } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Platform-native HEIC decoding — the Strategy behind `nativeDecode: true`.
|
|
4
|
+
* On HEIC-capable hosts (Safari/iOS, Edge, Windows) ImageIO decodes in
|
|
5
|
+
* hardware and the bundled libheif payload is never fetched. Dynamic-import
|
|
6
|
+
* only, so hosts that never opt in never download this chunk.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Decoded-dimension cap, a duplicate of `MAX_CANVAS_DIMENSION` in
|
|
10
|
+
* render/canvas.ts (pinned equal by native-decoder.test.ts) so this lazy
|
|
11
|
+
* chunk stays out of the render module graph.
|
|
12
|
+
*/
|
|
13
|
+
export declare const MAX_NATIVE_DECODE_DIMENSION = 16384;
|
|
14
|
+
/**
|
|
15
|
+
* Total-pixel cap, a duplicate of `kMaxDecodePixels` in
|
|
16
|
+
* build-wasm/wrapper/main.cpp (pinned equal by native-decoder.test.ts, same
|
|
17
|
+
* lazy-chunk-purity reason as the dimension cap). Without it, a
|
|
18
|
+
* container-declared 16384x16384 passes both side checks and the canvas +
|
|
19
|
+
* ImageData pair below allocates ~1 GB outside the WASM heap — the libheif
|
|
20
|
+
* path rejects that size, so native must not accept it.
|
|
21
|
+
*/
|
|
22
|
+
export declare const MAX_NATIVE_DECODE_PIXELS: number;
|
|
23
|
+
/** @internal Whether this realm has refused native decoding (decoder selection). */
|
|
24
|
+
export declare function isNativeHeicRefused(): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* @internal Record an environment-class native failure so later calls skip
|
|
27
|
+
* the attempt. The once-only warn is the breadcrumb: without it the page
|
|
28
|
+
* silently loses the opt-in with nothing naming the cause.
|
|
29
|
+
*/
|
|
30
|
+
export declare function markNativeHeicRefused(): void;
|
|
31
|
+
/** @internal Clear the refusal verdict and its breadcrumb (tests only). */
|
|
32
|
+
export declare function __resetNativeHeicProbe(): void;
|
|
33
|
+
/**
|
|
34
|
+
* createImageBitmap + OffscreenCanvas readback behind the same
|
|
35
|
+
* `DecodedImage` contract as LibheifDecoder, so the render stage is shared.
|
|
36
|
+
* `imageOrientation: 'from-image'` applies the display transform (EXIF and
|
|
37
|
+
* irot/imir), so results are upright with no pending orientation — the
|
|
38
|
+
* selection policy only picks this Strategy when `applyOrientation` is not
|
|
39
|
+
* false. Errors never reach a consumer: convertHeic retries with libheif,
|
|
40
|
+
* which produces the typed error of record, so these strings stay chunk-local.
|
|
41
|
+
*/
|
|
42
|
+
export declare class NativeHeicDecoder implements IHeicDecoder {
|
|
43
|
+
initialize(): Promise<void>;
|
|
44
|
+
decode(data: Uint8Array): Promise<DecodedImage>;
|
|
45
|
+
free(): void;
|
|
46
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { IHeicDecoder, DecodedImage } from '../types';
|
|
2
|
+
export interface LibheifDecoderOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Custom function to locate the WASM file.
|
|
5
|
+
* Useful when serving the WASM file from a custom route or CDN.
|
|
6
|
+
*/
|
|
7
|
+
locateFile?: (path: string, prefix: string) => string;
|
|
8
|
+
/**
|
|
9
|
+
* Raw WASM binary buffer. If provided, the library will use this buffer
|
|
10
|
+
* directly instead of attempting to fetch the WASM file. Accepts an
|
|
11
|
+
* `ArrayBuffer` or any `ArrayBufferView` (e.g. a Node.js `Buffer` from
|
|
12
|
+
* `fs.readFileSync`).
|
|
13
|
+
*/
|
|
14
|
+
wasmBinary?: ArrayBuffer | ArrayBufferView;
|
|
15
|
+
/**
|
|
16
|
+
* Advanced: extra properties merged into the Emscripten module argument
|
|
17
|
+
* object (e.g. `instantiateWasm` for streaming compilation). Prefer
|
|
18
|
+
* `locateFile`/`wasmBinary` for the common cases; keys provided here must
|
|
19
|
+
* not collide with them.
|
|
20
|
+
*/
|
|
21
|
+
moduleOverrides?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
export declare class LibheifDecoder implements IHeicDecoder {
|
|
24
|
+
private options?;
|
|
25
|
+
private module;
|
|
26
|
+
private decoderInstance;
|
|
27
|
+
/**
|
|
28
|
+
* Memoized module-loading promise so concurrent initialize()/decode() calls
|
|
29
|
+
* on the same instance never instantiate (or mutate) the module twice.
|
|
30
|
+
* Resolves null when a concurrent free() discarded the freshly created
|
|
31
|
+
* instance (see initGeneration).
|
|
32
|
+
*/
|
|
33
|
+
private initPromise;
|
|
34
|
+
/**
|
|
35
|
+
* Generation counter for init/free races: a load that finishes after a
|
|
36
|
+
* concurrent free() must not resurrect module/decoderInstance.
|
|
37
|
+
*/
|
|
38
|
+
private initGeneration;
|
|
39
|
+
constructor(options?: LibheifDecoderOptions);
|
|
40
|
+
/**
|
|
41
|
+
* Initializes the WebAssembly module and instantiates the HEIC decoder.
|
|
42
|
+
* Safe to call concurrently: the module is loaded at most once per instance.
|
|
43
|
+
*/
|
|
44
|
+
initialize(): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Decodes HEIC binary data into raw RGBA pixel data.
|
|
47
|
+
* @param data The HEIC file contents as a Uint8Array.
|
|
48
|
+
* @param onProgress Optional progress callback (receives a normalized
|
|
49
|
+
* percentage clamped to 0-100).
|
|
50
|
+
*/
|
|
51
|
+
decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
|
|
52
|
+
/**
|
|
53
|
+
* Cleans up the WebAssembly decoder instance and resources.
|
|
54
|
+
* Idempotent: safe to call multiple times. After free(), the next
|
|
55
|
+
* initialize() — or decode() directly, which re-initializes transparently
|
|
56
|
+
* — loads a fresh module.
|
|
57
|
+
*
|
|
58
|
+
* free() is also safe to call while initialize() is in flight: a load that
|
|
59
|
+
* completes after free() discards its fresh instance instead of leaking it.
|
|
60
|
+
*/
|
|
61
|
+
free(): void;
|
|
62
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=require("./chunk-TND3VERK.js"),r=require("./chunk-N2LCVW2Q.js"),t="Web Worker is not supported in the current environment",o="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.",s=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(t){if(void 0!==t&&(!Number.isInteger(t)||t<1||t>e.MAX_BATCH_CONCURRENCY))throw new r.HeicConverterError("invalid_concurrency",(o=t,`maxConcurrentWorkers must be an integer between 1 and ${e.MAX_BATCH_CONCURRENCY}, got: ${o}`));var o}function i(e){if(void 0!==e&&("number"!=typeof e||!Number.isFinite(e)||e<0))throw new r.HeicConverterError("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${e}`)}function a(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var d=new Map,c=1;function u(e,r,t){let o=d.get(e);o||(o={active:0,waiters:[],parked:[]},d.set(e,o));const s={granted:!1,released:!1},n=()=>{0===o.active&&0===o.waiters.length&&(0!==o.parked.length?o.idleTimer=setTimeout(()=>{o.idleTimer=void 0;for(const e of o.parked.splice(0))e.terminate();d.delete(e)},5e3):d.delete(e))},i=e=>{if(!s.released)if(s.released=!0,e&&(o.parked.length>=2&&o.parked.shift().terminate(),o.parked.push(e)),s.granted){s.granted=!1,o.active-=1;const e=o.waiters.shift();e?e():n()}else{const e=o.waiters.indexOf(a);-1!==e&&o.waiters.splice(e,1),n()}},a=()=>{s.released||(void 0!==o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=void 0),s.granted=!0,o.active+=1,t(i,o.parked.pop()))};return o.active<r?a():o.waiters.push(a),i}var l={reserveWorkerSlot:u,workerSlots:d,defaultMaxWorkers:a,WORKER_POOL_IDLE_MS:5e3,MAX_PARKED_WORKERS:2};function p(a,d){return new Promise((l,p)=>{if("undefined"==typeof Worker)return void p(new r.HeicConverterError("worker_unsupported",t));if(void 0!==d.decoder)return void p(new r.HeicConverterError("invalid_input",o));try{e.validateConvertOptions(d),n(d?.maxConcurrentWorkers),i(d?.timeoutMs)}catch(e){return void p(e)}if(d.signal?.aborted)return void p(new r.HeicConverterError("aborted",e.Messages.Aborted));const m={progressMessages:0},g=c++,f=e.progressGateFor(d.onProgress);let w,k,h,y=!1,C=!1;const E=(e=!1)=>{y||(y=!0,void 0!==k&&clearTimeout(k),d.signal?.removeEventListener("abort",b),w&&(w.removeEventListener("message",T),w.removeEventListener("messageerror",H),w.removeEventListener("error",$)),e&&w?h?.(w):(w?.terminate(),h?.()))},b=()=>{E(),p(new r.HeicConverterError("aborted",e.Messages.Aborted))};d.signal?.addEventListener("abort",b,{once:!0});const W=d.timeoutMs??6e4,M=Date.now();let _;W>0&&(k=setTimeout(()=>{E(),p(new r.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.staleResults&&t.push(`${r.staleResults} result(s) ignored for not echoing the request id (duplicate or stale replies must not be posted)`),void 0!==r.staleProgress&&t.push(`${r.staleProgress} progress message(s) ignored for not echoing the request id`),r.adopted&&t.push("lease adopted from the pool — a script that calls self.close() after replying stalls adopted leases"),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 { id, type: "progress" | "result" } protocol.`})(W,{progressMessages:m.progressMessages,lastPercent:m.lastPercent,unknownType:m.unknownType,staleResults:m.staleResults,staleProgress:m.staleProgress,adopted:C,workerUrl:d.workerUrl,startedAt:_,queueWaitMs:void 0===_?void 0:_-M})))},W));const T=t=>{const o=t.data;if("progress"===o?.type){if(o.id!==g)return void(m.staleProgress=(m.staleProgress??0)+1);m.progressMessages+=1;const r=e.clampPercent(o.percent);if(m.lastPercent=r,r>=100)return;f?.report(r);const t=f?.pendingError();return void(t&&(E(),p(t)))}if("result"!==o?.type)return void("string"==typeof o?.type&&(m.unknownType=o.type));if(o.id!==g)return void(m.staleResults=(m.staleResults??0)+1);const s=!0===o.ok&&void 0!==o.blob;if(E(s),s){try{f?.complete()}catch(e){return void p(e)}l(o.blob)}else p(new r.HeicConverterError("worker_failed",o.error??"Worker conversion failed"))},$=e=>{E();const t=e.filename?` (${e.filename}:${e.lineno})`:"";p(new r.HeicConverterError("worker_failed",`${e.message||s(d.workerUrl)}${t}`))},H=e=>{E();const t=e.data;p(new r.HeicConverterError("worker_failed",t instanceof Error?t.message:void 0!==t?String(t):s(d.workerUrl),{cause:t}))},{workerUrl:P,onProgress:R,timeoutMs:x,workerType:A,maxConcurrentWorkers:O,signal:L,...S}=d,q=`${String(P)}|${d.workerType??"classic"}`,U=v(d.maxConcurrentWorkers);h=u(q,U,(e,t)=>{if(h=e,y)t?.terminate();else{_=Date.now(),C=void 0!==t;try{w=t??new Worker(P,"module"===d.workerType?{type:"module"}:void 0)}catch(e){return E(),void p(new r.HeicConverterError("worker_create_failed",(o=e instanceof Error?e.message:String(e),`Failed to create Web Worker: ${o}`),{cause:e}))}w.addEventListener("message",T),w.addEventListener("messageerror",H),w.addEventListener("error",$);try{w.postMessage({id:g,input:a,options:S})}catch(e){E(),p(new r.HeicConverterError("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(e instanceof Error?e.message:String(e)),{cause:e}))}}var o})})}function v(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):a()}exports.__resetWorkerPool=function(){for(const e of d.values()){void 0!==e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0);for(const r of e.parked.splice(0))r.terminate()}d.clear()},exports.__semaphoreTestHooks=l,exports.convertHeicInWorker=p,exports.convertManyInWorker=async function(s,a){if(!Array.isArray(s))throw new r.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);if("undefined"==typeof Worker)throw new r.HeicConverterError("worker_unsupported",t);if(void 0!==a.decoder)throw new r.HeicConverterError("invalid_input",o);e.validateConvertOptions(a),e.validateBatchOptions(a),n(a.maxConcurrentWorkers),i(a.timeoutMs);const{onProgress:d,continueOnError:c,...u}=a,l=e.progressCallbackFor(d);return e.runBoundedBatch(s,v(a.maxConcurrentWorkers),(e,r)=>p(e,{...u,...l?{onProgress:e=>l(r,e)}:{}}),{continueOnError:!0===a.continueOnError,signal:a.signal})};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{validateConvertOptions as e,Messages as r,progressGateFor as t,validateBatchOptions as o,progressCallbackFor as s,runBoundedBatch as n,MAX_BATCH_CONCURRENCY as i,clampPercent as a}from"./chunk-BTAX2PFV.mjs";import{HeicConverterError as d}from"./chunk-AROQBV5T.mjs";var u="Web Worker is not supported in the current environment",l="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.",c=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 p(e){if(void 0!==e&&(!Number.isInteger(e)||e<1||e>i))throw new d("invalid_concurrency",`maxConcurrentWorkers must be an integer between 1 and ${i}, got: ${e}`)}function m(e){if(void 0!==e&&("number"!=typeof e||!Number.isFinite(e)||e<0))throw new d("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${e}`)}function g(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var v=new Map,f=1;function w(e,r,t){let o=v.get(e);o||(o={active:0,waiters:[],parked:[]},v.set(e,o));const s={granted:!1,released:!1},n=()=>{0===o.active&&0===o.waiters.length&&(0!==o.parked.length?o.idleTimer=setTimeout(()=>{o.idleTimer=void 0;for(const e of o.parked.splice(0))e.terminate();v.delete(e)},5e3):v.delete(e))},i=e=>{if(!s.released)if(s.released=!0,e&&(o.parked.length>=2&&o.parked.shift().terminate(),o.parked.push(e)),s.granted){s.granted=!1,o.active-=1;const e=o.waiters.shift();e?e():n()}else{const e=o.waiters.indexOf(a);-1!==e&&o.waiters.splice(e,1),n()}},a=()=>{s.released||(void 0!==o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=void 0),s.granted=!0,o.active+=1,t(i,o.parked.pop()))};return o.active<r?a():o.waiters.push(a),i}var k={reserveWorkerSlot:w,workerSlots:v,defaultMaxWorkers:g,WORKER_POOL_IDLE_MS:5e3,MAX_PARKED_WORKERS:2};function h(){for(const e of v.values()){void 0!==e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0);for(const r of e.parked.splice(0))r.terminate()}v.clear()}function y(o,s){return new Promise((n,i)=>{if("undefined"==typeof Worker)return void i(new d("worker_unsupported",u));if(void 0!==s.decoder)return void i(new d("invalid_input",l));try{e(s),p(s?.maxConcurrentWorkers),m(s?.timeoutMs)}catch(e){return void i(e)}if(s.signal?.aborted)return void i(new d("aborted",r.Aborted));const g={progressMessages:0},v=f++,k=t(s.onProgress);let h,y,W,M=!1,T=!1;const $=(e=!1)=>{M||(M=!0,void 0!==y&&clearTimeout(y),s.signal?.removeEventListener("abort",_),h&&(h.removeEventListener("message",R),h.removeEventListener("messageerror",S),h.removeEventListener("error",A)),e&&h?W?.(h):(h?.terminate(),W?.()))},_=()=>{$(),i(new d("aborted",r.Aborted))};s.signal?.addEventListener("abort",_,{once:!0});const E=s.timeoutMs??6e4,P=Date.now();let x;E>0&&(y=setTimeout(()=>{$(),i(new d("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.staleResults&&t.push(`${r.staleResults} result(s) ignored for not echoing the request id (duplicate or stale replies must not be posted)`),void 0!==r.staleProgress&&t.push(`${r.staleProgress} progress message(s) ignored for not echoing the request id`),r.adopted&&t.push("lease adopted from the pool — a script that calls self.close() after replying stalls adopted leases"),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 { id, type: "progress" | "result" } protocol.`})(E,{progressMessages:g.progressMessages,lastPercent:g.lastPercent,unknownType:g.unknownType,staleResults:g.staleResults,staleProgress:g.staleProgress,adopted:T,workerUrl:s.workerUrl,startedAt:x,queueWaitMs:void 0===x?void 0:x-P})))},E));const R=e=>{const r=e.data;if("progress"===r?.type){if(r.id!==v)return void(g.staleProgress=(g.staleProgress??0)+1);g.progressMessages+=1;const e=a(r.percent);if(g.lastPercent=e,e>=100)return;k?.report(e);const t=k?.pendingError();return void(t&&($(),i(t)))}if("result"!==r?.type)return void("string"==typeof r?.type&&(g.unknownType=r.type));if(r.id!==v)return void(g.staleResults=(g.staleResults??0)+1);const t=!0===r.ok&&void 0!==r.blob;if($(t),t){try{k?.complete()}catch(e){return void i(e)}n(r.blob)}else i(new d("worker_failed",r.error??"Worker conversion failed"))},A=e=>{$();const r=e.filename?` (${e.filename}:${e.lineno})`:"";i(new d("worker_failed",`${e.message||c(s.workerUrl)}${r}`))},S=e=>{$();const r=e.data;i(new d("worker_failed",r instanceof Error?r.message:void 0!==r?String(r):c(s.workerUrl),{cause:r}))},{workerUrl:C,onProgress:L,timeoutMs:O,workerType:q,maxConcurrentWorkers:U,signal:I,...j}=s,D=`${String(C)}|${s.workerType??"classic"}`,F=b(s.maxConcurrentWorkers);W=w(D,F,(e,r)=>{if(W=e,M)r?.terminate();else{x=Date.now(),T=void 0!==r;try{h=r??new Worker(C,"module"===s.workerType?{type:"module"}:void 0)}catch(e){return $(),void i(new d("worker_create_failed",(t=e instanceof Error?e.message:String(e),`Failed to create Web Worker: ${t}`),{cause:e}))}h.addEventListener("message",R),h.addEventListener("messageerror",S),h.addEventListener("error",A);try{h.postMessage({id:v,input:o,options:j})}catch(e){$(),i(new d("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(e instanceof Error?e.message:String(e)),{cause:e}))}}var t})})}function b(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):g()}async function W(t,i){if(!Array.isArray(t))throw new d("invalid_input",r.InputsMustBeArray);if("undefined"==typeof Worker)throw new d("worker_unsupported",u);if(void 0!==i.decoder)throw new d("invalid_input",l);e(i),o(i),p(i.maxConcurrentWorkers),m(i.timeoutMs);const{onProgress:a,continueOnError:c,...g}=i,v=s(a);return n(t,b(i.maxConcurrentWorkers),(e,r)=>y(e,{...g,...v?{onProgress:e=>v(r,e)}:{}}),{continueOnError:!0===i.continueOnError,signal:i.signal})}export{h as __resetWorkerPool,k as __semaphoreTestHooks,y as convertHeicInWorker,W as convertManyInWorker};
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { ConvertItemResult, ConvertOptions, ConvertResult, HeicInput, OutputShape } from './types';
|
|
2
|
+
export interface WorkerConvertOptions extends Omit<ConvertOptions, 'decoder'> {
|
|
3
|
+
/**
|
|
4
|
+
* URL of the worker script that performs the conversion. Should be a
|
|
5
|
+
* compile-time constant (e.g. `new URL('./worker.js', import.meta.url)`
|
|
6
|
+
* under a bundler); the script runs with the page's privileges.
|
|
7
|
+
*/
|
|
8
|
+
workerUrl: string | URL;
|
|
9
|
+
/**
|
|
10
|
+
* Maximum time in milliseconds to wait for the worker result before
|
|
11
|
+
* rejecting with a timeout (queueing for a free worker slot counts toward
|
|
12
|
+
* this). Defaults to 60000 (60s). Set to 0 to disable the timeout.
|
|
13
|
+
*/
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Worker script type. Use `'module'` when the script uses ES module
|
|
17
|
+
* imports (e.g. `import { convertHeic } from ...`); `'classic'`
|
|
18
|
+
* scripts must be pre-bundled.
|
|
19
|
+
* @default 'classic'
|
|
20
|
+
*/
|
|
21
|
+
workerType?: 'classic' | 'module';
|
|
22
|
+
/**
|
|
23
|
+
* Upper bound on simultaneously live workers for this worker script.
|
|
24
|
+
* Calls beyond the bound queue until a slot frees, which keeps bulk
|
|
25
|
+
* conversions (`inputs.map(i => convertHeicInWorker(i, …))`) from
|
|
26
|
+
* exhausting memory or the browser's worker limit. Must be an integer
|
|
27
|
+
* from 1 to `64` (each worker is a full WASM boot with its own heap, so
|
|
28
|
+
* an unbounded value is a page-taking-down footgun, not capacity).
|
|
29
|
+
* Defaults to `navigator.hardwareConcurrency` clamped to 1–8.
|
|
30
|
+
*/
|
|
31
|
+
maxConcurrentWorkers?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Correlation token: every reply must echo the `id` of the request it answers.
|
|
35
|
+
* Workers are pooled, so a duplicate or late reply would otherwise settle the
|
|
36
|
+
* *next* lease with the previous item's result.
|
|
37
|
+
*/
|
|
38
|
+
interface CorrelatedMessage {
|
|
39
|
+
id: number;
|
|
40
|
+
}
|
|
41
|
+
/** Progress message a worker script posts to report decode progress. */
|
|
42
|
+
export interface WorkerProgressMessage extends CorrelatedMessage {
|
|
43
|
+
type: 'progress';
|
|
44
|
+
percent: number;
|
|
45
|
+
}
|
|
46
|
+
/** Result message a worker script posts to settle a conversion. */
|
|
47
|
+
export interface WorkerResultMessage extends CorrelatedMessage {
|
|
48
|
+
type: 'result';
|
|
49
|
+
ok: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* The converted image as `convertHeic` returned it inside the worker: Blob,
|
|
52
|
+
* data-URL string, or ArrayBuffer. The field name `blob` is kept for
|
|
53
|
+
* protocol compatibility.
|
|
54
|
+
*/
|
|
55
|
+
blob?: Blob | string | ArrayBuffer;
|
|
56
|
+
error?: string;
|
|
57
|
+
}
|
|
58
|
+
export type WorkerMessage = WorkerProgressMessage | WorkerResultMessage;
|
|
59
|
+
declare function defaultMaxWorkers(): number;
|
|
60
|
+
/** Hands the lease back; a `recycle` worker is parked for the next grant. */
|
|
61
|
+
type WorkerReleaser = (recycle?: Worker) => void;
|
|
62
|
+
declare function reserveWorkerSlot(key: string, max: number, start: (release: WorkerReleaser, recycled: Worker | undefined) => void): WorkerReleaser;
|
|
63
|
+
/** @internal Semaphore unit-test hooks; not part of the public API. */
|
|
64
|
+
export declare const __semaphoreTestHooks: {
|
|
65
|
+
reserveWorkerSlot: typeof reserveWorkerSlot;
|
|
66
|
+
workerSlots: Map<string, {
|
|
67
|
+
active: number;
|
|
68
|
+
waiters: Array<() => void>;
|
|
69
|
+
parked: Worker[];
|
|
70
|
+
idleTimer?: ReturnType<typeof setTimeout>;
|
|
71
|
+
}>;
|
|
72
|
+
defaultMaxWorkers: typeof defaultMaxWorkers;
|
|
73
|
+
WORKER_POOL_IDLE_MS: number;
|
|
74
|
+
MAX_PARKED_WORKERS: number;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* @internal Terminate parked workers, cancel idle prunes and drop slot entries,
|
|
78
|
+
* so tests never adopt a worker parked by an earlier case. Like the other hooks
|
|
79
|
+
* this ships inside the lazy worker chunk — dead but inert bytes outside tests.
|
|
80
|
+
*/
|
|
81
|
+
export declare function __resetWorkerPool(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Implementation behind the public `convertHeicInWorker` wrapper in
|
|
84
|
+
* `src/index.ts`, which carries the published JSDoc (worker-script protocol,
|
|
85
|
+
* `workerType`/`decoder` rules, `timeoutMs` caveats) — that is what
|
|
86
|
+
* `dist/index.d.ts` ships, so keep behaviour in sync with that doc.
|
|
87
|
+
*/
|
|
88
|
+
export declare function convertHeicInWorker<S extends OutputShape = 'blob'>(input: HeicInput, options: WorkerConvertOptions & {
|
|
89
|
+
output?: S;
|
|
90
|
+
}): Promise<ConvertResult<S>>;
|
|
91
|
+
/**
|
|
92
|
+
* Options for {@link convertManyInWorker}: the {@link convertHeicInWorker}
|
|
93
|
+
* worker options plus the batch semantics of `convertMany`.
|
|
94
|
+
*/
|
|
95
|
+
export interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
|
|
96
|
+
/**
|
|
97
|
+
* Per-item progress callback: receives the 0-based item index and its
|
|
98
|
+
* progress percentage (normalized 0–100). Values below 100 may also be
|
|
99
|
+
* reported for items that ultimately fail; the 100% event fires only for
|
|
100
|
+
* items that succeed.
|
|
101
|
+
*/
|
|
102
|
+
onProgress?: (index: number, percent: number) => void;
|
|
103
|
+
/**
|
|
104
|
+
* Resolve with per-item results instead of rejecting the batch on the
|
|
105
|
+
* first failure; all items run to completion (see
|
|
106
|
+
* `ConvertManyOptions.continueOnError`).
|
|
107
|
+
* @default false
|
|
108
|
+
*/
|
|
109
|
+
continueOnError?: boolean;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Implementation behind the public `convertManyInWorker` wrapper in
|
|
113
|
+
* `src/index.ts`, which carries the published JSDoc — keep behaviour in sync
|
|
114
|
+
* with that doc; the entry point just resolves the lazy chunk and forwards.
|
|
115
|
+
*/
|
|
116
|
+
export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
|
|
117
|
+
output?: S;
|
|
118
|
+
continueOnError: true;
|
|
119
|
+
}): Promise<ConvertItemResult<ConvertResult<S>>[]>;
|
|
120
|
+
export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
|
|
121
|
+
output?: S;
|
|
122
|
+
continueOnError?: false;
|
|
123
|
+
}): Promise<ConvertResult<S>[]>;
|
|
124
|
+
export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
|
|
125
|
+
output?: S;
|
|
126
|
+
continueOnError: boolean;
|
|
127
|
+
}): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
|
|
128
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@keeratita/heic-converter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
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",
|
|
@@ -26,10 +26,11 @@
|
|
|
26
26
|
"node": ">=20.0.0"
|
|
27
27
|
},
|
|
28
28
|
"scripts": {
|
|
29
|
-
"build": "tsup && node build-scripts/compress-wasm.mjs",
|
|
29
|
+
"build": "tsup && tsc -p tsconfig.json --emitDeclarationOnly && node build-scripts/compress-wasm.mjs",
|
|
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
|
+
"wasm:goldens": "node build-scripts/wasm-golden-table.mjs",
|
|
33
34
|
"check:scripts": "node build-scripts/check-install-scripts.mjs",
|
|
34
35
|
"verify:provenance": "node build-scripts/verify-npm-provenance.mjs",
|
|
35
36
|
"test": "vitest run",
|
|
@@ -78,16 +79,16 @@
|
|
|
78
79
|
"homepage": "https://github.com/keeratita/heic-converter#readme",
|
|
79
80
|
"devDependencies": {
|
|
80
81
|
"@eslint/js": "^10.0.1",
|
|
81
|
-
"@types/node": "^
|
|
82
|
+
"@types/node": "^26.6.5",
|
|
82
83
|
"@vitest/coverage-v8": "^5.0.3",
|
|
83
84
|
"eslint": "^10.12.0",
|
|
84
85
|
"globals": "^17.13.0",
|
|
85
86
|
"husky": "^9.1.7",
|
|
86
|
-
"playwright": "^1.
|
|
87
|
+
"playwright": "^1.64.0",
|
|
87
88
|
"terser": "^5.51.2",
|
|
88
89
|
"tsup": "^8.0.0",
|
|
89
|
-
"typescript": "^
|
|
90
|
-
"typescript-eslint": "^8.71.
|
|
90
|
+
"typescript": "^6.0.3",
|
|
91
|
+
"typescript-eslint": "^8.71.1",
|
|
91
92
|
"vitest": "^5.0.3"
|
|
92
93
|
}
|
|
93
94
|
}
|
package/dist/chunk-FKEXCXR4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e={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} — 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'`,WorkerChunkLoadFailed:e=>`Failed to load the Web Worker implementation chunk (dist/worker-*.mjs): ${e} — deploy every file in dist/ together, or use convertHeic to convert in the current thread`,RenderEncodeFailed:(e,t)=>`Failed to render and encode image as ${e}: ${t}`,ConcurrencyInvalid:e=>`Concurrency must be a positive integer, 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,t,n)=>`Conversion of item ${e} of ${t} failed: ${n}`,ConvertManyExtraFailures:(e,t)=>` (${e} of ${t} 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,t,n)=>`Target image size ${e}x${t} exceeds the maximum supported dimension of ${n}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,t)=>`Invalid image dimensions: ${e}x${t}. Width and height must be positive integers.`,DataLengthMismatch:(e,t,n,i)=>`Image data length mismatch. Expected ${e} bytes for ${t}x${n}, got ${i}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' — canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,t)=>`crop.${e} must be ${"width"===e||"height"===e?"a positive integer":"a non-negative integer"}, got: ${t}`,CropOutOfBounds:(e,t,n,i,o,r)=>`crop ${n}x${i} at (${e}, ${t}) exceeds the ${o}x${r} 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 — is the file truncated or empty?)`,DecodeFailedWithDetail:(e,t)=>`HEIC decoding failed: ${e} (input: ${t} bytes)`,DecodeFaulted:e=>`Decoder faulted on a ${e}-byte image (out of memory, or a corrupted WebAssembly instance); retry — a faulted pooled decoder is discarded, not reused`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`},t=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(e,t,n){super(t,{cause:n?.cause}),this.name="HeicConverterError",this.code=e,void 0!==n?.itemIndex&&(this.itemIndex=n.itemIndex),void 0!==n?.itemTotal&&(this.itemTotal=n.itemTotal),void 0!==n?.failedCount&&(this.failedCount=n.failedCount)}},n=["jpeg","jpg","png","svg","webp","avif"];function i(n){if(void 0!==n&&"boolean"!=typeof n)throw new t("invalid_input",e.ContinueOnErrorInvalid(n))}function o(i){const o=String(i).toLowerCase();if(!n.includes(o))throw new t("invalid_format",e.UnsupportedFormat(String(i)))}function r(n){if(!n)return;const{maxWidth:i,maxHeight:o,scale:r}=n;if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<=0))throw new t("invalid_resize",e.ScaleInvalid(r));if(void 0!==i&&("number"!=typeof i||!Number.isFinite(i)||i<=0))throw new t("invalid_resize",e.MaxWidthInvalid(i));if(void 0!==o&&("number"!=typeof o||!Number.isFinite(o)||o<=0))throw new t("invalid_resize",e.MaxHeightInvalid(o))}function a(n){if(!n)return;const{x:i=0,y:o=0,width:r,height:a}=n;if(!Number.isInteger(r)||r<=0)throw new t("invalid_crop",e.CropInvalid("width",r));if(!Number.isInteger(a)||a<=0)throw new t("invalid_crop",e.CropInvalid("height",a));if(!Number.isInteger(i)||i<0)throw new t("invalid_crop",e.CropInvalid("x",i));if(!Number.isInteger(o)||o<0)throw new t("invalid_crop",e.CropInvalid("y",o))}function d(e,t){return Math.min(e,t)}exports.DEFAULT_QUALITY=.92,exports.HeicConverterError=t,exports.Messages=e,exports.SUPPORTED_FORMATS=n,exports.clampPercent=function(e){const t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0},exports.runBoundedBatch=async function(n,i,o,r){const a=!0===r?.continueOnError,s=r?.signal,l=new Array(n.length);let u=0,c=!1,p=0,v=null,h=-1,f=0;const m=[];let g;const b=new Promise(e=>{g=e}),w=()=>g?.();s&&!a&&s.addEventListener("abort",w,{once:!0});const y=d(i,n.length),x=Array.from({length:y},()=>(async()=>{for(;!c&&!s?.aborted||a;){const i=u;if(u+=1,i>=n.length)return;if(a&&s?.aborted){const o=new t("aborted",e.Aborted);for(let e=i;e<n.length;e++)l[e]={index:e,ok:!1,error:o};return void(u=n.length)}try{const e=await o(n[i],i);l[i]={index:i,ok:!0,result:e},p+=1}catch(e){if(f+=1,a){l[i]={index:i,ok:!1,error:e instanceof Error?e:new Error(String(e))};continue}c?m.length<2&&m.push(e instanceof Error?e.message:String(e)):(c=!0,v=e,h=i,g?.())}}})());try{if(a)return await Promise.all(x),l;if(await Promise.race([Promise.all(x),b]),p===n.length)return l.map(n=>{if(!n||!n.ok)throw new t("batch_item_failed",e.BatchItemProducedNoResult(n?.index));return n.result});if(s?.aborted)throw new t("aborted",e.Aborted);if(c){const i=v instanceof Error?v.message:String(v);let o=e.ConvertManyItemFailed(h+1,n.length,i);throw f>1&&(o+=e.ConvertManyExtraFailures(f,n.length),m.length>0&&(o+=e.ConvertManyOtherErrors(m))),new t("batch_item_failed",o,{cause:v,itemIndex:h,itemTotal:n.length,failedCount:f})}throw new t("batch_item_failed",e.BatchEndedWithoutResult)}finally{s?.removeEventListener("abort",w)}},exports.runnerCountFor=d,exports.throwIfAborted=function(n){if(n?.aborted)throw new t("aborted",e.Aborted)},exports.validateBatchOptions=function(n){i(n?.continueOnError),function(n){if(void 0!==n&&"boolean"!=typeof n)throw new t("invalid_input",e.ReuseDecodersInvalid(n))}(n?.reuseDecoders)},exports.validateConcurrency=function(n){if(!Number.isInteger(n)||n<1)throw new t("invalid_concurrency",e.ConcurrencyInvalid(n))},exports.validateContinueOnError=i,exports.validateConvertOptions=function(n){o(n?.to??"jpeg"),void 0!==n?.quality&&function(n){if("number"!=typeof n||!Number.isFinite(n)||n<0||n>1)throw new t("invalid_quality",e.QualityInvalid(n))}(n.quality),function(n){if(void 0!==n&&"boolean"!=typeof n)throw new t("invalid_input",e.ApplyOrientationInvalid(n))}(n?.applyOrientation),function(n){if(void 0!==n&&"blob"!==n&&"dataUrl"!==n&&"arrayBuffer"!==n)throw new t("invalid_input",e.OutputShapeInvalid(n))}(n?.output),function(n){if(void 0!==n&&("object"!=typeof n||null===n||"function"!=typeof n.addEventListener))throw new t("invalid_input",e.SignalInvalid(n))}(n?.signal),a(n?.crop),function(n){if(void 0!==n&&"boolean"!=typeof n)throw new t("invalid_input",e.PreserveExifInvalid(n))}(n?.preserveExif),r(void 0!==n?.maxWidth||void 0!==n?.maxHeight||void 0!==n?.scale?n:void 0)},exports.validateCrop=a,exports.validateFormat=o,exports.validateResize=r;
|
package/dist/chunk-PTRQ7ZFB.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e={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} — 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'`,WorkerChunkLoadFailed:e=>`Failed to load the Web Worker implementation chunk (dist/worker-*.mjs): ${e} — deploy every file in dist/ together, or use convertHeic to convert in the current thread`,RenderEncodeFailed:(e,t)=>`Failed to render and encode image as ${e}: ${t}`,ConcurrencyInvalid:e=>`Concurrency must be a positive integer, 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,t,n)=>`Conversion of item ${e} of ${t} failed: ${n}`,ConvertManyExtraFailures:(e,t)=>` (${e} of ${t} 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,t,n)=>`Target image size ${e}x${t} exceeds the maximum supported dimension of ${n}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,t)=>`Invalid image dimensions: ${e}x${t}. Width and height must be positive integers.`,DataLengthMismatch:(e,t,n,i)=>`Image data length mismatch. Expected ${e} bytes for ${t}x${n}, got ${i}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' — canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,t)=>`crop.${e} must be ${"width"===e||"height"===e?"a positive integer":"a non-negative integer"}, got: ${t}`,CropOutOfBounds:(e,t,n,i,o,r)=>`crop ${n}x${i} at (${e}, ${t}) exceeds the ${o}x${r} 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 — is the file truncated or empty?)`,DecodeFailedWithDetail:(e,t)=>`HEIC decoding failed: ${e} (input: ${t} bytes)`,DecodeFaulted:e=>`Decoder faulted on a ${e}-byte image (out of memory, or a corrupted WebAssembly instance); retry — a faulted pooled decoder is discarded, not reused`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`};function t(e){const t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}var n=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(e,t,n){super(t,{cause:n?.cause}),this.name="HeicConverterError",this.code=e,void 0!==n?.itemIndex&&(this.itemIndex=n.itemIndex),void 0!==n?.itemTotal&&(this.itemTotal=n.itemTotal),void 0!==n?.failedCount&&(this.failedCount=n.failedCount)}},i=["jpeg","jpg","png","svg","webp","avif"],o=.92;function r(t){u(t?.to??"jpeg"),void 0!==t?.quality&&function(t){if("number"!=typeof t||!Number.isFinite(t)||t<0||t>1)throw new n("invalid_quality",e.QualityInvalid(t))}(t.quality),function(t){if(void 0!==t&&"boolean"!=typeof t)throw new n("invalid_input",e.ApplyOrientationInvalid(t))}(t?.applyOrientation),function(t){if(void 0!==t&&"blob"!==t&&"dataUrl"!==t&&"arrayBuffer"!==t)throw new n("invalid_input",e.OutputShapeInvalid(t))}(t?.output),function(t){if(void 0!==t&&("object"!=typeof t||null===t||"function"!=typeof t.addEventListener))throw new n("invalid_input",e.SignalInvalid(t))}(t?.signal),f(t?.crop),function(t){if(void 0!==t&&"boolean"!=typeof t)throw new n("invalid_input",e.PreserveExifInvalid(t))}(t?.preserveExif),c(void 0!==t?.maxWidth||void 0!==t?.maxHeight||void 0!==t?.scale?t:void 0)}function a(t){s(t?.continueOnError),function(t){if(void 0!==t&&"boolean"!=typeof t)throw new n("invalid_input",e.ReuseDecodersInvalid(t))}(t?.reuseDecoders)}function d(t){if(!Number.isInteger(t)||t<1)throw new n("invalid_concurrency",e.ConcurrencyInvalid(t))}function s(t){if(void 0!==t&&"boolean"!=typeof t)throw new n("invalid_input",e.ContinueOnErrorInvalid(t))}function l(t){if(t?.aborted)throw new n("aborted",e.Aborted)}function u(t){const o=String(t).toLowerCase();if(!i.includes(o))throw new n("invalid_format",e.UnsupportedFormat(String(t)))}function c(t){if(!t)return;const{maxWidth:i,maxHeight:o,scale:r}=t;if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<=0))throw new n("invalid_resize",e.ScaleInvalid(r));if(void 0!==i&&("number"!=typeof i||!Number.isFinite(i)||i<=0))throw new n("invalid_resize",e.MaxWidthInvalid(i));if(void 0!==o&&("number"!=typeof o||!Number.isFinite(o)||o<=0))throw new n("invalid_resize",e.MaxHeightInvalid(o))}function f(t){if(!t)return;const{x:i=0,y:o=0,width:r,height:a}=t;if(!Number.isInteger(r)||r<=0)throw new n("invalid_crop",e.CropInvalid("width",r));if(!Number.isInteger(a)||a<=0)throw new n("invalid_crop",e.CropInvalid("height",a));if(!Number.isInteger(i)||i<0)throw new n("invalid_crop",e.CropInvalid("x",i));if(!Number.isInteger(o)||o<0)throw new n("invalid_crop",e.CropInvalid("y",o))}function h(e,t){return Math.min(e,t)}async function v(t,i,o,r){const a=!0===r?.continueOnError,d=r?.signal,s=new Array(t.length);let l=0,u=!1,c=0,f=null,v=-1,p=0;const m=[];let g;const b=new Promise(e=>{g=e}),w=()=>g?.();d&&!a&&d.addEventListener("abort",w,{once:!0});const y=h(i,t.length),I=Array.from({length:y},()=>(async()=>{for(;!u&&!d?.aborted||a;){const i=l;if(l+=1,i>=t.length)return;if(a&&d?.aborted){const o=new n("aborted",e.Aborted);for(let e=i;e<t.length;e++)s[e]={index:e,ok:!1,error:o};return void(l=t.length)}try{const e=await o(t[i],i);s[i]={index:i,ok:!0,result:e},c+=1}catch(e){if(p+=1,a){s[i]={index:i,ok:!1,error:e instanceof Error?e:new Error(String(e))};continue}u?m.length<2&&m.push(e instanceof Error?e.message:String(e)):(u=!0,f=e,v=i,g?.())}}})());try{if(a)return await Promise.all(I),s;if(await Promise.race([Promise.all(I),b]),c===t.length)return s.map(t=>{if(!t||!t.ok)throw new n("batch_item_failed",e.BatchItemProducedNoResult(t?.index));return t.result});if(d?.aborted)throw new n("aborted",e.Aborted);if(u){const i=f instanceof Error?f.message:String(f);let o=e.ConvertManyItemFailed(v+1,t.length,i);throw p>1&&(o+=e.ConvertManyExtraFailures(p,t.length),m.length>0&&(o+=e.ConvertManyOtherErrors(m))),new n("batch_item_failed",o,{cause:f,itemIndex:v,itemTotal:t.length,failedCount:p})}throw new n("batch_item_failed",e.BatchEndedWithoutResult)}finally{d?.removeEventListener("abort",w)}}export{o as DEFAULT_QUALITY,n as HeicConverterError,e as Messages,i as SUPPORTED_FORMATS,t as clampPercent,v as runBoundedBatch,h as runnerCountFor,l as throwIfAborted,a as validateBatchOptions,d as validateConcurrency,s as validateContinueOnError,r as validateConvertOptions,f as validateCrop,u as validateFormat,c as validateResize};
|