@keeratita/heic-converter 0.6.2-prerelease → 0.6.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/types.d.ts DELETED
@@ -1,257 +0,0 @@
1
- export interface DecodedImage {
2
- width: number;
3
- height: number;
4
- /**
5
- * RGBA pixel data, interleaved, row-major, 4 bytes per pixel.
6
- *
7
- * The buffer is always a plain `ArrayBuffer` owned by the returned array
8
- * (never a view into the WASM heap), so it stays valid after
9
- * `LibheifDecoder.free()` and can be passed directly to
10
- * `new ImageData(...)` / `putImageData` — including the `ImageData`
11
- * overload that requires `Uint8ClampedArray<ArrayBuffer>` under TS >= 5.7.
12
- */
13
- data: Uint8ClampedArray;
14
- /**
15
- * Raw EXIF block copied from the source file, normalized to the JPEG APP1
16
- * payload form: `"Exif\0\0"` followed by the TIFF structure. Present when
17
- * the file carries an Exif item — including files where libheif already
18
- * applied `irot`/`imir` (the block is reported independently of
19
- * {@link DecodedImage.orientation}).
20
- *
21
- * `convertHeic` re-injects this block into JPEG (APP1) and PNG (`eXIf`)
22
- * output when `preserveExif: true`; raw-decode consumers can attach it to
23
- * their own encoder output (e.g. `sharp`'s `.withMetadata({ exif })`).
24
- * Owned by the returned object; never a WASM-heap view.
25
- */
26
- exif?: Uint8Array;
27
- /**
28
- * EXIF orientation of the **stored** pixels (1–8, EXIF tag 274 semantics;
29
- * 1 = upright). Absent or 1 means no rotation is pending.
30
- *
31
- * libheif already applies `irot`/`imir` container transforms during
32
- * decode — for those files this is 1 and the pixels are upright. A value
33
- * > 1 means the orientation comes only from the Exif item: `convertHeic`
34
- * applies it automatically (unless `applyOrientation: false`), while raw
35
- * `decode()` consumers get stored pixels and must apply it themselves.
36
- * Decoders that do not report orientation may omit this field.
37
- */
38
- orientation?: number;
39
- }
40
- /**
41
- * Decoder contract used by {@link ConvertOptions.decoder} /
42
- * {@link ConvertManyOptions.decoder} and implemented by `LibheifDecoder`.
43
- *
44
- * Lifecycle rules followed by the library (implementations may rely on them):
45
- * - `initialize()` is called before every `decode()`; implementations must
46
- * make repeated/concurrent calls cheap (e.g. memoize the load promise).
47
- * - `decode()` is awaited before the library calls `free()`; the returned
48
- * `DecodedImage` must therefore not reference decoder-owned memory that
49
- * `free()` releases (copy pixels out, as `LibheifDecoder` does).
50
- * - `free()` is called at most once per conversion. Decoders **injected** via
51
- * options are never freed by the library — the caller owns their lifetime.
52
- *
53
- * Concurrency: with `convertMany`, a single injected decoder is shared by
54
- * all concurrent conversions, so `decode()` must be safe to call concurrently
55
- * on one instance (no shared mutable state across in-flight decodes).
56
- */
57
- export interface IHeicDecoder {
58
- /**
59
- * Initializes the decoder (e.g., loading WebAssembly module).
60
- */
61
- initialize(): Promise<void>;
62
- /**
63
- * Decodes HEIC binary data into raw RGBA pixel data.
64
- * @param data The HEIC file as a Uint8Array.
65
- * @param onProgress Optional progress callback that receives the progress percentage.
66
- */
67
- decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
68
- /**
69
- * Cleans up allocated resources. Idempotent: safe to call multiple times.
70
- */
71
- free(): void;
72
- }
73
- export type ImageFormat = 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp' | 'avif';
74
- /**
75
- * Formats accepted by {@link ConvertOptions.to} (case-insensitive).
76
- * `'jpg'` is an alias of `'jpeg'`. `'avif'` requires an environment whose
77
- * canvas can encode AVIF (Chromium/Firefox today); elsewhere it rejects with
78
- * `format_unsupported`.
79
- */
80
- export declare const SUPPORTED_FORMATS: readonly ImageFormat[];
81
- /** Default JPEG/WebP encoding quality used when `quality` is not provided. */
82
- export declare const DEFAULT_QUALITY = 0.92;
83
- /**
84
- * Accepted input for every convert entry point. `ArrayBufferView` is a
85
- * declared (tested) surface: DataView and non-Uint8 typed arrays are read as
86
- * raw bytes (byteOffset/byteLength), including SharedArrayBuffer-backed
87
- * views. Cross-realm Blob-likes (anything exposing `arrayBuffer()`, e.g. a
88
- * Blob from another frame) are accepted at runtime even though `instanceof
89
- * Blob` cannot see them.
90
- */
91
- export type HeicInput = Blob | ArrayBuffer | ArrayBufferView;
92
- /**
93
- * How {@link convertHeic} returns the converted image.
94
- * - `'blob'` — a `Blob` (the default; browser-native, works everywhere)
95
- * - `'dataUrl'` — a `data:image/...;base64,…` string (previews, `<img src>`)
96
- * - `'arrayBuffer'` — raw bytes (uploads, WebCodecs, Node-friendly transfer)
97
- */
98
- export type OutputShape = 'blob' | 'dataUrl' | 'arrayBuffer';
99
- /** Resolved return type of `convertHeic`/`convertMany` for an output shape. */
100
- export type ConvertResult<S extends OutputShape> = S extends 'dataUrl' ? string : S extends 'arrayBuffer' ? ArrayBuffer : Blob;
101
- /** Crop rectangle in **post-orientation display pixels** (top-left origin). */
102
- export interface CropOptions {
103
- /** Left edge of the crop box. @default 0 */
104
- x?: number;
105
- /** Top edge of the crop box. @default 0 */
106
- y?: number;
107
- /** Crop width in pixels. Must be a positive integer and fit inside the image. */
108
- width: number;
109
- /** Crop height in pixels. Must be a positive integer and fit inside the image. */
110
- height: number;
111
- }
112
- /** Per-item outcome when `continueOnError: true`. */
113
- export type ConvertItemResult<T = Blob> = {
114
- index: number;
115
- ok: true;
116
- result: T;
117
- } | {
118
- index: number;
119
- ok: false;
120
- error: Error;
121
- };
122
- export interface ResizeOptions {
123
- /**
124
- * Maximum width in pixels. The image is downscaled to fit within this
125
- * bound while preserving the aspect ratio. Images smaller than the bound
126
- * are never upscaled.
127
- */
128
- maxWidth?: number;
129
- /**
130
- * Maximum height in pixels. The image is downscaled to fit within this
131
- * bound while preserving the aspect ratio. Images smaller than the bound
132
- * are never upscaled.
133
- */
134
- maxHeight?: number;
135
- /**
136
- * Uniform scale factor applied to both dimensions (e.g. 0.5 halves the
137
- * image). Takes precedence over `maxWidth` and `maxHeight` when set.
138
- */
139
- scale?: number;
140
- }
141
- export interface ConvertOptions extends ResizeOptions {
142
- /**
143
- * Target format for the conversion. Must be one of the values in
144
- * {@link SUPPORTED_FORMATS}; an unknown value is rejected up front,
145
- * before the input is decoded.
146
- * @default 'jpeg'
147
- */
148
- to?: ImageFormat;
149
- /**
150
- * Quality of the converted image, between 0.0 and 1.0 (inclusive).
151
- * Applicable for 'jpeg', 'jpg', 'webp', and 'avif' formats — but validated
152
- * for every format: passing an out-of-range value (e.g. `90` from a 0-100
153
- * scale) throws regardless of `to`.
154
- * @default 0.92
155
- */
156
- quality?: number;
157
- /**
158
- * Optional custom decoder implementation to inject.
159
- * If not provided, a default LibheifDecoder is used.
160
- * The library never calls `free()` on an injected decoder.
161
- */
162
- decoder?: IHeicDecoder;
163
- /**
164
- * Optional progress callback that receives the progress percentage during
165
- * decoding. Values are normalized and clamped to the range 0 to 100; the
166
- * final 100% is emitted only when the conversion succeeds. A callback that
167
- * throws rejects the conversion with `progress_callback_failed`.
168
- */
169
- onProgress?: (percent: number) => void;
170
- /**
171
- * Rotate/flip the output so it matches the source's EXIF orientation
172
- * (applied as a canvas transform during rendering; `irot`/`imir` container
173
- * transforms are already applied by the decoder and never stacked on top).
174
- * Set `false` to keep the exact stored-pixel geometry. A non-boolean value
175
- * is rejected up front with `invalid_input`.
176
- * @default true
177
- */
178
- applyOrientation?: boolean;
179
- /**
180
- * Representation of the converted image. See {@link OutputShape}.
181
- * @default 'blob'
182
- */
183
- output?: OutputShape;
184
- /**
185
- * AbortSignal that cancels the conversion. Cancellation is checked at
186
- * stage boundaries (input read, decoder init, before/after decode,
187
- * before encode) and aborts `convertHeicInWorker` calls immediately by
188
- * terminating the worker; the synchronous WASM decode itself cannot be
189
- * preempted mid-call. An aborted signal rejects with code `aborted`.
190
- */
191
- signal?: AbortSignal;
192
- /**
193
- * Crop rectangle in post-orientation display pixels (the geometry the
194
- * image will be displayed in). Applied before resize: `scale`/`maxWidth`/
195
- * `maxHeight` then downscale the cropped region. Out-of-bounds crops
196
- * reject with `invalid_crop`.
197
- */
198
- crop?: CropOptions;
199
- /**
200
- * Copy the source HEIC's EXIF block into JPEG (APP1) and PNG (`eXIf`
201
- * chunk) output so converted files keep camera metadata (orientation,
202
- * GPS, timestamps). Note this **preserves private data** like GPS — set
203
- * deliberately. Ignored for `webp`/`svg` output.
204
- * @default false
205
- */
206
- preserveExif?: boolean;
207
- /**
208
- * Decode with the platform's native HEIC stack (`createImageBitmap` on
209
- * Safari/iOS, Edge, Windows) instead of the bundled libheif WASM decoder,
210
- * skipping its ~300 KB payload. Hosts without native HEIC support fall
211
- * back to libheif on the same conversion; the refusal is cached per realm.
212
- *
213
- * Ignored (libheif used) with an injected `decoder`, `preserveExif: true`
214
- * or `applyOrientation: false`. Native output is upright and progress
215
- * fires only at completion (tile progress is a libheif feature).
216
- * @default false
217
- */
218
- nativeDecode?: boolean;
219
- }
220
- export interface ConvertManyOptions extends Omit<ConvertOptions, 'onProgress'> {
221
- /**
222
- * Maximum number of conversions running concurrently.
223
- * @default 4
224
- */
225
- concurrency?: number;
226
- /**
227
- * Optional progress callback that receives the item index (0-based) and
228
- * its progress percentage (normalized to 0 to 100) during decoding.
229
- */
230
- onProgress?: (index: number, percent: number) => void;
231
- /**
232
- * Optional custom decoder implementation to inject. When provided, the
233
- * same instance is shared by all concurrent conversions, so it must be
234
- * safe for concurrent `decode()` calls (see {@link IHeicDecoder}). If not
235
- * provided, a fresh default LibheifDecoder is created per item.
236
- */
237
- decoder?: IHeicDecoder;
238
- /**
239
- * Resolve with per-item results instead of rejecting the whole batch on
240
- * the first failure: the promise fulfills with `ConvertItemResult[]` in
241
- * input order, each item `{ index, ok: true, result }` or
242
- * `{ index, ok: false, error }`. All items always run to completion.
243
- * Up-front option validation failures still reject normally (a typo is a
244
- * caller bug, not an item failure).
245
- * @default false
246
- */
247
- continueOnError?: boolean;
248
- /**
249
- * Reuse one library-owned `LibheifDecoder` per concurrent runner across
250
- * items instead of creating (and WASM-initializing) a fresh instance per
251
- * item — amortizes the module load in large batches while preserving the
252
- * exclusive-use invariant (an instance is only ever held by one runner,
253
- * never decodes concurrently). Ignored when `decoder` is injected.
254
- * @default false
255
- */
256
- reuseDecoders?: boolean;
257
- }
@@ -1,59 +0,0 @@
1
- import type { CropOptions, ImageFormat, ResizeOptions } from './types';
2
- /**
3
- * Option validators shared by `index.ts` (convertHeic/convertMany) and
4
- * `worker.ts` (the *InWorker APIs perform the same up-front checks so a
5
- * typo surfaces its own error code on the main thread instead of coming
6
- * back stringified as worker_failed). Lives in its own module to keep
7
- * index ↔ worker import-free; the render layer imports these too for its
8
- * internal re-checks, so validation lives in exactly one place.
9
- */
10
- /**
11
- * Upper bound for `concurrency` / `maxConcurrentWorkers`. Every unit of
12
- * concurrency is a full WASM boot (its own instantiated module and grown
13
- * heap), so a runaway config value — a query param, a queue-size setting —
14
- * would otherwise boot hundreds of decoders and take the page down. The
15
- * default paths clamp to 8; explicit values may reach this ceiling.
16
- */
17
- export declare const MAX_BATCH_CONCURRENCY = 64;
18
- /** Validates every per-conversion option shared by all four entry points. */
19
- export declare function validateConvertOptions(options?: {
20
- to?: ImageFormat;
21
- quality?: number;
22
- applyOrientation?: boolean;
23
- output?: unknown;
24
- signal?: AbortSignal;
25
- crop?: CropOptions;
26
- preserveExif?: boolean;
27
- nativeDecode?: boolean;
28
- maxWidth?: number;
29
- maxHeight?: number;
30
- scale?: number;
31
- }): void;
32
- /**
33
- * Validates the batch knobs shared by both batch entry points (convertMany
34
- * and convertManyInWorker both call this). The worker-only knobs
35
- * (`maxConcurrentWorkers`, `timeoutMs`) are validated in `src/worker.ts`, so
36
- * their message text stays in the lazy worker chunk.
37
- */
38
- export declare function validateBatchOptions(options?: {
39
- continueOnError?: boolean;
40
- reuseDecoders?: boolean;
41
- }): void;
42
- /** @throws `invalid_concurrency` for a `concurrency` outside 1..MAX_BATCH_CONCURRENCY. */
43
- export declare function validateConcurrency(concurrency: number): void;
44
- /** Boundary check for cooperative cancellation (sync WASM decode cannot be preempted). */
45
- export declare function throwIfAborted(signal?: AbortSignal): void;
46
- /**
47
- * Validates that a requested output format is supported (case-insensitive).
48
- */
49
- export declare function validateFormat(format: ImageFormat): void;
50
- /**
51
- * Validates resize options. Throws if any value is not a positive finite number.
52
- */
53
- export declare function validateResize(resize?: ResizeOptions): void;
54
- /**
55
- * Validates the crop rectangle *shape* (integer, positive, non-negative).
56
- * Range checking against the image size happens in `renderAndEncode`, once
57
- * the post-orientation display dimensions are known.
58
- */
59
- export declare function validateCrop(crop?: CropOptions): void;
@@ -1,3 +0,0 @@
1
- export declare function markFaulted(decoder: object): void;
2
- export declare function clearFaulted(decoder: object): void;
3
- export declare function isDecoderPoisoned(decoder: object): boolean;
@@ -1 +0,0 @@
1
- export * from './wrapper';
@@ -1,46 +0,0 @@
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
- }
@@ -1,61 +0,0 @@
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
- /**
27
- * Memoized module-loading promise so concurrent initialize()/decode() calls
28
- * on the same instance never instantiate (or mutate) the module twice.
29
- * Resolves null when a concurrent free() discarded the freshly loaded
30
- * module (see initGeneration).
31
- */
32
- private initPromise;
33
- /**
34
- * Generation counter for init/free races: a load that finishes after a
35
- * concurrent free() must not resurrect module.
36
- */
37
- private initGeneration;
38
- constructor(options?: LibheifDecoderOptions);
39
- /**
40
- * Initializes the WebAssembly module (the raw C-ABI decoder surface).
41
- * Safe to call concurrently: the module is loaded at most once per instance.
42
- */
43
- initialize(): Promise<void>;
44
- /**
45
- * Decodes HEIC binary data into raw RGBA pixel data.
46
- * @param data The HEIC file contents as a Uint8Array.
47
- * @param onProgress Optional progress callback (receives a normalized
48
- * percentage clamped to 0-100).
49
- */
50
- decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
51
- /**
52
- * Cleans up the WebAssembly decoder resources.
53
- * Idempotent: safe to call multiple times. After free(), the next
54
- * initialize() — or decode() directly, which re-initializes transparently
55
- * — loads a fresh module.
56
- *
57
- * free() is also safe to call while initialize() is in flight: a load that
58
- * completes after free() discards itself instead of resurrecting state.
59
- */
60
- free(): void;
61
- }
@@ -1 +0,0 @@
1
- "use strict";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})};
package/dist/worker.d.ts DELETED
@@ -1,128 +0,0 @@
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 {};
File without changes