UNPKG

@awesome-compressor/browser-compress-image

Version:

🚀 A powerful, lightweight browser image compression library with TypeScript support. Compress JPEG, PNG, GIF images with multiple output formats (Blob, File, Base64, ArrayBuffer) and zero dependencies.

1 lines 5.22 kB
import{__esmMin as e,__export as t}from"./chunk-BFNP_Rck.js";import{init_logger as n,logger_default as r}from"./logger-C7b05YKe.js";var i={};t(i,{configureWasmLoading:()=>a,default:()=>g,diagnoseJsquashAvailability:()=>d,downloadWasmFiles:()=>f,ensureWasmLoaded:()=>u,isWebAssemblySupported:()=>o});function a(e){y={...y,...e}}function o(){return typeof WebAssembly<`u`&&typeof WebAssembly.instantiate==`function`}function s(){return typeof window<`u`&&typeof document<`u`}function c(){try{return globalThis.__vitest__!==void 0}catch{return!1}}async function l(e){if(!s())throw Error(`JSQuash not supported in Node.js environment for ${e}`);try{let t=`https://unpkg.com/@jsquash/${e}@latest?module`;return await import(t)}catch(t){throw r.error(`CDN import failed for ${e}:`,t),t}}async function u(e){if(v.has(e))return v.get(e);let t=(async()=>{try{if(y.useLocal)try{await p(e);return}catch(t){r.warn(`Local WASM loading failed for ${e}, falling back to CDN:`,t)}await l(e)}catch(t){throw v.delete(e),t instanceof Error&&t.message.includes(`magic word`)?(r.error(`WASM loading failed for ${e}: Invalid WASM file or CDN issue`,t),Error(`Failed to load ${e} WASM module. This might be due to network issues or CDN problems.`)):(r.error(`Failed to initialize WASM for ${e}:`,t),Error(`Failed to initialize ${e} support: ${t instanceof Error?t.message:String(t)}`))}})();return v.set(e,t),t}async function d(){let e={wasmSupported:o(),availableFormats:[],errors:[]};if(!e.wasmSupported)return e;let t=[`avif`,`jpeg`,`jxl`,`png`,`webp`];for(let n of t)try{await u(n),e.availableFormats.push(n)}catch(t){e.errors.push({format:n,error:t instanceof Error?t.message:String(t)})}return e}async function f(e=[`avif`,`jpeg`,`jxl`,`png`,`webp`],t=`/wasm/`){let n=[];for(let t of e)try{let e=`@jsquash/${t}`,i=b[t],a=`https://unpkg.com/${e}/codec/${i}`;r.log(`正在下载 ${t} WASM 文件: ${a}`);let o=await fetch(a);if(!o.ok)throw Error(`Failed to fetch: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),c=new Uint8Array(s.slice(0,4));if(c[0]!==0||c[1]!==97||c[2]!==115||c[3]!==109)throw Error(`Invalid WASM file format`);let l=new Blob([s],{type:`application/wasm`}),u=URL.createObjectURL(l),d=document.createElement(`a`);d.href=u,d.download=`${t}_${i}`,d.style.display=`none`,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u),n.push({format:t,success:!0}),r.log(`✅ ${t} WASM 文件下载成功`)}catch(e){let i=e instanceof Error?e.message:String(e);n.push({format:t,success:!1,error:i}),r.error(`❌ ${t} WASM 文件下载失败:`,i)}return n}async function p(e){if(`serviceWorker`in navigator){let t=`jsquash-wasm-cache`,n=b[e],i=`${y.baseUrl}${n}`;try{let n=await caches.open(t),a=await n.match(i);if(a){r.log(`从缓存加载 ${e} WASM 文件`);return}}catch(e){r.warn(`Cache API not available:`,e)}}let t=`${y.baseUrl}${b[e]}`,n=await fetch(t);if(!n.ok)throw Error(`Local WASM file not found: ${t}`);let i=await n.arrayBuffer(),a=new Uint8Array(i.slice(0,4));if(a[0]!==0||a[1]!==97||a[2]!==115||a[3]!==109)throw Error(`Invalid local WASM file: ${t}`);r.log(`✅ 本地 ${e} WASM 文件验证成功`)}function m(e){return e.includes(`png`)?`png`:e.includes(`webp`)?`webp`:e.includes(`avif`)?`avif`:e.includes(`jxl`)?`jxl`:`jpeg`}async function h(e){return new Promise((t,n)=>{let r=new Image,i=document.createElement(`canvas`),a=i.getContext(`2d`);r.onload=()=>{i.width=r.width,i.height=r.height,a.drawImage(r,0,0);let e=a.getImageData(0,0,i.width,i.height);t(e)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}async function g(e,t){let{quality:n,targetWidth:i,targetHeight:a,maxWidth:o,maxHeight:d}=t;if(!s())return c()||r.warn(`JSQuash: non-browser environment detected; skipping WASM compression and returning original file`),e;let f=m(e.type);try{await u(f);let t=await l(f),r=await h(e),s=r;(i||a||o||d)&&(s=await _(r,i||o,a||d));let c;switch(f){case`avif`:c=await t.encode(s,{quality:Math.round(n*100)});break;case`jpeg`:c=await t.encode(s,{quality:Math.round(n*100)});break;case`jxl`:c=await t.encode(s,{quality:Math.round(n*100)});break;case`png`:c=await t.encode(s);break;case`webp`:c=await t.encode(s,{quality:Math.round(n*100)});break;default:throw Error(`Unsupported output format: ${f}`)}let p=`image/${f===`jxl`?`jxl`:f}`,m=new Blob([c],{type:p});return m.size>=e.size*.98?e:m}catch(t){return r.error(`JSQuash compression failed:`,t),e}}async function _(e,t,n){if(!t&&!n)return e;let r=document.createElement(`canvas`),i=r.getContext(`2d`),a=e.width,o=e.height,s=t||a,c=n||o;t&&!n?c=Math.round(o*t/a):n&&!t&&(s=Math.round(a*n/o));let l=document.createElement(`canvas`),u=l.getContext(`2d`);return l.width=a,l.height=o,u.putImageData(e,0,0),r.width=s,r.height=c,i.drawImage(l,0,0,s,c),i.getImageData(0,0,s,c)}var v,y,b,x=e(()=>{n(),v=new Map,y={baseUrl:`/wasm/`,useLocal:!1},b={avif:`squoosh_avif_bg.wasm`,jpeg:`mozjpeg_bg.wasm`,jxl:`jxl_bg.wasm`,png:`squoosh_png_bg.wasm`,webp:`squoosh_webp_bg.wasm`}});export{g as compressWithJsquash,i as compressWithJsquash_exports,a as configureWasmLoading,d as diagnoseJsquashAvailability,f as downloadWasmFiles,u as ensureWasmLoaded,x as init_compressWithJsquash,o as isWebAssemblySupported};