imagepressor 0.2.0 → 0.2.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/README.md CHANGED
@@ -23,10 +23,10 @@
23
23
  - **Zero-Memory Chunk-Hopping Inspector:** `getImageMetadata()` reads RIFF headers and hops past multi-megabyte image pixel frames directly to the metadata chunks, keeping memory footprint minimal.
24
24
  - **Smart Anti-Expansion Guards & Strict Mode:**
25
25
  - Prevents generational file bloat when re-compressing already-optimized images.
26
- - Automatically guards against WebP 100% lossless mode (`VP8L`) inflation.
26
+ - Automatically guards against browser WebP 100% lossless mode (`VP8L`) inflation.
27
27
  - Supports `strict: true` (following Compressor.js standards) to guarantee output is never larger than the input file.
28
28
  - **Native Transparency via WebP:** Recommends modern WebP for transparent assets (logos, UI graphics), eliminating black backgrounds without lossless PNG bloat.
29
- - **Zero Runtime Dependencies:** Pure TypeScript and native Web Platform APIs. Under 8 KB minified.
29
+ - **Zero Runtime Dependencies:** Pure TypeScript and native Web Platform APIs. ~6 KB min+gzip.
30
30
 
31
31
  ---
32
32
 
@@ -51,7 +51,9 @@ Compress an image down to under 1 MB and max 1920px width:
51
51
  ```typescript
52
52
  import { compressImage } from "imagepressor";
53
53
 
54
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
54
+ const fileInput = document.querySelector(
55
+ 'input[type="file"]',
56
+ ) as HTMLInputElement;
55
57
 
56
58
  fileInput.addEventListener("change", async (event) => {
57
59
  const target = event.target as HTMLInputElement;
@@ -60,9 +62,9 @@ fileInput.addEventListener("change", async (event) => {
60
62
 
61
63
  try {
62
64
  const compressed = await compressImage(file, {
63
- maxSizeMB: 1, // Target maximum size: 1 MB
64
- maxWidth: 1920, // Max width in pixels (aspect ratio maintained)
65
- quality: 0.85, // Visual quality (0.0 to 1.0)
65
+ maxSizeMB: 1, // Target maximum size: 1 MB
66
+ maxWidth: 1920, // Max width in pixels (aspect ratio maintained)
67
+ quality: 0.85, // Visual quality (0.0 to 1.0)
66
68
  });
67
69
 
68
70
  console.log("Original size:", file.size);
@@ -140,44 +142,44 @@ import { getImageMetadata } from "imagepressor";
140
142
 
141
143
  const metadata = await getImageMetadata(file);
142
144
 
143
- console.log(metadata.hasExif); // true
144
- console.log(metadata.make); // "Apple"
145
- console.log(metadata.model); // "iPhone 15 Pro"
146
- console.log(metadata.dateTime); // "2024:05:12 14:23:01"
147
- console.log(metadata.colorSpace); // "Display P3 / Wide Gamut (ICCP Preserved)"
148
- console.log(metadata.orientation); // 1
145
+ console.log(metadata.hasExif); // true
146
+ console.log(metadata.make); // "Apple"
147
+ console.log(metadata.model); // "iPhone 15 Pro"
148
+ console.log(metadata.dateTime); // "2024:05:12 14:23:01"
149
+ console.log(metadata.colorSpace); // "ICC profile embedded" (or "sRGB (Standard)")
150
+ console.log(metadata.orientation); // 1
149
151
  ```
150
152
 
151
153
  ---
152
154
 
153
155
  ## Options API Reference
154
156
 
155
- | Option | Type | Default | Description |
156
- | :--- | :--- | :--- | :--- |
157
- | `maxSizeMB` | `number` | `undefined` | Target maximum output file size in megabytes (e.g. `1` for 1 MB). If omitted, compression is governed by `quality` and dimensions without forcing a hard megabyte ceiling. |
158
- | `maxWidth` | `number` | `undefined` | Maximum width in pixels. Proportional scaling preserves aspect ratio. |
159
- | `maxHeight` | `number` | `undefined` | Maximum height in pixels. Proportional scaling preserves aspect ratio. |
160
- | `quality` | `number` | `0.85` | Compression quality between `0.0` (lowest, smallest) and `1.0` (highest, largest). |
161
- | `mimeType` | `"image/jpeg" \| "image/webp"` | input type | Target output format (`"image/jpeg"`, `"image/webp"`). Defaults to input MIME type (WebP/PNG $\rightarrow$ WebP, JPEG $\rightarrow$ JPEG). |
162
- | `preserveMetadata`| `boolean` | `true` | When `true`, extracts and re-injects camera EXIF and Display P3 ICC color profiles for both JPEG and WebP outputs. |
163
- | `strict` | `boolean` | `true` (same format) | When `true`, returns the original image if compression output turns out larger than the original image without dimension downscaling. |
164
- | `useWebWorker` | `boolean` | `true` | Runs off the main thread in an inline Web Worker. Automatically falls back to main-thread processing if workers or `OffscreenCanvas` are unavailable. |
165
- | `signal` | `AbortSignal` | `undefined` | An `AbortSignal` to cancel compression immediately and clean up worker memory. |
166
- | `onProgress` | `(progress: number, stage: string) => void` | `undefined` | Callback receiving `(percent: number, stage: string)`. |
157
+ | Option | Type | Default | Description |
158
+ | :----------------- | :------------------------------------------ | :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
159
+ | `maxSizeMB` | `number` | `undefined` | Target maximum output file size in megabytes (e.g. `1` for 1 MB). If omitted, compression is governed by `quality` and dimensions without forcing a hard megabyte ceiling. |
160
+ | `maxWidth` | `number` | `undefined` | Maximum width in pixels. Proportional scaling preserves aspect ratio. |
161
+ | `maxHeight` | `number` | `undefined` | Maximum height in pixels. Proportional scaling preserves aspect ratio. |
162
+ | `quality` | `number` | `0.85` | Compression quality between `0.0` (lowest, smallest) and `1.0` (highest, largest). |
163
+ | `mimeType` | `"image/jpeg" \| "image/webp"` | input type | Target output format (`"image/jpeg"`, `"image/webp"`). Defaults to input MIME type (WebP/PNG $\rightarrow$ WebP, JPEG $\rightarrow$ JPEG). |
164
+ | `preserveMetadata` | `boolean` | `true` | When `true`, extracts and re-injects camera EXIF and the embedded ICC color profile for both JPEG and WebP outputs. Best-effort: corrupt metadata never fails a compression. |
165
+ | `strict` | `boolean` | `true` (same format) | When `true`, returns the original image if compression output turns out larger than the original image without dimension downscaling. Ignored when `maxSizeMB` is set: the smallest attempt is returned so the requested ceiling wins. |
166
+ | `useWebWorker` | `boolean` | `true` | Runs off the main thread in an inline Web Worker. Automatically falls back to main-thread processing if workers or `OffscreenCanvas` are unavailable. |
167
+ | `signal` | `AbortSignal` | `undefined` | An `AbortSignal` to cancel compression immediately and clean up worker memory. |
168
+ | `onProgress` | `(progress: number, stage: string) => void` | `undefined` | Callback receiving `(percent: number, stage: string)`. |
167
169
 
168
170
  ---
169
171
 
170
172
  ## Exported Utilities
171
173
 
172
- | Function | Description |
173
- | :--- | :--- |
174
- | `compressImage(fileOrBlob, options)` | Primary client-side compression function with worker offloading and metadata preservation. |
175
- | `getImageMetadata(blob)` | Fast zero-memory metadata scanner for JPEG APP1/APP2 markers and WebP RIFF chunks. |
176
- | `extractMetadataSegments(blob)` | Extracts raw binary metadata segments (EXIF APP1 and ICC APP2) from JPEG or WebP files. |
177
- | `spliceMetadataIntoBlob(blob, segments)` | Injects binary metadata segments into a JPEG blob. |
178
- | `spliceWebpMetadata(blob, segments, w, h)` | Muxes binary metadata segments into an extended WebP container. |
179
- | `insertWebPExif(webpBytes, rawExif, rawIcc, w, h)` | Low-level pure TypeScript WebP RIFF muxer that upgrades simple VP8 WebP to extended VP8X. |
180
- | `normalizeExifOrientation(segment)` | Normalizes EXIF orientation tag in-place to `1` (Standard). |
174
+ | Function | Description |
175
+ | :------------------------------------------------- | :----------------------------------------------------------------------------------------- |
176
+ | `compressImage(fileOrBlob, options)` | Primary client-side compression function with worker offloading and metadata preservation. |
177
+ | `getImageMetadata(blob)` | Fast zero-memory metadata scanner for JPEG APP1/APP2 markers and WebP RIFF chunks. |
178
+ | `extractMetadataSegments(blob)` | Extracts raw binary metadata segments (EXIF APP1 and ICC APP2) from JPEG or WebP files. |
179
+ | `spliceMetadataIntoBlob(blob, segments)` | Injects binary metadata segments into a JPEG blob. |
180
+ | `spliceWebpMetadata(blob, segments, w, h)` | Muxes binary metadata segments into an extended WebP container. |
181
+ | `insertWebPExif(webpBytes, rawExif, rawIcc, w, h)` | Low-level pure TypeScript WebP RIFF muxer that upgrades simple VP8 WebP to extended VP8X. |
182
+ | `normalizeExifOrientation(segment)` | Normalizes EXIF orientation tag in-place to `1` (Standard). |
181
183
 
182
184
  ---
183
185
 
@@ -1 +1 @@
1
- {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../src/canvas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAwG5B"}
1
+ {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../src/canvas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAwF5B"}
package/dist/index.cjs CHANGED
@@ -1,39 +1,37 @@
1
- var{defineProperty:F,getOwnPropertyNames:j,getOwnPropertyDescriptor:Z}=Object,J=Object.prototype.hasOwnProperty;function H(e){return this[e]}var O=(e)=>{var t=(k??=new WeakMap).get(e),f;if(t)return t;if(t=F({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var r of j(e))if(!J.call(t,r))F(t,r,{get:H.bind(e,r),enumerable:!(f=Z(e,r))||f.enumerable})}return k.set(e,t),t},k;var q=(e)=>e;function Q(e,t){this[e]=q.bind(null,t)}var Y=(e,t)=>{for(var f in t)F(e,f,{get:t[f],enumerable:!0,configurable:!0,set:Q.bind(t,f)})};var oe={};Y(oe,{compressImage:()=>X,compressWithMainThread:()=>b,compressWithWorker:()=>A,default:()=>se,extractMetadataSegments:()=>U,getImageMetadata:()=>L,getJpegMetadata:()=>D,insertWebPExif:()=>z,normalizeExifOrientation:()=>C,spliceMetadataIntoBlob:()=>I,spliceWebpMetadata:()=>E});module.exports=O(oe);async function b(e,t,f,r,i,n){if(n?.aborted)throw new DOMException("Compression aborted","AbortError");if(typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u"){let s;try{s=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{s=await createImageBitmap(e)}let o=s.width,a=s.height;if(t&&o>t)a=Math.round(a*t/o),o=t;if(f&&a>f)o=Math.round(o*f/a),a=f;let d=new OffscreenCanvas(o,a),c=d.getContext("2d");if(!c)throw Error("OffscreenCanvas 2D context unavailable");return c.drawImage(s,0,0,o,a),s.close(),{blob:await d.convertToBlob({type:i,quality:r}),width:o,height:a}}return new Promise((s,o)=>{if(typeof window>"u"||typeof document>"u"){s({blob:e,width:0,height:0});return}let a=new Image,d=URL.createObjectURL(e),c=()=>{URL.revokeObjectURL(d),o(new DOMException("Compression aborted","AbortError"))};if(n){if(n.aborted)return c();n.addEventListener("abort",c,{once:!0})}a.onload=()=>{URL.revokeObjectURL(d);let{naturalWidth:u,naturalHeight:g}=a;if(t&&u>t)g=Math.round(g*t/u),u=t;if(f&&g>f)u=Math.round(u*f/g),g=f;let p=document.createElement("canvas");p.width=u,p.height=g;let h=p.getContext("2d");if(!h){o(Error("Canvas 2D context unavailable"));return}h.drawImage(a,0,0,u,g),p.toBlob((x)=>{if(x)s({blob:x,width:u,height:g});else o(Error("Canvas compression failed to produce blob"))},i,r)},a.onerror=()=>{URL.revokeObjectURL(d),o(Error("Failed to load image for compression"))},a.src=d})}async function U(e){let t=Math.min(e.size,262144),f=await e.slice(0,t).arrayBuffer(),r=new DataView(f);if(r.byteLength<4)return[];if(r.getUint16(0)===65496){let i=[],n=2;while(n+4<r.byteLength){let s=r.getUint16(n);if(s===65498||s===65497||(s&65280)!==65280)break;let o=r.getUint16(n+2);if(o<2||n+2+o>r.byteLength)break;if(s===65505||s===65506){let a=new Uint8Array(f.slice(n,n+2+o));C(a),i.push(a)}n+=2+o}return i}if(r.byteLength>=12&&r.getUint32(0,!1)===1380533830&&r.getUint32(8,!1)===1464156752){let i=[],n=12,s=e.size;while(n+8<=s){let o,a;if(n+8<=r.byteLength)o=r.getUint32(n,!1),a=r.getUint32(n+4,!0);else{let c=await e.slice(n,n+8).arrayBuffer();if(c.byteLength<8)break;let u=new DataView(c);o=u.getUint32(0,!1),a=u.getUint32(4,!0)}let d=a+1&-2;if(o===1163413830&&a>=6){let c=await e.slice(n+8,n+8+a).arrayBuffer(),u=new Uint8Array(c),p=u.length>=6&&u[0]===69&&u[1]===120&&u[2]===105&&u[3]===102&&u[4]===0&&u[5]===0?u.subarray(6):u,h=8+p.length,x=new Uint8Array(2+h);x[0]=255,x[1]=225,x[2]=h>>8&255,x[3]=h&255,x[4]=69,x[5]=120,x[6]=105,x[7]=102,x[8]=0,x[9]=0,x.set(p,10),C(x),i.push(x)}if(o===1229144912&&a>0){let c=await e.slice(n+8,n+8+a).arrayBuffer(),u=new Uint8Array(c),g=16+u.length,p=new Uint8Array(2+g);p[0]=255,p[1]=226,p[2]=g>>8&255,p[3]=g&255;let h=[73,67,67,95,80,82,79,70,73,76,69,0,1,1];p.set(h,4),p.set(u,18),i.push(p)}n+=8+d}return i}return[]}function C(e){if(e.length<14)return!1;if(!(e[0]===255&&e[1]===225&&e[4]===69&&e[5]===120&&e[6]===105&&e[7]===102&&e[8]===0&&e[9]===0))return!1;let f=10,r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=r.getUint16(f)===18761;if(!i&&r.getUint16(f)!==19789)return!1;if(r.getUint16(f+2,i)!==42)return!1;let n=r.getUint32(f+4,i),s=f+n;if(s+2>e.length)return!1;let o=r.getUint16(s,i);for(let a=0;a<o;a++){let d=s+2+a*12;if(d+12>e.length)break;if(r.getUint16(d,i)===274)return r.setUint16(d+8,1,i),!0}return!1}async function I(e,t){if(t.length===0)return e;let f=await e.slice(0,32).arrayBuffer(),r=new DataView(f);if(r.byteLength<4||r.getUint16(0)!==65496)return e;let i=2;if(r.getUint16(2)===65504)i=4+r.getUint16(4);let n=e.slice(0,i),s=e.slice(i),o=t.map((a)=>a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength));return new Blob([n,...o,s],{type:e.type||"image/jpeg"})}async function L(e){let t={hasExif:!1,hasIccProfile:!1,colorSpace:"sRGB (Standard)"},f=Math.min(e.size,262144),r=await e.slice(0,f).arrayBuffer(),i=new DataView(r);if(i.byteLength<12)return t;if(i.getUint16(0)===65496){let n=2;while(n+4<i.byteLength){let s=i.getUint16(n);if(s===65498||s===65497||(s&65280)!==65280)break;let o=i.getUint16(n+2);if(o<2||n+2+o>i.byteLength)break;if(s===65506){if(t.hasIccProfile=!0,o>=14)t.colorSpace="Display P3 / Wide Gamut (APP2 Preserved)"}if(s===65505&&o>=14){if(i.getUint8(n+4)===69&&i.getUint8(n+5)===120&&i.getUint8(n+6)===105&&i.getUint8(n+7)===102)t.hasExif=!0,S(i,n+10,t)}n+=2+o}return t}if(i.byteLength>=12&&i.getUint32(0,!1)===1380533830&&i.getUint32(8,!1)===1464156752){let n=12,s=e.size;while(n+8<=s){let o,a;if(n+8<=i.byteLength)o=i.getUint32(n,!1),a=i.getUint32(n+4,!0);else{let c=await e.slice(n,n+8).arrayBuffer();if(c.byteLength<8)break;let u=new DataView(c);o=u.getUint32(0,!1),a=u.getUint32(4,!0)}let d=a+1&-2;if(o===1229144912)t.hasIccProfile=!0,t.colorSpace="Display P3 / Wide Gamut (ICCP Preserved)";if(o===1163413830&&a>=6){t.hasExif=!0;let c;if(n+8+a<=i.byteLength)c=new DataView(r,n+8,a);else{let g=await e.slice(n+8,n+8+a).arrayBuffer();c=new DataView(g)}let u=0;if(c.byteLength>=6&&c.getUint8(0)===69&&c.getUint8(1)===120&&c.getUint8(2)===105&&c.getUint8(3)===102&&c.getUint8(4)===0&&c.getUint8(5)===0)u=6;S(c,u,t)}n+=8+d}return t}return t}var D=L;function S(e,t,f){if(t+8>e.byteLength)return;let r=e.getUint16(t)===18761;if(!r&&e.getUint16(t)!==19789)return;if(e.getUint16(t+2,r)!==42)return;let i=e.getUint32(t+4,r),n=t+i;if(n+2>e.byteLength)return;let s,o=e.getUint16(n,r);for(let a=0;a<o;a++){let d=n+2+a*12;if(d+12>e.byteLength)break;let c=e.getUint16(d,r),u=e.getUint16(d+2,r),g=e.getUint32(d+4,r);if(c===274)f.orientation=e.getUint16(d+8,r);else if(c===271&&u===2)f.make=y(e,t,d,g,r);else if(c===272&&u===2)f.model=y(e,t,d,g,r);else if(c===306&&u===2)f.dateTime=y(e,t,d,g,r);else if(c===34665&&(u===3||u===4))s=e.getUint32(d+8,r)}if(s){let a=t+s;if(a+2<=e.byteLength){let d=e.getUint16(a,r);for(let c=0;c<d;c++){let u=a+2+c*12;if(u+12>e.byteLength)break;let g=e.getUint16(u,r),p=e.getUint16(u+2,r),h=e.getUint32(u+4,r);if((g===36867||g===36868)&&p===2&&!f.dateTime)f.dateTime=y(e,t,u,h,r)}}}}function y(e,t,f,r,i){if(r<=4){let d="";for(let c=0;c<r;c++){let u=e.getUint8(f+8+c);if(u===0)break;d+=String.fromCharCode(u)}return d.trim()}let n=e.getUint32(f+8,i),s=t+n;if(s>=e.byteLength)return"";let o=Math.min(r,e.byteLength-s),a="";for(let d=0;d<o;d++){let c=e.getUint8(s+d);if(c===0)break;a+=String.fromCharCode(c)}return a.trim()}function W(e,t){return String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])}function v(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function _(e,t,f){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,f,!0)}function V(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function B(e,t,f){e[t]=f&255,e[t+1]=f>>>8&255,e[t+2]=f>>>16&255}function K(e){if(e.length<12)throw Error("Invalid WebP: file is too small");if(W(e,0)!=="RIFF"||W(e,8)!=="WEBP")throw Error("Invalid WebP: missing RIFF/WEBP header");let t=v(e,4);if(Math.abs(t+8-e.length)>1&&t+8>e.length)throw Error("Invalid WebP: RIFF size mismatch");let f=[],r=12;while(r<e.length){if(r+8>e.length)break;let i=W(e,r),n=v(e,r+4),s=r+8,o=s+n,a=o+(n&1);if(o>e.length)break;f.push({fourCC:i,data:e.subarray(s,o)}),r=Math.min(a,e.length)}return f}function ee(e){let t=e.find((i)=>i.fourCC==="VP8X");if(t&&t.data.length>=10){let i=1+V(t.data,4),n=1+V(t.data,7),s=(t.data[0]&16)!==0;return{width:i,height:n,alpha:s}}let f=e.find((i)=>i.fourCC==="VP8 "),r=e.find((i)=>i.fourCC==="VP8L");if(f){let i=f.data;if(i.length>=10&&i[3]===157&&i[4]===1&&i[5]===42){let n=(i[6]|i[7]<<8)&16383,s=(i[8]|i[9]<<8)&16383;if(n&&s)return{width:n,height:s,alpha:!1}}}if(r){let i=r.data;if(i.length>=5&&i[0]===47){let n=i[1]|i[2]<<8|i[3]<<16|i[4]<<24,s=(n&16383)+1,o=(n>>>14&16383)+1,a=(n>>>28&1)!==0;return{width:s,height:o,alpha:a}}}return{width:1,height:1,alpha:!1}}function te(e,t,f,r,i){let{width:n,height:s,alpha:o}=ee(e);if(r&&(!n||n===1))n=r;if(i&&(!s||s===1))s=i;let a=0;if(t)a|=8;if(f||e.some((c)=>c.fourCC==="ICCP"))a|=32;if(o||e.some((c)=>c.fourCC==="ALPH"))a|=16;if(e.some((c)=>c.fourCC==="XMP "))a|=4;if(e.some((c)=>c.fourCC==="ANIM"||c.fourCC==="ANMF"))a|=2;let d=new Uint8Array(10);return d[0]=a,B(d,4,Math.max(0,n-1)),B(d,7,Math.max(0,s-1)),{fourCC:"VP8X",data:d}}function ne(e){if(e.length===0)throw Error("EXIF data cannot be empty");let t=e;if(t.length>=4&&t[0]===255&&t[1]===225)t=t.subarray(4);let r=t.length>=6&&t[0]===69&&t[1]===120&&t[2]===105&&t[3]===102&&t[4]===0&&t[5]===0?t.subarray(6):t;if(r.length<8)throw Error("Invalid EXIF TIFF header");let i=r[0]===73&&r[1]===73,n=r[0]===77&&r[1]===77;if(!i&&!n)throw Error("Invalid EXIF byte order");if((i?r[2]|r[3]<<8:r[2]<<8|r[3])!==42)throw Error("Invalid EXIF TIFF magic");return r}function re(e){let t=e;if(t.length>=4&&t[0]===255&&t[1]===226)t=t.subarray(4);if(t.length>=14&&t[0]===73&&t[1]===67&&t[2]===67&&t[3]===95&&t[4]===80&&t[5]===82&&t[6]===79&&t[7]===70&&t[8]===73&&t[9]===76&&t[10]===69&&t[11]===0)return t.subarray(14);return t}function ie(e){let t=12;for(let i of e)t+=8+i.data.length+(i.data.length&1);if(t-8>4294967295)throw Error("WebP file exceeds RIFF size limit");let f=new Uint8Array(t);f.set([82,73,70,70],0),_(f,4,t-8),f.set([87,69,66,80],8);let r=12;for(let i of e){for(let n=0;n<4;n++)f[r+n]=i.fourCC.charCodeAt(n);if(_(f,r+4,i.data.length),f.set(i.data,r+8),r+=8+i.data.length,i.data.length&1)f[r]=0,r++}return f}function z(e,t,f,r,i){if(!(e instanceof Uint8Array))throw TypeError("webp must be a Uint8Array");let n=t?ne(t):void 0,s=f?re(f):void 0,o=K(e),a=o.findIndex((d)=>d.fourCC==="VP8X");if(a!==-1){let c=o[a].data.slice();if(n)c[0]|=8;if(s)c[0]|=32;o[a]={fourCC:"VP8X",data:c}}else o=[te(o,Boolean(n),Boolean(s),r,i),...o];if(n)o=o.filter((d)=>d.fourCC!=="EXIF");if(s)o=o.filter((d)=>d.fourCC!=="ICCP");if(s){let d=o.findIndex((c)=>c.fourCC==="VP8X")+1;o.splice(d,0,{fourCC:"ICCP",data:s})}if(n)o.push({fourCC:"EXIF",data:n});return ie(o)}async function E(e,t,f,r){let i,n;for(let a of t)if(a.length>=14&&a[0]===255&&a[1]===225)i=a;else if(a.length>=18&&a[0]===255&&a[1]===226)n=a;if(!i&&!n)return e;let s=new Uint8Array(await e.arrayBuffer()),o=z(s,i,n,f,r);return new Blob([o.buffer.slice(0,o.byteLength)],{type:"image/webp"})}var ae=`
1
+ var{defineProperty:R,getOwnPropertyNames:ie,getOwnPropertyDescriptor:oe}=Object,se=Object.prototype.hasOwnProperty;function fe(e){return this[e]}var ce=(e)=>{var t=(V??=new WeakMap).get(e),r;if(t)return t;if(t=R({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var n of ie(e))if(!se.call(t,n))R(t,n,{get:fe.bind(e,n),enumerable:!(r=oe(e,n))||r.enumerable})}return V.set(e,t),t},V;var ue=(e)=>e;function pe(e,t){this[e]=ue.bind(null,t)}var de=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pe.bind(t,r)})};var Me={};de(Me,{compressImage:()=>ee,compressWithMainThread:()=>C,compressWithWorker:()=>z,default:()=>Fe,detectInputMime:()=>M,extractMetadataSegments:()=>L,getImageMetadata:()=>B,getJpegMetadata:()=>H,insertWebPExif:()=>T,normalizeExifOrientation:()=>P,spliceMetadataIntoBlob:()=>W,spliceWebpMetadata:()=>k});module.exports=ce(Me);function M(e,t){let r=e.type;if(r==="image/jpeg"||r==="image/webp"||r==="image/png")return r;let n=t??(e instanceof File?e.name:"");if(/\.(jpe?g)$/i.test(n))return"image/jpeg";if(/\.webp$/i.test(n))return"image/webp";if(/\.png$/i.test(n))return"image/png";return}async function j(e){if(e.size<4)return null;let t=await e.slice(0,12).arrayBuffer(),r=new DataView(t);if(r.byteLength>=2&&r.getUint16(0)===65496)return"jpeg";if(r.byteLength>=12&&r.getUint32(0,!1)===1380533830&&r.getUint32(8,!1)===1464156752)return"webp";return null}function v(e,t,r,n){if(r&&e>r)t=Math.round(t*r/e),e=r;if(n&&t>n)e=Math.round(e*n/t),t=n;return{width:e,height:t}}function w(e){e?.throwIfAborted()}async function C(e,t,r,n,a,i){if(w(i),typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u"){let c=await createImageBitmap(e),{width:u,height:o}=v(c.width,c.height,t,r),s=new OffscreenCanvas(u,o),f=s.getContext("2d");if(!f)throw Error("OffscreenCanvas 2D context unavailable");return f.drawImage(c,0,0,u,o),c.close(),{blob:await s.convertToBlob({type:a,quality:n}),width:u,height:o}}return new Promise((c,u)=>{if(typeof window>"u"||typeof document>"u"){c({blob:e,width:0,height:0});return}let o=new Image,s=URL.createObjectURL(e),f=!1,p=()=>{if(f)return;f=!0,URL.revokeObjectURL(s),u(new DOMException("Compression aborted","AbortError"))},d=(l)=>{if(f)return;f=!0,i?.removeEventListener("abort",p),l()};if(i){if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0})}o.onload=()=>{if(f)return;URL.revokeObjectURL(s);let{width:l,height:m}=v(o.naturalWidth,o.naturalHeight,t,r),g=document.createElement("canvas");g.width=l,g.height=m;let b=g.getContext("2d");if(!b){d(()=>u(Error("Canvas 2D context unavailable")));return}b.drawImage(o,0,0,l,m),g.toBlob((U)=>{if(U)d(()=>c({blob:U,width:l,height:m}));else d(()=>u(Error("Canvas compression failed to produce blob")))},a,n)},o.onerror=()=>{URL.revokeObjectURL(s),d(()=>u(Error("Failed to load image for compression")))},o.src=s})}var A=[69,120,105,102,0,0];function _(e,t=0){if(e.length<t+A.length)return!1;for(let r=0;r<A.length;r++)if(e[t+r]!==A[r])return!1;return!0}function O(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ge(e,t,r){return new Uint8Array(e.buffer.slice(e.byteOffset+t,e.byteOffset+r))}async function*le(e,t){let r=0,n=t,a=2;while(!0){if(a+4>n.byteLength){let s=r+a;if(s+4>e.size)return;let f=await e.slice(s,s+262144).arrayBuffer();if(f.byteLength<4)return;r=s,n=new DataView(f),a=0;continue}let i=n.getUint16(a);if(i===65498||i===65497||(i&65280)!==65280)return;let c=n.getUint16(a+2);if(c<2)return;let u=a+2+c,o=r+u;if(o>e.size)return;if(i===65505||i===65506){let s=u<=n.byteLength?ge(n,a,u):new Uint8Array(await e.slice(r+a,o).arrayBuffer());yield{kind:i===65505?"jpeg-app1":"jpeg-app2",bytes:s}}a=u}}async function*me(e,t){let r=e.size,n=12;while(n+8<=r){let a,i;if(n+8<=t.byteLength)a=t.getUint32(n,!1),i=t.getUint32(n+4,!0);else{let s=await e.slice(n,n+8).arrayBuffer();if(s.byteLength<8)return;let f=new DataView(s);a=f.getUint32(0,!1),i=f.getUint32(4,!0)}let c=i+1&-2,u=a===1163413830,o=a===1229144912;if(u&&i>=6||o){let s=n+8+i;if(s>r)return;if(i>0){let f=new Uint8Array(await e.slice(n+8,s).arrayBuffer());yield{kind:u?"webp-exif":"webp-iccp",bytes:f}}}n+=8+c}}async function*G(e){let t=Math.min(e.size,262144),r=await e.slice(0,t).arrayBuffer(),n=new DataView(r);if(n.byteLength<4)return;if(n.getUint16(0)===65496){yield*le(e,n);return}if(n.byteLength>=12&&n.getUint32(0,!1)===1380533830&&n.getUint32(8,!1)===1464156752)yield*me(e,n)}function he(e){let t=_(e)?e.subarray(A.length):e,r=2+A.length+t.length,n=new Uint8Array(2+r);return n[0]=255,n[1]=225,n[2]=r>>8&255,n[3]=r&255,n.set(A,4),n.set(t,4+A.length),n}function xe(e){let t=[73,67,67,95,80,82,79,70,73,76,69,0,1,1],r=2+t.length+e.length,n=new Uint8Array(2+r);return n[0]=255,n[1]=226,n[2]=r>>8&255,n[3]=r&255,n.set(t,4),n.set(e,4+t.length),n}async function L(e){let t=[];for await(let r of G(e))switch(r.kind){case"jpeg-app1":{P(r.bytes),t.push(r.bytes);break}case"jpeg-app2":{t.push(r.bytes);break}case"webp-exif":{let n=he(r.bytes);P(n),t.push(n);break}case"webp-iccp":{t.push(xe(r.bytes));break}}return t}function P(e){if(e.length<14)return!1;if(!(e[0]===255&&e[1]===225&&e[4]===69&&e[5]===120&&e[6]===105&&e[7]===102&&e[8]===0&&e[9]===0))return!1;let r=10,n=new DataView(e.buffer,e.byteOffset,e.byteLength),a=n.getUint16(r)===18761;if(!a&&n.getUint16(r)!==19789)return!1;if(n.getUint16(r+2,a)!==42)return!1;let i=n.getUint32(r+4,a),c=r+i;if(c+2>e.length)return!1;let u=n.getUint16(c,a);for(let o=0;o<u;o++){let s=c+2+o*12;if(s+12>e.length)break;if(n.getUint16(s,a)===274)return n.setUint16(s+8,1,a),!0}return!1}async function W(e,t){if(t.length===0)return e;let r=await e.slice(0,32).arrayBuffer(),n=new DataView(r);if(n.byteLength<4||n.getUint16(0)!==65496)return e;let a=2;if(n.getUint16(2)===65504)a=4+n.getUint16(4);let i=e.slice(0,a),c=e.slice(a),u=t.map((o)=>o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength));return new Blob([i,...u,c],{type:e.type||"image/jpeg"})}async function B(e){let t={hasExif:!1,hasIccProfile:!1,colorSpace:"sRGB (Standard)"};for await(let r of G(e))if(r.kind==="jpeg-app1"){if(_(r.bytes,4))t.hasExif=!0,X(O(r.bytes),10,t)}else if(r.kind==="webp-exif")t.hasExif=!0,X(O(r.bytes),_(r.bytes)?A.length:0,t);else t.hasIccProfile=!0,t.colorSpace="ICC profile embedded";return t}var H=B;function X(e,t,r){if(t+8>e.byteLength)return;let n=e.getUint16(t)===18761;if(!n&&e.getUint16(t)!==19789)return;if(e.getUint16(t+2,n)!==42)return;let a=e.getUint32(t+4,n),i=t+a;if(i+2>e.byteLength)return;let c,u=e.getUint16(i,n);for(let o=0;o<u;o++){let s=i+2+o*12;if(s+12>e.byteLength)break;let f=e.getUint16(s,n),p=e.getUint16(s+2,n),d=e.getUint32(s+4,n);if(f===274)r.orientation=e.getUint16(s+8,n);else if(f===271&&p===2)r.make=F(e,t,s,d,n);else if(f===272&&p===2)r.model=F(e,t,s,d,n);else if(f===306&&p===2)r.dateTime=F(e,t,s,d,n);else if(f===34665&&(p===3||p===4))c=e.getUint32(s+8,n)}if(c){let o=t+c;if(o+2<=e.byteLength){let s=e.getUint16(o,n);for(let f=0;f<s;f++){let p=o+2+f*12;if(p+12>e.byteLength)break;let d=e.getUint16(p,n),l=e.getUint16(p+2,n),m=e.getUint32(p+4,n);if((d===36867||d===36868)&&l===2&&!r.dateTime)r.dateTime=F(e,t,p,m,n)}}}}function F(e,t,r,n,a){if(n<=4){let s="";for(let f=0;f<n;f++){let p=e.getUint8(r+8+f);if(p===0)break;s+=String.fromCharCode(p)}return s.trim()}let i=e.getUint32(r+8,a),c=t+i;if(c>=e.byteLength)return"";let u=Math.min(n,e.byteLength-c),o="";for(let s=0;s<u;s++){let f=e.getUint8(c+s);if(f===0)break;o+=String.fromCharCode(f)}return o.trim()}var Z=new Set(["VP8 ","VP8L","ALPH","ANIM","ANMF"]);function D(e,t){return String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])}function J(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function K(e,t,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,r,!0)}function Q(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function q(e,t,r){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255}function be(e){if(e.length<12)throw Error("Invalid WebP: file is too small");if(D(e,0)!=="RIFF"||D(e,8)!=="WEBP")throw Error("Invalid WebP: missing RIFF/WEBP header");let t=J(e,4);if(Math.abs(t+8-e.length)>1&&t+8>e.length)throw Error("Invalid WebP: RIFF size mismatch");let r=[],n=12;while(n<e.length){if(n+8>e.length)break;let a=D(e,n),i=J(e,n+4),c=n+8,u=c+i,o=u+(i&1);if(u>e.length)break;r.push({fourCC:a,data:e.subarray(c,u)}),n=Math.min(o,e.length)}return r}function ye(e){let t=e.find((a)=>a.fourCC==="VP8X");if(t&&t.data.length>=10){let a=1+Q(t.data,4),i=1+Q(t.data,7),c=(t.data[0]&16)!==0;return{width:a,height:i,alpha:c}}let r=e.find((a)=>a.fourCC==="VP8 "),n=e.find((a)=>a.fourCC==="VP8L");if(r){let a=r.data;if(a.length>=10&&a[3]===157&&a[4]===1&&a[5]===42){let i=(a[6]|a[7]<<8)&16383,c=(a[8]|a[9]<<8)&16383;if(i&&c)return{width:i,height:c,alpha:!1}}}if(n){let a=n.data;if(a.length>=5&&a[0]===47){let i=a[1]|a[2]<<8|a[3]<<16|a[4]<<24,c=(i&16383)+1,u=(i>>>14&16383)+1,o=(i>>>28&1)!==0;return{width:c,height:u,alpha:o}}}return null}function we(e,t,r,n,a){let i=ye(e),c=i?.width??n??1,u=i?.height??a??1,o=i?.alpha??!1,s=0;if(t)s|=8;if(r||e.some((p)=>p.fourCC==="ICCP"))s|=32;if(o||e.some((p)=>p.fourCC==="ALPH"))s|=16;if(e.some((p)=>p.fourCC==="XMP "))s|=4;if(e.some((p)=>p.fourCC==="ANIM"||p.fourCC==="ANMF"))s|=2;let f=new Uint8Array(10);return f[0]=s,q(f,4,Math.max(0,c-1)),q(f,7,Math.max(0,u-1)),{fourCC:"VP8X",data:f}}function Ce(e){if(e.length===0)throw Error("EXIF data cannot be empty");let t=e;if(t.length>=4&&t[0]===255&&t[1]===225)t=t.subarray(4);let n=t.length>=6&&t[0]===69&&t[1]===120&&t[2]===105&&t[3]===102&&t[4]===0&&t[5]===0?t.subarray(6):t;if(n.length<8)throw Error("Invalid EXIF TIFF header");let a=n[0]===73&&n[1]===73,i=n[0]===77&&n[1]===77;if(!a&&!i)throw Error("Invalid EXIF byte order");if((a?n[2]|n[3]<<8:n[2]<<8|n[3])!==42)throw Error("Invalid EXIF TIFF magic");return n}function Ae(e){let t=e;if(t.length>=4&&t[0]===255&&t[1]===226)t=t.subarray(4);if(t.length>=14&&t[0]===73&&t[1]===67&&t[2]===67&&t[3]===95&&t[4]===80&&t[5]===82&&t[6]===79&&t[7]===70&&t[8]===73&&t[9]===76&&t[10]===69&&t[11]===0)return t.subarray(14);return t}function Ie(e){let t=12;for(let a of e)t+=8+a.data.length+(a.data.length&1);if(t-8>4294967295)throw Error("WebP file exceeds RIFF size limit");let r=new Uint8Array(t);r.set([82,73,70,70],0),K(r,4,t-8),r.set([87,69,66,80],8);let n=12;for(let a of e){for(let i=0;i<4;i++)r[n+i]=a.fourCC.charCodeAt(i);if(K(r,n+4,a.data.length),r.set(a.data,n+8),n+=8+a.data.length,a.data.length&1)r[n]=0,n++}return r}function T(e,t,r,n,a){if(!(e instanceof Uint8Array))throw TypeError("webp must be a Uint8Array");let i=t?Ce(t):void 0,c=r?Ae(r):void 0,u=be(e),o=u.find((g)=>g.fourCC==="EXIF"),s=u.find((g)=>g.fourCC==="ICCP"),f=i?{fourCC:"EXIF",data:i}:o,p=c?{fourCC:"ICCP",data:c}:s,d=u.filter((g)=>g.fourCC!=="VP8X"&&g.fourCC!=="EXIF"&&g.fourCC!=="ICCP"),l=[];if(p)l.push(p);if(l.push(...d.filter((g)=>Z.has(g.fourCC))),f)l.push(f);l.push(...d.filter((g)=>!Z.has(g.fourCC)));let m=we(l,Boolean(f),Boolean(p),n,a);return Ie([m,...l])}async function k(e,t,r,n){let a,i;for(let o of t)if(o.length>=14&&o[0]===255&&o[1]===225)a=o;else if(o.length>=18&&o[0]===255&&o[1]===226)i=o;if(!a&&!i)return e;let c=new Uint8Array(await e.arrayBuffer()),u=T(c,a,i,r,n);return new Blob([u.buffer.slice(0,u.byteLength)],{type:"image/webp"})}var Ue=`
2
+ function computeTargetSize(width, height, maxWidth, maxHeight) {
3
+ if (maxWidth && width > maxWidth) {
4
+ height = Math.round((height * maxWidth) / width);
5
+ width = maxWidth;
6
+ }
7
+ if (maxHeight && height > maxHeight) {
8
+ width = Math.round((width * maxHeight) / height);
9
+ height = maxHeight;
10
+ }
11
+ return { width, height };
12
+ }
2
13
  self.onmessage = async (e) => {
3
- const { id, blob, maxWidth, maxHeight, quality, mimeType } = e.data;
14
+ const { blob, maxWidth, maxHeight, quality, mimeType } = e.data;
4
15
  try {
5
- let bitmap;
6
- try {
7
- bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
8
- } catch {
9
- bitmap = await createImageBitmap(blob);
10
- }
11
-
12
- let width = bitmap.width;
13
- let height = bitmap.height;
14
-
15
- if (maxWidth && width > maxWidth) {
16
- height = Math.round((height * maxWidth) / width);
17
- width = maxWidth;
18
- }
19
- if (maxHeight && height > maxHeight) {
20
- width = Math.round((width * maxHeight) / height);
21
- height = maxHeight;
22
- }
23
-
16
+ const bitmap = await createImageBitmap(blob);
17
+ const { width, height } = computeTargetSize(
18
+ bitmap.width,
19
+ bitmap.height,
20
+ maxWidth,
21
+ maxHeight,
22
+ );
24
23
  const canvas = new OffscreenCanvas(width, height);
25
24
  const ctx = canvas.getContext("2d");
26
25
  if (!ctx) throw new Error("OffscreenCanvas 2D context unavailable");
27
-
28
26
  ctx.drawImage(bitmap, 0, 0, width, height);
29
27
  bitmap.close();
30
-
31
28
  const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });
32
- self.postMessage({ id, success: true, blob: outputBlob, width, height });
29
+ self.postMessage({ success: true, blob: outputBlob, width, height });
33
30
  } catch (err) {
34
- self.postMessage({ id, success: false, error: err?.message || String(err) });
31
+ self.postMessage({ success: false, error: err?.message || String(err) });
35
32
  }
36
33
  };
37
- `;async function A(e,t,f,r,i,n){if(typeof Worker>"u"||typeof OffscreenCanvas>"u")return b(e,t,f,r,i,n);let s=null;try{let o=new Blob([ae],{type:"application/javascript"});s=URL.createObjectURL(o);let a=new Worker(s),d=a;return await new Promise((c,u)=>{let g=Math.random().toString(36).slice(2),p=()=>{if(d)d.terminate(),d=null;if(s)URL.revokeObjectURL(s),s=null};if(n){if(n.aborted){p(),u(new DOMException("Compression aborted","AbortError"));return}n.addEventListener("abort",()=>{p(),u(new DOMException("Compression aborted","AbortError"))},{once:!0})}a.onmessage=(h)=>{if(h.data.id!==g)return;if(p(),h.data.success)c({blob:h.data.blob,width:h.data.width,height:h.data.height});else u(Error(h.data.error||"Worker compression failed"))},a.onerror=(h)=>{p(),u(Error(h.message||"Worker execution failed"))},a.postMessage({id:g,blob:e,maxWidth:t,maxHeight:f,quality:r,mimeType:i})})}catch{return b(e,t,f,r,i,n)}}async function X(e,t={}){if(typeof window>"u"&&typeof self>"u")return e;let f=e.type==="image/webp"||e.type==="image/png"||e instanceof File&&/\.(png|webp)$/i.test(e.name)?"image/webp":"image/jpeg",{maxSizeMB:r=Number.POSITIVE_INFINITY,maxWidth:i,maxHeight:n,quality:s=0.85,mimeType:o=f,preserveMetadata:a=!0,useWebWorker:d=!0,strict:c,signal:u,onProgress:g}=t;if(u?.aborted)throw new DOMException("Compression aborted","AbortError");let p=e.type||(e instanceof File&&/\.(jpe?g)$/i.test(e.name)?"image/jpeg":e instanceof File&&/\.webp$/i.test(e.name)?"image/webp":void 0),h=!p||p===o,x=r*1024*1024;if(s>=1&&(!r||!Number.isFinite(x))&&!i&&!n){if(o==="image/webp")return console.warn("[imagepressor] Warning: WebP quality is set to 1.0 (100%) without a maxSizeMB ceiling. In browsers, WebP quality 1.0 triggers lossless mode (VP8L), which can significantly inflate photographic image file sizes (+45% or more). Returning original image to prevent file size increase."),g?.(100,"Completed (original image preserved to prevent WebP 100% inflation)"),e;if(o==="image/jpeg")return console.warn("[imagepressor] Warning: JPEG quality is set to 1.0 (100%) without a maxSizeMB ceiling or resizing. Returning original image to preserve full fidelity and prevent re-compression generation loss."),g?.(100,"Completed (original image preserved to prevent JPEG re-compression)"),e}if(Number.isFinite(x)&&e.size<=x&&!i&&!n&&(!e.type||e.type===o)&&s>=1)return e;g?.(10,"Extracting metadata");let w=[],T=e.type==="image/jpeg"||e.type==="image/webp"||e instanceof File&&/\.(jpe?g|webp)$/i.test(e.name)||!e.type;if(a&&T){try{w=await U(e)}catch{}if(w.length===0)console.warn("[imagepressor] Warning: Image does not contain EXIF metadata or Display P3 ICC profile to preserve.")}if(u?.aborted)throw new DOMException("Compression aborted","AbortError");g?.(30,"Compressing pixels");let R=d?A:b,l=await R(e,i,n,s,o,u);if(Number.isFinite(x)&&l.blob.size>x){g?.(65,"Optimizing file size");let M=Math.sqrt(x/l.blob.size)*0.95,P=Math.max(800,Math.round(l.width*Math.min(0.85,M))),N=Math.max(0.65,s*0.85);l=await R(l.blob,P,void 0,N,o,u)}if(u?.aborted)throw new DOMException("Compression aborted","AbortError");g?.(85,"Preserving metadata");let m=l.blob;if(w.length>0){if(o==="image/jpeg")m=await I(m,w);else if(o==="image/webp")m=await E(m,w,l.width,l.height)}let G=c!==void 0?c:h;if(m.size>=e.size&&G&&!i&&!n&&(!Number.isFinite(x)||x>=e.size/1048576))return console.warn(`[imagepressor] Notice: Compression to ${o} resulted in a larger file (${(m.size/1048576).toFixed(2)} MB vs original ${(e.size/1048576).toFixed(2)} MB). Returning original file to prevent file size expansion.`),e;if(m.size>=e.size&&!i&&!n&&!h)console.warn(`[imagepressor] Notice: Format conversion from ${p||"original"} to ${o} increased file size from ${(e.size/1048576).toFixed(2)} MB to ${(m.size/1048576).toFixed(2)} MB. Modern formats like WebP are ~30% more efficient than legacy JPEG. To prevent expansion, set strict: true or specify maxSizeMB.`);if(g?.(100,"Complete"),e instanceof File){let M=o==="image/webp"?"webp":"jpg",P=e.name.replace(/\.[^/.]+$/,"")||"photo";return new File([m],`${P}.${M}`,{type:o,lastModified:e.lastModified})}return m}var se=X;
34
+ `;async function z(e,t,r,n,a,i){if(w(i),typeof Worker>"u"||typeof OffscreenCanvas>"u")return C(e,t,r,n,a,i);let c=null;try{let o=new Blob([Ue],{type:"application/javascript"});c=URL.createObjectURL(o)}catch{return C(e,t,r,n,a,i)}let u;try{u=new Worker(c)}catch{return URL.revokeObjectURL(c),c=null,C(e,t,r,n,a,i)}return new Promise((o,s)=>{function f(){if(u.terminate(),i?.removeEventListener("abort",p),c)URL.revokeObjectURL(c),c=null}let p=()=>{f(),s(new DOMException("Compression aborted","AbortError"))};if(i){if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0})}u.onmessage=(d)=>{if(f(),d.data.success)o({blob:d.data.blob,width:d.data.width,height:d.data.height});else s(Error(d.data.error||"Worker compression failed"))},u.onerror=(d)=>{f(),s(Error(d.message||"Worker execution failed"))},u.postMessage({blob:e,maxWidth:t,maxHeight:r,quality:n,mimeType:a})})}var Y={extract:{progress:10,stage:"Extracting metadata"},compress:{progress:30,stage:"Compressing pixels"},optimize:{progress:65,stage:"Optimizing file size"},preserve:{progress:85,stage:"Preserving metadata"},complete:{progress:100,stage:"Complete"}};function Ee(e,t,r){if(t==="image/webp")return console.warn("[imagepressor] Warning: WebP quality is set to 1.0 (100%) without a maxSizeMB ceiling. Browsers may encode WebP at quality 1.0 losslessly (VP8L), which can significantly inflate photographic image file sizes (+45% or more). Returning original image to prevent file size increase."),r?.(100,"Completed (original image preserved to prevent WebP 100% inflation)"),e;if(t==="image/jpeg")return console.warn("[imagepressor] Warning: JPEG quality is set to 1.0 (100%) without a maxSizeMB ceiling or resizing. Returning original image to preserve full fidelity and prevent re-compression generation loss."),r?.(100,"Completed (original image preserved to prevent JPEG re-compression)"),e;return null}async function ee(e,t={}){if(!(typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u")&&!(typeof document<"u"&&typeof Image<"u"))return e;let a=M(e),i=a==="image/webp"||a==="image/png"?"image/webp":"image/jpeg",{maxSizeMB:c=Number.POSITIVE_INFINITY,maxWidth:u,maxHeight:o,quality:s=0.85,mimeType:f=i,preserveMetadata:p=!0,useWebWorker:d=!0,strict:l,signal:m,onProgress:g}=t,b=(h)=>g?.(Y[h].progress,Y[h].stage);w(m);let U=!a||a===f,I=c*1024*1024;if(s>=1&&(!c||!Number.isFinite(I))&&!u&&!o){let h=Ee(e,f,g);if(h)return h}if(Number.isFinite(I)&&e.size<=I&&!u&&!o&&(!a||a===f)&&s>=1)return e;b("extract");let E=[],te=await j(e);if(p&&te){try{E=await L(e)}catch{}if(E.length===0)console.warn("[imagepressor] Warning: Image does not contain EXIF metadata or an ICC color profile to preserve.")}w(m),b("compress");let N=d?z:C,y=await N(e,u,o,s,f,m);if(Number.isFinite(I)&&y.blob.size>I){b("optimize");let h=Math.sqrt(I/y.blob.size)*0.95,S=Math.max(800,Math.round(y.width*Math.min(0.85,h))),ae=Math.max(0.65,s*0.85);y=await N(y.blob,S,void 0,ae,f,m)}w(m),b("preserve");let x=y.blob;if(E.length>0)try{if(f==="image/jpeg")x=await W(x,E);else if(f==="image/webp")x=await k(x,E,y.width,y.height)}catch(h){console.warn("[imagepressor] Warning: Could not preserve metadata on the compressed image; returning pixels without metadata.",h)}let ne=l!==void 0?l:U,re=Number.isFinite(I);if(x.size>=e.size&&ne&&!u&&!o&&!re)return console.warn(`[imagepressor] Notice: Compression to ${f} resulted in a larger file (${(x.size/1048576).toFixed(2)} MB vs original ${(e.size/1048576).toFixed(2)} MB). Returning original file to prevent file size expansion.`),e;if(x.size>=e.size&&!u&&!o&&!U)console.warn(`[imagepressor] Notice: Format conversion from ${a||"original"} to ${f} increased file size from ${(e.size/1048576).toFixed(2)} MB to ${(x.size/1048576).toFixed(2)} MB. Modern formats like WebP are ~30% more efficient than legacy JPEG. To prevent expansion, set strict: true or specify maxSizeMB.`);if(b("complete"),e instanceof File){let h=f==="image/webp"?"webp":"jpg",S=e.name.replace(/\.[^/.]+$/,"")||"photo";return new File([x],`${S}.${h}`,{type:f,lastModified:e.lastModified})}return x}var Fe=ee;
38
35
 
39
- //# debugId=F692EECE5C71E06764756E2164756E21
36
+ //# debugId=977F7AECF7E5160B64756E2164756E21
37
+ //# sourceMappingURL=index.cjs.map