@blazediff/matcher 2.0.8 → 3.0.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 CHANGED
@@ -124,46 +124,22 @@ Main function for snapshot comparison.
124
124
  <td>Force update snapshots (like running with -u flag)</td>
125
125
  </tr>
126
126
  <tr>
127
- <td><code>threshold</code></td>
128
- <td>number</td>
129
- <td>0.1</td>
130
- <td>Color difference threshold for core/core-native methods (0-1)</td>
131
- </tr>
132
- <tr>
133
- <td><code>antialiasing</code></td>
134
- <td>boolean</td>
135
- <td>false</td>
136
- <td>Enable anti-aliasing detection (core-native method)</td>
137
- </tr>
138
- <tr>
139
- <td><code>includeAA</code></td>
140
- <td>boolean</td>
141
- <td>false</td>
142
- <td>Include anti-aliased pixels in diff count (core method)</td>
143
- </tr>
144
- <tr>
145
- <td><code>windowSize</code></td>
146
- <td>number</td>
147
- <td>11</td>
148
- <td>Window size for SSIM variants</td>
149
- </tr>
150
- <tr>
151
- <td><code>k1</code></td>
152
- <td>number</td>
153
- <td>0.01</td>
154
- <td>k1 constant for SSIM</td>
127
+ <td><code>diff</code></td>
128
+ <td>Omit&lt;DiffOptions, "output"&gt;</td>
129
+ <td>-</td>
130
+ <td><code>threshold</code>, <code>antialiasing</code> (default true), <code>metric</code>, <code>mask</code>, <code>window</code> and <code>render</code>. See <code>@blazediff/core</code>. Used by core, core-wasm and core-native.</td>
155
131
  </tr>
156
132
  <tr>
157
- <td><code>k2</code></td>
158
- <td>number</td>
159
- <td>0.03</td>
160
- <td>k2 constant for SSIM</td>
133
+ <td><code>ssim</code></td>
134
+ <td>Omit&lt;SsimOptions, "output"&gt;</td>
135
+ <td>-</td>
136
+ <td><code>windowSize</code>, <code>k1</code>, <code>k2</code>, <code>bitDepth</code>, <code>msSsim</code> and <code>hitchhikers</code>. See <code>@blazediff/ssim</code>. Used by ssim, msssim and hitchhikers-ssim.</td>
161
137
  </tr>
162
138
  <tr>
163
- <td><code>downsample</code></td>
164
- <td>0 | 1</td>
165
- <td>0</td>
166
- <td>Downsample factor for GMSD</td>
139
+ <td><code>gmsd</code></td>
140
+ <td>Omit&lt;GmsdOptions, "output"&gt;</td>
141
+ <td>-</td>
142
+ <td><code>downsample</code> and <code>c</code>. See <code>@blazediff/gmsd</code>. Used by gmsd.</td>
167
143
  </tr>
168
144
  <tr>
169
145
  <td><code>runInWorker</code></td>
@@ -233,6 +209,7 @@ Main function for snapshot comparison.
233
209
  ```typescript
234
210
  type ImageInput =
235
211
  | string // File path
212
+ | Uint8Array // Encoded PNG bytes (a Buffer works)
236
213
  | {
237
214
  data: Uint8Array | Uint8ClampedArray | Buffer;
238
215
  width: number;
@@ -244,10 +221,14 @@ type ImageInput =
244
221
 
245
222
  ### `core-native`
246
223
  Rust-native comparison via N-API bindings. **Fastest method** with native performance.
247
- - **Input**: File paths only
224
+ - **Input**: File paths, PNG buffers or raw RGBA images
248
225
  - **Algorithm**: YIQ color space with block-based optimization
249
226
  - **Best for**: Production testing, large images
250
227
 
228
+ ### `core-wasm`
229
+ The `core-native` algorithm compiled to WebAssembly. Same results, no native binaries.
230
+ - **Input**: File paths or buffers
231
+
251
232
  ### `core`
252
233
  Pixel-by-pixel comparison in JavaScript. Pure JS implementation with no native dependencies.
253
234
  - **Input**: File paths or buffers
@@ -317,6 +298,7 @@ const result = await getOrCreateSnapshot(
317
298
  method: 'core',
318
299
  failureThreshold: 0.1,
319
300
  failureThresholdType: 'percent', // Allow 0.1% difference
301
+ diff: { threshold: 0.05 }, // Stricter per-pixel color threshold
320
302
  },
321
303
  { testPath: __filename, testName: 'test name' }
322
304
  );
@@ -325,7 +307,7 @@ const result = await getOrCreateSnapshot(
325
307
  ### Different Comparison Methods
326
308
 
327
309
  ```typescript
328
- // Fastest - Rust native (file paths only)
310
+ // Fastest - Rust native (paths, PNG buffers or raw images)
329
311
  await getOrCreateSnapshot(imagePath, { method: 'core-native' }, context);
330
312
 
331
313
  // Pure JavaScript
package/dist/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { Buffer as Buffer$1 } from 'node:buffer';
2
+ import { DiffOptions } from '@blazediff/core';
3
+ import { GmsdOptions } from '@blazediff/gmsd';
4
+ import { SsimOptions } from '@blazediff/ssim';
2
5
 
3
6
  /**
4
7
  * Comparison methods available in blazediff
@@ -57,42 +60,12 @@ interface MatcherOptions {
57
60
  * @default '--update'
58
61
  */
59
62
  updateCommand?: string;
60
- /**
61
- * Color difference threshold for core/core-native methods (0-1)
62
- * Lower = more strict
63
- * @default 0.1
64
- */
65
- threshold?: number;
66
- /**
67
- * Enable anti-aliasing detection (core-native method)
68
- * @default false
69
- */
70
- antialiasing?: boolean;
71
- /**
72
- * Include anti-aliased pixels in diff count (core method)
73
- * @default false
74
- */
75
- includeAA?: boolean;
76
- /**
77
- * Window size for SSIM variants
78
- * @default 11
79
- */
80
- windowSize?: number;
81
- /**
82
- * k1 constant for SSIM
83
- * @default 0.01
84
- */
85
- k1?: number;
86
- /**
87
- * k2 constant for SSIM
88
- * @default 0.03
89
- */
90
- k2?: number;
91
- /**
92
- * Downsample factor for GMSD (0 or 1)
93
- * @default 0
94
- */
95
- downsample?: 0 | 1;
63
+ /** Options for the core, core-wasm and core-native methods. The matcher manages `output`. */
64
+ diff?: Omit<DiffOptions, "output">;
65
+ /** Options for the ssim, msssim and hitchhikers-ssim methods. The matcher manages `output`. */
66
+ ssim?: Omit<SsimOptions, "output">;
67
+ /** Options for the gmsd method. The matcher manages `output`. */
68
+ gmsd?: Omit<GmsdOptions, "output">;
96
69
  /**
97
70
  * Run image I/O and comparison in a worker thread
98
71
  * Worker threads provide better performance by avoiding V8 heap contention
@@ -151,10 +124,6 @@ interface RunComparisonResult {
151
124
  /** Diff visualization output buffer */
152
125
  diffOutput?: Uint8Array;
153
126
  }
154
- /**
155
- * Validate that the comparison method supports the given input type
156
- */
157
- declare function validateMethodSupportsInput(method: ComparisonMethod, input: ImageInput): void;
158
127
  /**
159
128
  * Run comparison using the specified method
160
129
  */
@@ -231,4 +200,4 @@ declare function compareImages(received: ImageInput, baseline: ImageInput, optio
231
200
 
232
201
  declare function terminateWorker(): Promise<number>;
233
202
 
234
- export { type ComparisonMethod, type ComparisonResult, type FormatOptions, type ImageData, type ImageInput, type MatcherOptions, type TestContext, compareImages, fileExists, formatMessage as formatReport, getOrCreateSnapshot, isFilePath, isImageBuffer, isImageData, isRawPngBuffer, loadPNG, normalizeImageInput, runComparison, savePNG, saveRawPNGBuffer, terminateWorker, validateMethodSupportsInput };
203
+ export { type ComparisonMethod, type ComparisonResult, type FormatOptions, type ImageData, type ImageInput, type MatcherOptions, type TestContext, compareImages, fileExists, formatMessage as formatReport, getOrCreateSnapshot, isFilePath, isImageBuffer, isImageData, isRawPngBuffer, loadPNG, normalizeImageInput, runComparison, savePNG, saveRawPNGBuffer, terminateWorker };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var fs=require('fs'),path=require('path'),codecPngjs=require('@blazediff/codec-pngjs'),core=require('@blazediff/core'),coreNative=require('@blazediff/core-native'),promises=require('fs/promises'),module$1=require('module'),gmsd=require('@blazediff/gmsd'),ssim=require('@blazediff/ssim'),hitchhikersSsim=require('@blazediff/ssim/hitchhikers-ssim'),msssim=require('@blazediff/ssim/msssim'),s=require('picocolors'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var s__default=/*#__PURE__*/_interopDefault(s);var ye=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:true});};var xe,I,u=b(()=>{xe=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,I=xe();});var ce={};me(ce,{ensureDir:()=>te,fileExists:()=>v,isFilePath:()=>C,isImageBuffer:()=>de,isImageData:()=>P,isRawPngBuffer:()=>W,loadPNG:()=>E,normalizeImageInput:()=>S,savePNG:()=>y,saveRawPNGBuffer:()=>R});function C(e){return typeof e=="string"}function W(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function de(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}function P(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function E(e){if(!fs.existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function y(e,t,r,o){let n=path.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true}),await codecPngjs.codecPngjs.write({data:t instanceof Uint8Array?t:new Uint8Array(t),width:r,height:o},e);}function R(e,t){let r=path.dirname(e);fs.existsSync(r)||fs.mkdirSync(r,{recursive:true}),fs.writeFileSync(e,t);}async function S(e){if(C(e))return E(e);if(W(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function v(e){return fs.existsSync(e)}function te(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:true});}var O=b(()=>{u();});function z(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {diffCount:i,diffPercentage:100};let f=r?new Uint8Array(i*4):void 0,c=core.diff(e.data,t.data,f,n,a,{threshold:o.threshold??.1,includeAA:o.includeAA??false});return {diffCount:c,diffPercentage:c/i*100,diffOutput:f}}var re=b(()=>{u();});async function G(e,t,r,o){if(!C(e))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!C(t))throw new Error("Method 'core-native' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let n=await coreNative.compare(e,t,r,{threshold:o.threshold,antialiasing:o.antialiasing});if(n.match)return {diffCount:0,diffPercentage:0};if(n.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(n.reason==="pixel-diff")return {diffCount:n.diffCount,diffPercentage:n.diffPercentage};if(n.reason==="file-not-exists")throw new Error(`Image file not found: ${n.file}`);return {diffCount:0,diffPercentage:0}}var ae=b(()=>{u();O();});function ke(){return oe||(oe=import('@blazediff/core-wasm').then(async e=>{let t=Oe.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await promises.readFile(t)),e})),oe}async function F(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {diffCount:i,diffPercentage:100};let f=r?new Uint8Array(i*4):void 0,{diff:c}=await ke(),m=await c(e.data,t.data,n,a,f,{threshold:o.threshold??.1,includeAA:o.includeAA??false});return {diffCount:m,diffPercentage:m/i*100,diffOutput:f}}var Oe,oe,ne=b(()=>{u();Oe=module$1.createRequire(I);});function _(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {score:1};let f=r?new Uint8Array(i*4):void 0;return {score:gmsd.gmsd(e.data,t.data,f,n,a,{downsample:o.downsample}),diffOutput:f}}var ie=b(()=>{u();});function j(e,t,r,o,n){let{width:a,height:i}=e,f=a*i;if(e.width!==t.width||e.height!==t.height)return {score:0};let c=o?new Uint8Array(f*4):void 0,m={windowSize:n.windowSize,k1:n.k1,k2:n.k2},M;switch(r){case "ssim":M=ssim.ssim(e.data,t.data,c,a,i,m);break;case "msssim":M=msssim.msssim(e.data,t.data,c,a,i,m);break;case "hitchhikers-ssim":M=hitchhikersSsim.hitchhikersSSIM(e.data,t.data,c,a,i,m);break;default:throw new Error(`Unknown SSIM method: ${r}`)}return {score:M,diffOutput:c}}function k(e){return e==="ssim"||e==="msssim"||e==="hitchhikers-ssim"}var q=b(()=>{u();});var pe={};me(pe,{compareCore:()=>z,compareCoreNative:()=>G,compareCoreWasm:()=>F,compareGmsd:()=>_,compareSsim:()=>j,isSsimMethod:()=>k,runComparison:()=>$,validateMethodSupportsInput:()=>L});function L(e,t){if(e==="core-native"&&!C(t))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function $(e,t,r,o,n){if(L(r,e),L(r,t),r==="core-native"){let m=await G(e,t,n,o);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage}}let a=P(e)?e:await S(e),i=P(t)?t:await S(t),f=n!==void 0;if(k(r)){let m=j(a,i,r,f,o);return {score:m.score,diffOutput:m.diffOutput}}if(r==="gmsd"){let m=_(a,i,f,o);return {score:m.score,diffOutput:m.diffOutput}}if(r==="core-wasm"){let m=await F(a,i,f,o);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage,diffOutput:m.diffOutput}}let c=z(a,i,f,o);return {diffCount:c.diffCount,diffPercentage:c.diffPercentage,diffOutput:c.diffOutput}}var H=b(()=>{u();O();re();ae();ne();ie();q();re();ae();ne();ie();q();});u();H();O();u();var B={success:s__default.default.isColorSupported?"\u2714":"\u221A",error:s__default.default.isColorSupported?"\u2716":"\xD7",info:s__default.default.isColorSupported?"\u2139":"i",arrow:s__default.default.isColorSupported?"\u2514\u2500":"'-"},We=new Set(["ssim","msssim","hitchhikers-ssim"]);function A(e){return e.snapshotCreated?Ee(e.baselinePath):e.pass?Be():Ne(e)}function Ee(e){return [`${s__default.default.green(B.success)} ${s__default.default.green("New snapshot created")}`,` ${s__default.default.dim(B.arrow)} ${s__default.default.dim(e)}`].join(`
2
- `)}function Be(){return `${s__default.default.green(B.success)} ${s__default.default.green("Image matches snapshot")}`}function Ne(e){let{method:t,baselinePath:r,receivedPath:o,diffPath:n,diffCount:a=0,diffPercentage:i,score:f=0,threshold:c,thresholdType:m,updateCommand:M}=e,p=[`${s__default.default.red(B.error)} ${s__default.default.red(s__default.default.bold("Image snapshot mismatch"))}`,""],g=12;if(p.push(` ${s__default.default.dim("Method".padEnd(g))}${t}`),p.push(` ${s__default.default.dim("Baseline".padEnd(g))}${s__default.default.dim(r)}`),p.push(` ${s__default.default.dim("Received".padEnd(g))}${s__default.default.dim(o)}`),p.push(` ${s__default.default.dim("Diff".padEnd(g))}${s__default.default.dim(n)}`),p.push(""),We.has(t)){let T=((1-f)*100).toFixed(2);p.push(` ${s__default.default.dim("SSIM Score".padEnd(g))}${s__default.default.yellow(f.toFixed(4))} ${s__default.default.dim("(1.0 = identical)")}`),p.push(` ${s__default.default.dim("Difference".padEnd(g))}${s__default.default.yellow(`${T}%`)}`);}else if(t==="gmsd")p.push(` ${s__default.default.dim("GMSD Score".padEnd(g))}${s__default.default.yellow(f.toFixed(4))} ${s__default.default.dim("(0.0 = identical)")}`);else {let T=i?.toFixed(2)??"0.00";p.push(` ${s__default.default.dim("Difference".padEnd(g))}${s__default.default.yellow(a.toLocaleString())} pixels ${s__default.default.dim(`(${T}%)`)}`);}let K=m==="percent"?"%":"pixels";return p.push(` ${s__default.default.dim("Threshold".padEnd(g))}${c} ${K}`),p.push(""),p.push(` ${s__default.default.cyan(B.info)} ${s__default.default.cyan(`Run with ${M??"--update"} to update the snapshot`)}`),p.join(`
3
- `)}u();H();q();O();u();var x=null,ze=0,ge=false,D=new Map;function Ge(){let e=path.join(__dirname,"worker.js");if(fs.existsSync(e))return e;let t=path.join(__dirname,"../dist/worker.js");return fs.existsSync(t)?t:null}function Fe(){if(ge)return null;if(!x){let e=Ge();if(!e)return ge=true,null;x=new worker_threads.Worker(e),x.on("message",t=>{let r=D.get(t.id);r&&(D.delete(t.id),t.success?r.resolve(t.result):r.reject(new Error(t.error)));}),x.on("error",t=>{for(let r of D.values())r.reject(t);D.clear(),x=null;}),x.on("exit",t=>{if(t!==0){let r=new Error(`Worker exited with code ${t}`);for(let o of D.values())o.reject(r);D.clear();}x=null;});}return x}async function se(e,t){let r=Fe();if(!r){let{runComparison:o}=await Promise.resolve().then(()=>(H(),pe)),{loadPNG:n,normalizeImageInput:a}=await Promise.resolve().then(()=>(O(),ce));switch(e){case "normalize":return a(t.input);case "loadPNG":return n(t.filePath);case "compare":{let i=t;return o(i.received,i.baseline,i.method,i.options,i.diffOutputPath)}default:throw new Error(`Unknown request type: ${e}`)}}return new Promise((o,n)=>{let a=++ze;D.set(a,{resolve:o,reject:n});let i={id:a,type:e,payload:t};r.postMessage(i);})}function fe(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function we(e){let t=await se("normalize",{input:e});return fe(t)}async function Ie(e){let t=await se("loadPNG",{filePath:e});return fe(t)}function Ce(e,t,r,o,n){let a=fe(e);return se("compare",{received:a,baseline:t,method:r,options:o,diffOutputPath:n})}function _e(){if(x){let e=x;return x=null,e.terminate()}return Promise.resolve(0)}function Le(e){return e.testName.replace(/[^a-zA-Z0-9-_\s]/g,"").replace(/\s+/g,"-").toLowerCase()||"snapshot"}function He(e,t){let r=path.dirname(e.testPath),o=t.snapshotsDir??"__snapshots__",n=path.isAbsolute(o)?o:path.join(r,o),a=t.snapshotIdentifier??Le(e),i=t.method==="core-native"?"html":"png";return {snapshotDir:n,baselinePath:path.join(n,`${a}.png`),receivedPath:path.join(n,`${a}.received.png`),diffPath:path.join(n,`${a}.diff.${i}`)}}function Pe(e,t,r){let o=r.failureThreshold??0,n=r.failureThresholdType??"pixel";if(k(e)){let a=t.score??0;return n==="percent"?(1-a)*100<=o:a>=1-o/100}if(e==="gmsd"){let a=t.score??0;return n==="percent"?a*100<=o:a<=o/100}return n==="percent"?(t.diffPercentage??0)<=o:(t.diffCount??0)<=o}async function Xe(e,t,r){let o=He(r,t),{snapshotDir:n,baselinePath:a,receivedPath:i,diffPath:f}=o,c=W(e),m=c?e:null,M=t.runInWorker!==false,p=M?we:S,g=M?Ie:E,K=M?(w,l,V)=>Ce(w,l,t.method,t,V):(w,l,V)=>$(w,l,t.method,t,V);te(n);let T=v(a),N=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!T&&N!=="none"&&(N==="new"||N==="all")){if(m)R(a,m);else if(C(e)){let l=await g(e);await y(a,l.data,l.width,l.height);}else if(P(e))await y(a,e.data,e.width,e.height);else {let l=await p(e);await y(a,l.data,l.width,l.height);}return {pass:true,message:A({pass:true,method:t.method,snapshotCreated:true,baselinePath:a,receivedPath:i,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:a,snapshotStatus:"added"}}let h,d;t.method==="core-native"?(h=await $(e,a,t.method,t,f),d=e):(d=c?await p(e):e,h=await K(P(d)?d:await p(d),a,f));let Q=Pe(t.method,h,t);if(Q)return fs.existsSync(i)&&fs.unlinkSync(i),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:A({pass:Q,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,diffPath:f,diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,baselinePath:a,snapshotStatus:"matched"};if(N==="all"){if(m)R(a,m);else if(C(d)){let l=await g(d);await y(a,l.data,l.width,l.height);}else P(d)&&await y(a,d.data,d.width,d.height);return fs.existsSync(i)&&fs.unlinkSync(i),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:A({pass:true,method:t.method,snapshotCreated:true,baselinePath:a,receivedPath:i,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:a,snapshotStatus:"updated"}}if(m)R(i,m);else if(C(d)){let w=await g(d);await y(i,w.data,w.width,w.height);}else P(d)&&await y(i,d.data,d.width,d.height);if(h.diffOutput&&t.method!=="core-native"){let w=P(d)?d:await p(d);await y(f,h.diffOutput,w.width,w.height);}return {pass:false,message:A({pass:Q,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,diffPath:f,diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,baselinePath:a,receivedPath:i,diffPath:f,snapshotStatus:"failed"}}async function Ze(e,t,r){let o=await $(e,t,r.method,r),n=Pe(r.method,o,r);return {pass:n,message:n?"Images match.":`Images differ: ${o.diffCount??o.score} ${o.diffCount!==void 0?"pixels":"score"}`,diffCount:o.diffCount,diffPercentage:o.diffPercentage,score:o.score}}exports.compareImages=Ze;exports.fileExists=v;exports.formatReport=A;exports.getOrCreateSnapshot=Xe;exports.isFilePath=C;exports.isImageBuffer=de;exports.isImageData=P;exports.isRawPngBuffer=W;exports.loadPNG=E;exports.normalizeImageInput=S;exports.runComparison=$;exports.savePNG=y;exports.saveRawPNGBuffer=R;exports.terminateWorker=_e;exports.validateMethodSupportsInput=L;
1
+ 'use strict';var fs=require('fs'),path=require('path'),codecPngjs=require('@blazediff/codec-pngjs'),core=require('@blazediff/core'),coreNative=require('@blazediff/core-native'),promises=require('fs/promises'),module$1=require('module'),gmsd=require('@blazediff/gmsd'),ssim=require('@blazediff/ssim'),hitchhikersSsim=require('@blazediff/ssim/hitchhikers-ssim'),msssim=require('@blazediff/ssim/msssim'),i=require('picocolors'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var i__default=/*#__PURE__*/_interopDefault(i);var De=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var de=(e,t)=>{for(var r in t)De(e,r,{get:t[r],enumerable:true});};var be,I,m=y(()=>{be=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,I=be();});var he={};de(he,{ensureDir:()=>ae,fileExists:()=>F,isFilePath:()=>D,isImageBuffer:()=>ce,isImageData:()=>w,isRawPngBuffer:()=>A,loadPNG:()=>z,normalizeImageInput:()=>b,savePNG:()=>P,saveRawPNGBuffer:()=>S});function D(e){return typeof e=="string"}function A(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function ce(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}function w(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function z(e){if(!fs.existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function P(e,t,r,a){let n=path.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true}),await codecPngjs.codecPngjs.write({data:t instanceof Uint8Array?t:new Uint8Array(t),width:r,height:a},e);}function S(e,t){let r=path.dirname(e);fs.existsSync(r)||fs.mkdirSync(r,{recursive:true}),fs.writeFileSync(e,t);}async function b(e){if(D(e))return z(e);if(A(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function F(e){return fs.existsSync(e)}function ae(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:true});}var B=y(()=>{m();});function k(e,t){if(e.kind==="dimension-mismatch"){let{a:r,b:a}=e;return {diffCount:Math.max(r.width*r.height,a.width*a.height),diffPercentage:100}}return {diffCount:e.count,diffPercentage:e.percentage,diffOutput:t?.data}}function R({width:e,height:t}){return {data:new Uint8Array(e*t*4),width:e,height:t}}var O=y(()=>{m();});function j(e,t,r,a){let n=r?R(e):void 0;return k(core.diff(e,t,{...a.diff,output:n}),n)}var oe=y(()=>{m();O();});async function _(e,t,r,a){let n=await coreNative.diff(e,t,{...a.diff,output:r});if(n.kind==="io-error")throw new Error(n.path?`Image file not found or unreadable: ${n.path}. ${n.message}`:n.message);return k(n)}var ne=y(()=>{m();O();});function Ue(){return ie||(ie=import('@blazediff/core-wasm').then(async e=>{let t=Te.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await promises.readFile(t)),e})),ie}async function q(e,t,r,a){let n=r?R(e):void 0,{diff:o}=await Ue();return k(await o(e,t,{...a.diff,output:n}),n)}var Te,ie,se=y(()=>{m();O();Te=module$1.createRequire(I);});function L(e,t,r,a){let n=r?R(e):void 0,o=gmsd.gmsd(e,t,{...a.gmsd,output:n});return o.kind==="dimension-mismatch"?{score:1}:{score:o.score,diffOutput:n?.data}}var me=y(()=>{m();O();});function H(e,t,r,a,n){let o=a?R(e):void 0,s=le[r](e,t,{...n.ssim,output:o});return s.kind==="dimension-mismatch"?{score:0}:{score:s.score,diffOutput:o?.data}}function $(e){return e in le}var le,Z=y(()=>{m();O();le={ssim:ssim.ssim,msssim:msssim.msssim,"hitchhikers-ssim":hitchhikersSsim.hitchhikersSSIM};});var ge={};de(ge,{compareCore:()=>j,compareCoreNative:()=>_,compareCoreWasm:()=>q,compareGmsd:()=>L,compareSsim:()=>H,isSsimMethod:()=>$,runComparison:()=>T});async function T(e,t,r,a,n){if(r==="core-native"){let u=await _(e,t,n,a);return {diffCount:u.diffCount,diffPercentage:u.diffPercentage}}let o=w(e)?e:await b(e),s=w(t)?t:await b(t),f=n!==void 0;if($(r)){let u=H(o,s,r,f,a);return {score:u.score,diffOutput:u.diffOutput}}if(r==="gmsd"){let u=L(o,s,f,a);return {score:u.score,diffOutput:u.diffOutput}}if(r==="core-wasm"){let u=await q(o,s,f,a);return {diffCount:u.diffCount,diffPercentage:u.diffPercentage,diffOutput:u.diffOutput}}let x=j(o,s,f,a);return {diffCount:x.diffCount,diffPercentage:x.diffPercentage,diffOutput:x.diffOutput}}var J=y(()=>{m();B();oe();ne();se();me();Z();oe();ne();se();me();Z();});m();J();B();m();var E={success:i__default.default.isColorSupported?"\u2714":"\u221A",error:i__default.default.isColorSupported?"\u2716":"\xD7",info:i__default.default.isColorSupported?"\u2139":"i",arrow:i__default.default.isColorSupported?"\u2514\u2500":"'-"},ze=new Set(["ssim","msssim","hitchhikers-ssim"]);function U(e){return e.snapshotCreated?Be(e.baselinePath):e.pass?Ee():Ge(e)}function Be(e){return [`${i__default.default.green(E.success)} ${i__default.default.green("New snapshot created")}`,` ${i__default.default.dim(E.arrow)} ${i__default.default.dim(e)}`].join(`
2
+ `)}function Ee(){return `${i__default.default.green(E.success)} ${i__default.default.green("Image matches snapshot")}`}function Ge(e){let{method:t,baselinePath:r,receivedPath:a,diffPath:n,diffCount:o=0,diffPercentage:s,score:f=0,threshold:x,thresholdType:u,updateCommand:W}=e,p=[`${i__default.default.red(E.error)} ${i__default.default.red(i__default.default.bold("Image snapshot mismatch"))}`,""],l=12;if(p.push(` ${i__default.default.dim("Method".padEnd(l))}${t}`),p.push(` ${i__default.default.dim("Baseline".padEnd(l))}${i__default.default.dim(r)}`),p.push(` ${i__default.default.dim("Received".padEnd(l))}${i__default.default.dim(a)}`),p.push(` ${i__default.default.dim("Diff".padEnd(l))}${i__default.default.dim(n)}`),p.push(""),ze.has(t)){let N=((1-f)*100).toFixed(2);p.push(` ${i__default.default.dim("SSIM Score".padEnd(l))}${i__default.default.yellow(f.toFixed(4))} ${i__default.default.dim("(1.0 = identical)")}`),p.push(` ${i__default.default.dim("Difference".padEnd(l))}${i__default.default.yellow(`${N}%`)}`);}else if(t==="gmsd")p.push(` ${i__default.default.dim("GMSD Score".padEnd(l))}${i__default.default.yellow(f.toFixed(4))} ${i__default.default.dim("(0.0 = identical)")}`);else {let N=s?.toFixed(2)??"0.00";p.push(` ${i__default.default.dim("Difference".padEnd(l))}${i__default.default.yellow(o.toLocaleString())} pixels ${i__default.default.dim(`(${N}%)`)}`);}let X=u==="percent"?"%":"pixels";return p.push(` ${i__default.default.dim("Threshold".padEnd(l))}${x} ${X}`),p.push(""),p.push(` ${i__default.default.cyan(E.info)} ${i__default.default.cyan(`Run with ${W??"--update"} to update the snapshot`)}`),p.join(`
3
+ `)}m();J();Z();B();m();var C=null,je=0,Pe=false,M=new Map;function _e(){let e=path.join(__dirname,"worker.js");if(fs.existsSync(e))return e;let t=path.join(__dirname,"../dist/worker.js");return fs.existsSync(t)?t:null}function qe(){if(Pe)return null;if(!C){let e=_e();if(!e)return Pe=true,null;C=new worker_threads.Worker(e),C.on("message",t=>{let r=M.get(t.id);r&&(M.delete(t.id),t.success?r.resolve(t.result):r.reject(new Error(t.error)));}),C.on("error",t=>{for(let r of M.values())r.reject(t);M.clear(),C=null;}),C.on("exit",t=>{if(t!==0){let r=new Error(`Worker exited with code ${t}`);for(let a of M.values())a.reject(r);M.clear();}C=null;});}return C}async function fe(e,t){let r=qe();if(!r){let{runComparison:a}=await Promise.resolve().then(()=>(J(),ge)),{loadPNG:n,normalizeImageInput:o}=await Promise.resolve().then(()=>(B(),he));switch(e){case "normalize":return o(t.input);case "loadPNG":return n(t.filePath);case "compare":{let s=t;return a(s.received,s.baseline,s.method,s.options,s.diffOutputPath)}default:throw new Error(`Unknown request type: ${e}`)}}return new Promise((a,n)=>{let o=++je;M.set(o,{resolve:a,reject:n});let s={id:o,type:e,payload:t};r.postMessage(s);})}function ue(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function Ce(e){let t=await fe("normalize",{input:e});return ue(t)}async function ye(e){let t=await fe("loadPNG",{filePath:e});return ue(t)}function xe(e,t,r,a,n){let o=ue(e);return fe("compare",{received:o,baseline:t,method:r,options:a,diffOutputPath:n})}function Le(){if(C){let e=C;return C=null,e.terminate()}return Promise.resolve(0)}function Je(e){return e.testName.replace(/[^a-zA-Z0-9-_\s]/g,"").replace(/\s+/g,"-").toLowerCase()||"snapshot"}function Ke(e,t){let r=path.dirname(e.testPath),a=t.snapshotsDir??"__snapshots__",n=path.isAbsolute(a)?a:path.join(r,a),o=t.snapshotIdentifier??Je(e);return {snapshotDir:n,baselinePath:path.join(n,`${o}.png`),receivedPath:path.join(n,`${o}.received.png`),diffPath:path.join(n,`${o}.diff.png`)}}function Re(e,t,r){let a=r.failureThreshold??0,n=r.failureThresholdType??"pixel";if($(e)){let o=t.score??0;return n==="percent"?(1-o)*100<=a:o>=1-a/100}if(e==="gmsd"){let o=t.score??0;return n==="percent"?o*100<=a:o<=a/100}return n==="percent"?(t.diffPercentage??0)<=a:(t.diffCount??0)<=a}async function Qe(e,t,r){let a=Ke(r,t),{snapshotDir:n,baselinePath:o,receivedPath:s,diffPath:f}=a,x=A(e),u=x?e:null,W=t.runInWorker!==false,p=W?Ce:b,l=W?ye:z,X=W?(g,h,ee)=>xe(g,h,t.method,t,ee):(g,h,ee)=>T(g,h,t.method,t,ee);ae(n);let N=F(o),G=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!N&&G!=="none"&&(G==="new"||G==="all")){if(u)S(o,u);else if(D(e)){let h=await l(e);await P(o,h.data,h.width,h.height);}else if(w(e))await P(o,e.data,e.width,e.height);else {let h=await p(e);await P(o,h.data,h.width,h.height);}return {pass:true,message:U({pass:true,method:t.method,snapshotCreated:true,baselinePath:o,receivedPath:s,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:o,snapshotStatus:"added"}}let c,d;t.method==="core-native"?(c=await T(e,o,t.method,t,f),d=e):(d=x?await p(e):e,c=await X(w(d)?d:await p(d),o,f));let Y=Re(t.method,c,t);if(Y)return fs.existsSync(s)&&fs.unlinkSync(s),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:U({pass:Y,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:s,diffPath:f,diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,baselinePath:o,snapshotStatus:"matched"};if(G==="all"){if(u)S(o,u);else if(D(d)){let h=await l(d);await P(o,h.data,h.width,h.height);}else w(d)&&await P(o,d.data,d.width,d.height);return fs.existsSync(s)&&fs.unlinkSync(s),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:U({pass:true,method:t.method,snapshotCreated:true,baselinePath:o,receivedPath:s,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:o,snapshotStatus:"updated"}}if(u)S(s,u);else if(D(d)){let g=await l(d);await P(s,g.data,g.width,g.height);}else w(d)&&await P(s,d.data,d.width,d.height);if(c.diffOutput){let g=w(d)?d:await p(d);await P(f,c.diffOutput,g.width,g.height);}return {pass:false,message:U({pass:Y,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:s,diffPath:f,diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,baselinePath:o,receivedPath:s,diffPath:f,snapshotStatus:"failed"}}async function Ve(e,t,r){let a=await T(e,t,r.method,r),n=Re(r.method,a,r);return {pass:n,message:n?"Images match.":`Images differ: ${a.diffCount??a.score} ${a.diffCount!==void 0?"pixels":"score"}`,diffCount:a.diffCount,diffPercentage:a.diffPercentage,score:a.score}}exports.compareImages=Ve;exports.fileExists=F;exports.formatReport=U;exports.getOrCreateSnapshot=Qe;exports.isFilePath=D;exports.isImageBuffer=ce;exports.isImageData=w;exports.isRawPngBuffer=A;exports.loadPNG=z;exports.normalizeImageInput=b;exports.runComparison=T;exports.savePNG=P;exports.saveRawPNGBuffer=S;exports.terminateWorker=Le;
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import Me,{dirname,isAbsolute,join}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,unlinkSync}from'fs';import {codecPngjs}from'@blazediff/codec-pngjs';import {diff}from'@blazediff/core';import {compare}from'@blazediff/core-native';import {readFile}from'fs/promises';import {createRequire}from'module';import {gmsd}from'@blazediff/gmsd';import {ssim}from'@blazediff/ssim';import {hitchhikersSSIM}from'@blazediff/ssim/hitchhikers-ssim';import {msssim}from'@blazediff/ssim/msssim';import s from'picocolors';import {Worker}from'worker_threads';var xe=Object.defineProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var r in t)xe(e,r,{get:t[r],enumerable:true});};var De,Se,I,u=D(()=>{De=()=>fileURLToPath(import.meta.url),Se=()=>Me.dirname(De()),I=Se();});var ce={};ue(ce,{ensureDir:()=>re,fileExists:()=>z,isFilePath:()=>C,isImageBuffer:()=>pe,isImageData:()=>P,isRawPngBuffer:()=>E,loadPNG:()=>B,normalizeImageInput:()=>S,savePNG:()=>y,saveRawPNGBuffer:()=>O});function C(e){return typeof e=="string"}function E(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function pe(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}function P(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function B(e){if(!existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function y(e,t,r,o){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true}),await codecPngjs.write({data:t instanceof Uint8Array?t:new Uint8Array(t),width:r,height:o},e);}function O(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t);}async function S(e){if(C(e))return B(e);if(E(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function z(e){return existsSync(e)}function re(e){existsSync(e)||mkdirSync(e,{recursive:true});}var k=D(()=>{u();});function G(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {diffCount:i,diffPercentage:100};let f=r?new Uint8Array(i*4):void 0,p=diff(e.data,t.data,f,n,a,{threshold:o.threshold??.1,includeAA:o.includeAA??false});return {diffCount:p,diffPercentage:p/i*100,diffOutput:f}}var ae=D(()=>{u();});async function F(e,t,r,o){if(!C(e))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!C(t))throw new Error("Method 'core-native' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let n=await compare(e,t,r,{threshold:o.threshold,antialiasing:o.antialiasing});if(n.match)return {diffCount:0,diffPercentage:0};if(n.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(n.reason==="pixel-diff")return {diffCount:n.diffCount,diffPercentage:n.diffPercentage};if(n.reason==="file-not-exists")throw new Error(`Image file not found: ${n.file}`);return {diffCount:0,diffPercentage:0}}var oe=D(()=>{u();k();});function Ue(){return ne||(ne=import('@blazediff/core-wasm').then(async e=>{let t=Ae.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await readFile(t)),e})),ne}async function j(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {diffCount:i,diffPercentage:100};let f=r?new Uint8Array(i*4):void 0,{diff:p}=await Ue(),m=await p(e.data,t.data,n,a,f,{threshold:o.threshold??.1,includeAA:o.includeAA??false});return {diffCount:m,diffPercentage:m/i*100,diffOutput:f}}var Ae,ne,ie=D(()=>{u();Ae=createRequire(import.meta.url);});function _(e,t,r,o){let{width:n,height:a}=e,i=n*a;if(e.width!==t.width||e.height!==t.height)return {score:1};let f=r?new Uint8Array(i*4):void 0;return {score:gmsd(e.data,t.data,f,n,a,{downsample:o.downsample}),diffOutput:f}}var se=D(()=>{u();});function q(e,t,r,o,n){let{width:a,height:i}=e,f=a*i;if(e.width!==t.width||e.height!==t.height)return {score:0};let p=o?new Uint8Array(f*4):void 0,m={windowSize:n.windowSize,k1:n.k1,k2:n.k2},M;switch(r){case "ssim":M=ssim(e.data,t.data,p,a,i,m);break;case "msssim":M=msssim(e.data,t.data,p,a,i,m);break;case "hitchhikers-ssim":M=hitchhikersSSIM(e.data,t.data,p,a,i,m);break;default:throw new Error(`Unknown SSIM method: ${r}`)}return {score:M,diffOutput:p}}function $(e){return e==="ssim"||e==="msssim"||e==="hitchhikers-ssim"}var L=D(()=>{u();});var he={};ue(he,{compareCore:()=>G,compareCoreNative:()=>F,compareCoreWasm:()=>j,compareGmsd:()=>_,compareSsim:()=>q,isSsimMethod:()=>$,runComparison:()=>T,validateMethodSupportsInput:()=>H});function H(e,t){if(e==="core-native"&&!C(t))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function T(e,t,r,o,n){if(H(r,e),H(r,t),r==="core-native"){let m=await F(e,t,n,o);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage}}let a=P(e)?e:await S(e),i=P(t)?t:await S(t),f=n!==void 0;if($(r)){let m=q(a,i,r,f,o);return {score:m.score,diffOutput:m.diffOutput}}if(r==="gmsd"){let m=_(a,i,f,o);return {score:m.score,diffOutput:m.diffOutput}}if(r==="core-wasm"){let m=await j(a,i,f,o);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage,diffOutput:m.diffOutput}}let p=G(a,i,f,o);return {diffCount:p.diffCount,diffPercentage:p.diffPercentage,diffOutput:p.diffOutput}}var X=D(()=>{u();k();ae();oe();ie();se();L();ae();oe();ie();se();L();});u();X();k();u();var N={success:s.isColorSupported?"\u2714":"\u221A",error:s.isColorSupported?"\u2716":"\xD7",info:s.isColorSupported?"\u2139":"i",arrow:s.isColorSupported?"\u2514\u2500":"'-"},ve=new Set(["ssim","msssim","hitchhikers-ssim"]);function A(e){return e.snapshotCreated?ze(e.baselinePath):e.pass?Ge():Fe(e)}function ze(e){return [`${s.green(N.success)} ${s.green("New snapshot created")}`,` ${s.dim(N.arrow)} ${s.dim(e)}`].join(`
2
- `)}function Ge(){return `${s.green(N.success)} ${s.green("Image matches snapshot")}`}function Fe(e){let{method:t,baselinePath:r,receivedPath:o,diffPath:n,diffCount:a=0,diffPercentage:i,score:f=0,threshold:p,thresholdType:m,updateCommand:M}=e,c=[`${s.red(N.error)} ${s.red(s.bold("Image snapshot mismatch"))}`,""],g=12;if(c.push(` ${s.dim("Method".padEnd(g))}${t}`),c.push(` ${s.dim("Baseline".padEnd(g))}${s.dim(r)}`),c.push(` ${s.dim("Received".padEnd(g))}${s.dim(o)}`),c.push(` ${s.dim("Diff".padEnd(g))}${s.dim(n)}`),c.push(""),ve.has(t)){let U=((1-f)*100).toFixed(2);c.push(` ${s.dim("SSIM Score".padEnd(g))}${s.yellow(f.toFixed(4))} ${s.dim("(1.0 = identical)")}`),c.push(` ${s.dim("Difference".padEnd(g))}${s.yellow(`${U}%`)}`);}else if(t==="gmsd")c.push(` ${s.dim("GMSD Score".padEnd(g))}${s.yellow(f.toFixed(4))} ${s.dim("(0.0 = identical)")}`);else {let U=i?.toFixed(2)??"0.00";c.push(` ${s.dim("Difference".padEnd(g))}${s.yellow(a.toLocaleString())} pixels ${s.dim(`(${U}%)`)}`);}let Q=m==="percent"?"%":"pixels";return c.push(` ${s.dim("Threshold".padEnd(g))}${p} ${Q}`),c.push(""),c.push(` ${s.cyan(N.info)} ${s.cyan(`Run with ${M??"--update"} to update the snapshot`)}`),c.join(`
3
- `)}u();X();L();k();u();var x=null,_e=0,we=false,R=new Map;function qe(){let e=join(I,"worker.js");if(existsSync(e))return e;let t=join(I,"../dist/worker.js");return existsSync(t)?t:null}function Le(){if(we)return null;if(!x){let e=qe();if(!e)return we=true,null;x=new Worker(e),x.on("message",t=>{let r=R.get(t.id);r&&(R.delete(t.id),t.success?r.resolve(t.result):r.reject(new Error(t.error)));}),x.on("error",t=>{for(let r of R.values())r.reject(t);R.clear(),x=null;}),x.on("exit",t=>{if(t!==0){let r=new Error(`Worker exited with code ${t}`);for(let o of R.values())o.reject(r);R.clear();}x=null;});}return x}async function fe(e,t){let r=Le();if(!r){let{runComparison:o}=await Promise.resolve().then(()=>(X(),he)),{loadPNG:n,normalizeImageInput:a}=await Promise.resolve().then(()=>(k(),ce));switch(e){case "normalize":return a(t.input);case "loadPNG":return n(t.filePath);case "compare":{let i=t;return o(i.received,i.baseline,i.method,i.options,i.diffOutputPath)}default:throw new Error(`Unknown request type: ${e}`)}}return new Promise((o,n)=>{let a=++_e;R.set(a,{resolve:o,reject:n});let i={id:a,type:e,payload:t};r.postMessage(i);})}function me(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function Ie(e){let t=await fe("normalize",{input:e});return me(t)}async function Ce(e){let t=await fe("loadPNG",{filePath:e});return me(t)}function Pe(e,t,r,o,n){let a=me(e);return fe("compare",{received:a,baseline:t,method:r,options:o,diffOutputPath:n})}function He(){if(x){let e=x;return x=null,e.terminate()}return Promise.resolve(0)}function Je(e){return e.testName.replace(/[^a-zA-Z0-9-_\s]/g,"").replace(/\s+/g,"-").toLowerCase()||"snapshot"}function Ke(e,t){let r=dirname(e.testPath),o=t.snapshotsDir??"__snapshots__",n=isAbsolute(o)?o:join(r,o),a=t.snapshotIdentifier??Je(e),i=t.method==="core-native"?"html":"png";return {snapshotDir:n,baselinePath:join(n,`${a}.png`),receivedPath:join(n,`${a}.received.png`),diffPath:join(n,`${a}.diff.${i}`)}}function ye(e,t,r){let o=r.failureThreshold??0,n=r.failureThresholdType??"pixel";if($(e)){let a=t.score??0;return n==="percent"?(1-a)*100<=o:a>=1-o/100}if(e==="gmsd"){let a=t.score??0;return n==="percent"?a*100<=o:a<=o/100}return n==="percent"?(t.diffPercentage??0)<=o:(t.diffCount??0)<=o}async function Qe(e,t,r){let o=Ke(r,t),{snapshotDir:n,baselinePath:a,receivedPath:i,diffPath:f}=o,p=E(e),m=p?e:null,M=t.runInWorker!==false,c=M?Ie:S,g=M?Ce:B,Q=M?(w,l,Y)=>Pe(w,l,t.method,t,Y):(w,l,Y)=>T(w,l,t.method,t,Y);re(n);let U=z(a),v=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!U&&v!=="none"&&(v==="new"||v==="all")){if(m)O(a,m);else if(C(e)){let l=await g(e);await y(a,l.data,l.width,l.height);}else if(P(e))await y(a,e.data,e.width,e.height);else {let l=await c(e);await y(a,l.data,l.width,l.height);}return {pass:true,message:A({pass:true,method:t.method,snapshotCreated:true,baselinePath:a,receivedPath:i,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:a,snapshotStatus:"added"}}let h,d;t.method==="core-native"?(h=await T(e,a,t.method,t,f),d=e):(d=p?await c(e):e,h=await Q(P(d)?d:await c(d),a,f));let V=ye(t.method,h,t);if(V)return existsSync(i)&&unlinkSync(i),existsSync(f)&&unlinkSync(f),{pass:true,message:A({pass:V,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,diffPath:f,diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,baselinePath:a,snapshotStatus:"matched"};if(v==="all"){if(m)O(a,m);else if(C(d)){let l=await g(d);await y(a,l.data,l.width,l.height);}else P(d)&&await y(a,d.data,d.width,d.height);return existsSync(i)&&unlinkSync(i),existsSync(f)&&unlinkSync(f),{pass:true,message:A({pass:true,method:t.method,snapshotCreated:true,baselinePath:a,receivedPath:i,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:a,snapshotStatus:"updated"}}if(m)O(i,m);else if(C(d)){let w=await g(d);await y(i,w.data,w.width,w.height);}else P(d)&&await y(i,d.data,d.width,d.height);if(h.diffOutput&&t.method!=="core-native"){let w=P(d)?d:await c(d);await y(f,h.diffOutput,w.width,w.height);}return {pass:false,message:A({pass:V,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,diffPath:f,diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:h.diffCount,diffPercentage:h.diffPercentage,score:h.score,baselinePath:a,receivedPath:i,diffPath:f,snapshotStatus:"failed"}}async function Ve(e,t,r){let o=await T(e,t,r.method,r),n=ye(r.method,o,r);return {pass:n,message:n?"Images match.":`Images differ: ${o.diffCount??o.score} ${o.diffCount!==void 0?"pixels":"score"}`,diffCount:o.diffCount,diffPercentage:o.diffPercentage,score:o.score}}export{Ve as compareImages,z as fileExists,A as formatReport,Qe as getOrCreateSnapshot,C as isFilePath,pe as isImageBuffer,P as isImageData,E as isRawPngBuffer,B as loadPNG,S as normalizeImageInput,T as runComparison,y as savePNG,O as saveRawPNGBuffer,He as terminateWorker,H as validateMethodSupportsInput};
1
+ import Me,{dirname,isAbsolute,join}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,unlinkSync}from'fs';import {codecPngjs}from'@blazediff/codec-pngjs';import {diff as diff$1}from'@blazediff/core';import {diff}from'@blazediff/core-native';import {readFile}from'fs/promises';import {createRequire}from'module';import {gmsd}from'@blazediff/gmsd';import {ssim}from'@blazediff/ssim';import {hitchhikersSSIM}from'@blazediff/ssim/hitchhikers-ssim';import {msssim}from'@blazediff/ssim/msssim';import i from'picocolors';import {Worker}from'worker_threads';var be=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{for(var r in t)be(e,r,{get:t[r],enumerable:true});};var Se,Oe,l,m=x(()=>{Se=()=>fileURLToPath(import.meta.url),Oe=()=>Me.dirname(Se()),l=Oe();});var le={};pe(le,{ensureDir:()=>oe,fileExists:()=>j,isFilePath:()=>b,isImageBuffer:()=>he,isImageData:()=>P,isRawPngBuffer:()=>z,loadPNG:()=>B,normalizeImageInput:()=>M,savePNG:()=>C,saveRawPNGBuffer:()=>S});function b(e){return typeof e=="string"}function z(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function he(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}function P(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function B(e){if(!existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function C(e,t,r,a){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true}),await codecPngjs.write({data:t instanceof Uint8Array?t:new Uint8Array(t),width:r,height:a},e);}function S(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t);}async function M(e){if(b(e))return B(e);if(z(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function j(e){return existsSync(e)}function oe(e){existsSync(e)||mkdirSync(e,{recursive:true});}var E=x(()=>{m();});function O(e,t){if(e.kind==="dimension-mismatch"){let{a:r,b:a}=e;return {diffCount:Math.max(r.width*r.height,a.width*a.height),diffPercentage:100}}return {diffCount:e.count,diffPercentage:e.percentage,diffOutput:t?.data}}function R({width:e,height:t}){return {data:new Uint8Array(e*t*4),width:e,height:t}}var $=x(()=>{m();});function _(e,t,r,a){let n=r?R(e):void 0;return O(diff$1(e,t,{...a.diff,output:n}),n)}var ne=x(()=>{m();$();});async function q(e,t,r,a){let n=await diff(e,t,{...a.diff,output:r});if(n.kind==="io-error")throw new Error(n.path?`Image file not found or unreadable: ${n.path}. ${n.message}`:n.message);return O(n)}var ie=x(()=>{m();$();});function Ae(){return se||(se=import('@blazediff/core-wasm').then(async e=>{let t=ve.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await readFile(t)),e})),se}async function L(e,t,r,a){let n=r?R(e):void 0,{diff:o}=await Ae();return O(await o(e,t,{...a.diff,output:n}),n)}var ve,se,me=x(()=>{m();$();ve=createRequire(import.meta.url);});function H(e,t,r,a){let n=r?R(e):void 0,o=gmsd(e,t,{...a.gmsd,output:n});return o.kind==="dimension-mismatch"?{score:1}:{score:o.score,diffOutput:n?.data}}var fe=x(()=>{m();$();});function Z(e,t,r,a,n){let o=a?R(e):void 0,s=ge[r](e,t,{...n.ssim,output:o});return s.kind==="dimension-mismatch"?{score:0}:{score:s.score,diffOutput:o?.data}}function T(e){return e in ge}var ge,J=x(()=>{m();$();ge={ssim:ssim,msssim:msssim,"hitchhikers-ssim":hitchhikersSSIM};});var Ie={};pe(Ie,{compareCore:()=>_,compareCoreNative:()=>q,compareCoreWasm:()=>L,compareGmsd:()=>H,compareSsim:()=>Z,isSsimMethod:()=>T,runComparison:()=>W});async function W(e,t,r,a,n){if(r==="core-native"){let u=await q(e,t,n,a);return {diffCount:u.diffCount,diffPercentage:u.diffPercentage}}let o=P(e)?e:await M(e),s=P(t)?t:await M(t),f=n!==void 0;if(T(r)){let u=Z(o,s,r,f,a);return {score:u.score,diffOutput:u.diffOutput}}if(r==="gmsd"){let u=H(o,s,f,a);return {score:u.score,diffOutput:u.diffOutput}}if(r==="core-wasm"){let u=await L(o,s,f,a);return {diffCount:u.diffCount,diffPercentage:u.diffPercentage,diffOutput:u.diffOutput}}let D=_(o,s,f,a);return {diffCount:D.diffCount,diffPercentage:D.diffPercentage,diffOutput:D.diffOutput}}var K=x(()=>{m();E();ne();ie();me();fe();J();ne();ie();me();fe();J();});m();K();E();m();var G={success:i.isColorSupported?"\u2714":"\u221A",error:i.isColorSupported?"\u2716":"\xD7",info:i.isColorSupported?"\u2139":"i",arrow:i.isColorSupported?"\u2514\u2500":"'-"},Fe=new Set(["ssim","msssim","hitchhikers-ssim"]);function N(e){return e.snapshotCreated?je(e.baselinePath):e.pass?_e():qe(e)}function je(e){return [`${i.green(G.success)} ${i.green("New snapshot created")}`,` ${i.dim(G.arrow)} ${i.dim(e)}`].join(`
2
+ `)}function _e(){return `${i.green(G.success)} ${i.green("Image matches snapshot")}`}function qe(e){let{method:t,baselinePath:r,receivedPath:a,diffPath:n,diffCount:o=0,diffPercentage:s,score:f=0,threshold:D,thresholdType:u,updateCommand:U}=e,p=[`${i.red(G.error)} ${i.red(i.bold("Image snapshot mismatch"))}`,""],g=12;if(p.push(` ${i.dim("Method".padEnd(g))}${t}`),p.push(` ${i.dim("Baseline".padEnd(g))}${i.dim(r)}`),p.push(` ${i.dim("Received".padEnd(g))}${i.dim(a)}`),p.push(` ${i.dim("Diff".padEnd(g))}${i.dim(n)}`),p.push(""),Fe.has(t)){let v=((1-f)*100).toFixed(2);p.push(` ${i.dim("SSIM Score".padEnd(g))}${i.yellow(f.toFixed(4))} ${i.dim("(1.0 = identical)")}`),p.push(` ${i.dim("Difference".padEnd(g))}${i.yellow(`${v}%`)}`);}else if(t==="gmsd")p.push(` ${i.dim("GMSD Score".padEnd(g))}${i.yellow(f.toFixed(4))} ${i.dim("(0.0 = identical)")}`);else {let v=s?.toFixed(2)??"0.00";p.push(` ${i.dim("Difference".padEnd(g))}${i.yellow(o.toLocaleString())} pixels ${i.dim(`(${v}%)`)}`);}let Y=u==="percent"?"%":"pixels";return p.push(` ${i.dim("Threshold".padEnd(g))}${D} ${Y}`),p.push(""),p.push(` ${i.cyan(G.info)} ${i.cyan(`Run with ${U??"--update"} to update the snapshot`)}`),p.join(`
3
+ `)}m();K();J();E();m();var y=null,He=0,Ce=false,k=new Map;function Ze(){let e=join(l,"worker.js");if(existsSync(e))return e;let t=join(l,"../dist/worker.js");return existsSync(t)?t:null}function Je(){if(Ce)return null;if(!y){let e=Ze();if(!e)return Ce=true,null;y=new Worker(e),y.on("message",t=>{let r=k.get(t.id);r&&(k.delete(t.id),t.success?r.resolve(t.result):r.reject(new Error(t.error)));}),y.on("error",t=>{for(let r of k.values())r.reject(t);k.clear(),y=null;}),y.on("exit",t=>{if(t!==0){let r=new Error(`Worker exited with code ${t}`);for(let a of k.values())a.reject(r);k.clear();}y=null;});}return y}async function ue(e,t){let r=Je();if(!r){let{runComparison:a}=await Promise.resolve().then(()=>(K(),Ie)),{loadPNG:n,normalizeImageInput:o}=await Promise.resolve().then(()=>(E(),le));switch(e){case "normalize":return o(t.input);case "loadPNG":return n(t.filePath);case "compare":{let s=t;return a(s.received,s.baseline,s.method,s.options,s.diffOutputPath)}default:throw new Error(`Unknown request type: ${e}`)}}return new Promise((a,n)=>{let o=++He;k.set(o,{resolve:a,reject:n});let s={id:o,type:e,payload:t};r.postMessage(s);})}function de(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function ye(e){let t=await ue("normalize",{input:e});return de(t)}async function xe(e){let t=await ue("loadPNG",{filePath:e});return de(t)}function De(e,t,r,a,n){let o=de(e);return ue("compare",{received:o,baseline:t,method:r,options:a,diffOutputPath:n})}function Ke(){if(y){let e=y;return y=null,e.terminate()}return Promise.resolve(0)}function Xe(e){return e.testName.replace(/[^a-zA-Z0-9-_\s]/g,"").replace(/\s+/g,"-").toLowerCase()||"snapshot"}function Ye(e,t){let r=dirname(e.testPath),a=t.snapshotsDir??"__snapshots__",n=isAbsolute(a)?a:join(r,a),o=t.snapshotIdentifier??Xe(e);return {snapshotDir:n,baselinePath:join(n,`${o}.png`),receivedPath:join(n,`${o}.received.png`),diffPath:join(n,`${o}.diff.png`)}}function Re(e,t,r){let a=r.failureThreshold??0,n=r.failureThresholdType??"pixel";if(T(e)){let o=t.score??0;return n==="percent"?(1-o)*100<=a:o>=1-a/100}if(e==="gmsd"){let o=t.score??0;return n==="percent"?o*100<=a:o<=a/100}return n==="percent"?(t.diffPercentage??0)<=a:(t.diffCount??0)<=a}async function et(e,t,r){let a=Ye(r,t),{snapshotDir:n,baselinePath:o,receivedPath:s,diffPath:f}=a,D=z(e),u=D?e:null,U=t.runInWorker!==false,p=U?ye:M,g=U?xe:B,Y=U?(I,h,te)=>De(I,h,t.method,t,te):(I,h,te)=>W(I,h,t.method,t,te);oe(n);let v=j(o),F=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!v&&F!=="none"&&(F==="new"||F==="all")){if(u)S(o,u);else if(b(e)){let h=await g(e);await C(o,h.data,h.width,h.height);}else if(P(e))await C(o,e.data,e.width,e.height);else {let h=await p(e);await C(o,h.data,h.width,h.height);}return {pass:true,message:N({pass:true,method:t.method,snapshotCreated:true,baselinePath:o,receivedPath:s,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:o,snapshotStatus:"added"}}let c,d;t.method==="core-native"?(c=await W(e,o,t.method,t,f),d=e):(d=D?await p(e):e,c=await Y(P(d)?d:await p(d),o,f));let ee=Re(t.method,c,t);if(ee)return existsSync(s)&&unlinkSync(s),existsSync(f)&&unlinkSync(f),{pass:true,message:N({pass:ee,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:s,diffPath:f,diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,baselinePath:o,snapshotStatus:"matched"};if(F==="all"){if(u)S(o,u);else if(b(d)){let h=await g(d);await C(o,h.data,h.width,h.height);}else P(d)&&await C(o,d.data,d.width,d.height);return existsSync(s)&&unlinkSync(s),existsSync(f)&&unlinkSync(f),{pass:true,message:N({pass:true,method:t.method,snapshotCreated:true,baselinePath:o,receivedPath:s,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:o,snapshotStatus:"updated"}}if(u)S(s,u);else if(b(d)){let I=await g(d);await C(s,I.data,I.width,I.height);}else P(d)&&await C(s,d.data,d.width,d.height);if(c.diffOutput){let I=P(d)?d:await p(d);await C(f,c.diffOutput,I.width,I.height);}return {pass:false,message:N({pass:ee,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:s,diffPath:f,diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),diffCount:c.diffCount,diffPercentage:c.diffPercentage,score:c.score,baselinePath:o,receivedPath:s,diffPath:f,snapshotStatus:"failed"}}async function tt(e,t,r){let a=await W(e,t,r.method,r),n=Re(r.method,a,r);return {pass:n,message:n?"Images match.":`Images differ: ${a.diffCount??a.score} ${a.diffCount!==void 0?"pixels":"score"}`,diffCount:a.diffCount,diffPercentage:a.diffPercentage,score:a.score}}export{tt as compareImages,j as fileExists,N as formatReport,et as getOrCreateSnapshot,b as isFilePath,he as isImageBuffer,P as isImageData,z as isRawPngBuffer,B as loadPNG,M as normalizeImageInput,W as runComparison,C as savePNG,S as saveRawPNGBuffer,Ke as terminateWorker};
package/dist/worker.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var worker_threads=require('worker_threads'),fs=require('fs');require('path');var codecPngjs=require('@blazediff/codec-pngjs'),core=require('@blazediff/core'),coreNative=require('@blazediff/core-native'),promises=require('fs/promises'),module$1=require('module'),gmsd=require('@blazediff/gmsd'),ssim=require('@blazediff/ssim'),hitchhikersSsim=require('@blazediff/ssim/hitchhikers-ssim'),msssim=require('@blazediff/ssim/msssim');var U=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,u=U();function p(t){return typeof t=="string"}function R(t){return (Buffer.isBuffer(t)||t instanceof Uint8Array)&&!("width"in t)}function g(t){return typeof t=="object"&&t!==null&&"data"in t&&"width"in t&&"height"in t}async function l(t){if(!fs.existsSync(t))throw new Error(`Image file not found: ${t}`);let e=await codecPngjs.codecPngjs.read(t);return {data:new Uint8Array(e.data),width:e.width,height:e.height}}async function d(t){if(p(t))return l(t);if(R(t)){let e=Buffer.isBuffer(t)?t:Buffer.from(t),o=await codecPngjs.codecPngjs.read(e);return {data:new Uint8Array(o.data),width:o.width,height:o.height}}return t.data instanceof Uint8Array?t:{data:new Uint8Array(t.data),width:t.width,height:t.height}}function w(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {diffCount:n,diffPercentage:100};let f=o?new Uint8Array(n*4):void 0,m=core.diff(t.data,e.data,f,r,i,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:m,diffPercentage:m/n*100,diffOutput:f}}async function y(t,e,o,a){if(!p(t))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!p(e))throw new Error("Method 'core-native' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let r=await coreNative.compare(t,e,o,{threshold:a.threshold,antialiasing:a.antialiasing});if(r.match)return {diffCount:0,diffPercentage:0};if(r.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(r.reason==="pixel-diff")return {diffCount:r.diffCount,diffPercentage:r.diffPercentage};if(r.reason==="file-not-exists")throw new Error(`Image file not found: ${r.file}`);return {diffCount:0,diffPercentage:0}}var B=module$1.createRequire(u),I;function G(){return I||(I=import('@blazediff/core-wasm').then(async t=>{let e=B.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await t.initBlazediff(await promises.readFile(e)),t})),I}async function C(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {diffCount:n,diffPercentage:100};let f=o?new Uint8Array(n*4):void 0,{diff:m}=await G(),s=await m(t.data,e.data,r,i,f,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:s,diffPercentage:s/n*100,diffOutput:f}}function P(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {score:1};let f=o?new Uint8Array(n*4):void 0;return {score:gmsd.gmsd(t.data,e.data,f,r,i,{downsample:a.downsample}),diffOutput:f}}function x(t,e,o,a,r){let{width:i,height:n}=t,f=i*n;if(t.width!==e.width||t.height!==e.height)return {score:0};let m=a?new Uint8Array(f*4):void 0,s={windowSize:r.windowSize,k1:r.k1,k2:r.k2},c;switch(o){case "ssim":c=ssim.ssim(t.data,e.data,m,i,n,s);break;case "msssim":c=msssim.msssim(t.data,e.data,m,i,n,s);break;case "hitchhikers-ssim":c=hitchhikersSsim.hitchhikersSSIM(t.data,e.data,m,i,n,s);break;default:throw new Error(`Unknown SSIM method: ${o}`)}return {score:c,diffOutput:m}}function M(t){return t==="ssim"||t==="msssim"||t==="hitchhikers-ssim"}function A(t,e){if(t==="core-native"&&!p(e))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function O(t,e,o,a,r){if(A(o,t),A(o,e),o==="core-native"){let s=await y(t,e,r,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage}}let i=g(t)?t:await d(t),n=g(e)?e:await d(e),f=r!==void 0;if(M(o)){let s=x(i,n,o,f,a);return {score:s.score,diffOutput:s.diffOutput}}if(o==="gmsd"){let s=P(i,n,f,a);return {score:s.score,diffOutput:s.diffOutput}}if(o==="core-wasm"){let s=await C(i,n,f,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage,diffOutput:s.diffOutput}}let m=w(i,n,f,a);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage,diffOutput:m.diffOutput}}function L(t){return t.data instanceof Uint8Array?t:{data:new Uint8Array(t.data),width:t.width,height:t.height}}async function _(t){switch(t.type){case "normalize":{let{input:e}=t.payload;return d(e)}case "loadPNG":{let{filePath:e}=t.payload;return l(e)}case "compare":{let{received:e,baseline:o,method:a,options:r,diffOutputPath:i}=t.payload;return O(L(e),o,a,r,i)}default:throw new Error(`Unknown request type: ${t.type}`)}}worker_threads.parentPort&&worker_threads.parentPort.on("message",async t=>{try{let e=await _(t);worker_threads.parentPort?.postMessage({id:t.id,success:!0,result:e});}catch(e){worker_threads.parentPort?.postMessage({id:t.id,success:false,error:e instanceof Error?e.message:String(e)});}});
1
+ 'use strict';var worker_threads=require('worker_threads'),fs=require('fs');require('path');var codecPngjs=require('@blazediff/codec-pngjs'),core=require('@blazediff/core'),coreNative=require('@blazediff/core-native'),promises=require('fs/promises'),module$1=require('module'),gmsd=require('@blazediff/gmsd'),ssim=require('@blazediff/ssim'),hitchhikersSsim=require('@blazediff/ssim/hitchhikers-ssim'),msssim=require('@blazediff/ssim/msssim');var O=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,s=O();function U(e){return typeof e=="string"}function S(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function l(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function h(e){if(!fs.existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function p(e){if(U(e))return h(e);if(S(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function u(e,t){if(e.kind==="dimension-mismatch"){let{a:r,b:a}=e;return {diffCount:Math.max(r.width*r.height,a.width*a.height),diffPercentage:100}}return {diffCount:e.count,diffPercentage:e.percentage,diffOutput:t?.data}}function m({width:e,height:t}){return {data:new Uint8Array(e*t*4),width:e,height:t}}function y(e,t,r,a){let o=r?m(e):void 0;return u(core.diff(e,t,{...a.diff,output:o}),o)}async function I(e,t,r,a){let o=await coreNative.diff(e,t,{...a.diff,output:r});if(o.kind==="io-error")throw new Error(o.path?`Image file not found or unreadable: ${o.path}. ${o.message}`:o.message);return u(o)}var B=module$1.createRequire(s),w;function W(){return w||(w=import('@blazediff/core-wasm').then(async e=>{let t=B.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await promises.readFile(t)),e})),w}async function P(e,t,r,a){let o=r?m(e):void 0,{diff:i}=await W();return u(await i(e,t,{...a.diff,output:o}),o)}function C(e,t,r,a){let o=r?m(e):void 0,i=gmsd.gmsd(e,t,{...a.gmsd,output:o});return i.kind==="dimension-mismatch"?{score:1}:{score:i.score,diffOutput:o?.data}}var b={ssim:ssim.ssim,msssim:msssim.msssim,"hitchhikers-ssim":hitchhikersSsim.hitchhikersSSIM};function x(e,t,r,a,o){let i=a?m(e):void 0,f=b[r](e,t,{...o.ssim,output:i});return f.kind==="dimension-mismatch"?{score:0}:{score:f.score,diffOutput:i?.data}}function R(e){return e in b}async function M(e,t,r,a,o){if(r==="core-native"){let n=await I(e,t,o,a);return {diffCount:n.diffCount,diffPercentage:n.diffPercentage}}let i=l(e)?e:await p(e),f=l(t)?t:await p(t),c=o!==void 0;if(R(r)){let n=x(i,f,r,c,a);return {score:n.score,diffOutput:n.diffOutput}}if(r==="gmsd"){let n=C(i,f,c,a);return {score:n.score,diffOutput:n.diffOutput}}if(r==="core-wasm"){let n=await P(i,f,c,a);return {diffCount:n.diffCount,diffPercentage:n.diffPercentage,diffOutput:n.diffOutput}}let g=y(i,f,c,a);return {diffCount:g.diffCount,diffPercentage:g.diffPercentage,diffOutput:g.diffOutput}}function j(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function F(e){switch(e.type){case "normalize":{let{input:t}=e.payload;return p(t)}case "loadPNG":{let{filePath:t}=e.payload;return h(t)}case "compare":{let{received:t,baseline:r,method:a,options:o,diffOutputPath:i}=e.payload;return M(j(t),r,a,o,i)}default:throw new Error(`Unknown request type: ${e.type}`)}}worker_threads.parentPort&&worker_threads.parentPort.on("message",async e=>{try{let t=await F(e);worker_threads.parentPort?.postMessage({id:e.id,success:!0,result:t});}catch(t){worker_threads.parentPort?.postMessage({id:e.id,success:false,error:t instanceof Error?t.message:String(t)});}});
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import {parentPort}from'worker_threads';import {existsSync}from'fs';import'path';import {codecPngjs}from'@blazediff/codec-pngjs';import {diff}from'@blazediff/core';import {compare}from'@blazediff/core-native';import {readFile}from'fs/promises';import {createRequire}from'module';import {gmsd}from'@blazediff/gmsd';import {ssim}from'@blazediff/ssim';import {hitchhikersSSIM}from'@blazediff/ssim/hitchhikers-ssim';import {msssim}from'@blazediff/ssim/msssim';function d(t){return typeof t=="string"}function R(t){return (Buffer.isBuffer(t)||t instanceof Uint8Array)&&!("width"in t)}function l(t){return typeof t=="object"&&t!==null&&"data"in t&&"width"in t&&"height"in t}async function w(t){if(!existsSync(t))throw new Error(`Image file not found: ${t}`);let e=await codecPngjs.read(t);return {data:new Uint8Array(e.data),width:e.width,height:e.height}}async function c(t){if(d(t))return w(t);if(R(t)){let e=Buffer.isBuffer(t)?t:Buffer.from(t),o=await codecPngjs.read(e);return {data:new Uint8Array(o.data),width:o.width,height:o.height}}return t.data instanceof Uint8Array?t:{data:new Uint8Array(t.data),width:t.width,height:t.height}}function y(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {diffCount:n,diffPercentage:100};let f=o?new Uint8Array(n*4):void 0,m=diff(t.data,e.data,f,r,i,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:m,diffPercentage:m/n*100,diffOutput:f}}async function I(t,e,o,a){if(!d(t))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!d(e))throw new Error("Method 'core-native' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let r=await compare(t,e,o,{threshold:a.threshold,antialiasing:a.antialiasing});if(r.match)return {diffCount:0,diffPercentage:0};if(r.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(r.reason==="pixel-diff")return {diffCount:r.diffCount,diffPercentage:r.diffPercentage};if(r.reason==="file-not-exists")throw new Error(`Image file not found: ${r.file}`);return {diffCount:0,diffPercentage:0}}var B=createRequire(import.meta.url),C;function G(){return C||(C=import('@blazediff/core-wasm').then(async t=>{let e=B.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await t.initBlazediff(await readFile(e)),t})),C}async function P(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {diffCount:n,diffPercentage:100};let f=o?new Uint8Array(n*4):void 0,{diff:m}=await G(),s=await m(t.data,e.data,r,i,f,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:s,diffPercentage:s/n*100,diffOutput:f}}function x(t,e,o,a){let{width:r,height:i}=t,n=r*i;if(t.width!==e.width||t.height!==e.height)return {score:1};let f=o?new Uint8Array(n*4):void 0;return {score:gmsd(t.data,e.data,f,r,i,{downsample:a.downsample}),diffOutput:f}}function M(t,e,o,a,r){let{width:i,height:n}=t,f=i*n;if(t.width!==e.width||t.height!==e.height)return {score:0};let m=a?new Uint8Array(f*4):void 0,s={windowSize:r.windowSize,k1:r.k1,k2:r.k2},h;switch(o){case "ssim":h=ssim(t.data,e.data,m,i,n,s);break;case "msssim":h=msssim(t.data,e.data,m,i,n,s);break;case "hitchhikers-ssim":h=hitchhikersSSIM(t.data,e.data,m,i,n,s);break;default:throw new Error(`Unknown SSIM method: ${o}`)}return {score:h,diffOutput:m}}function b(t){return t==="ssim"||t==="msssim"||t==="hitchhikers-ssim"}function O(t,e){if(t==="core-native"&&!d(e))throw new Error("Method 'core-native' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function D(t,e,o,a,r){if(O(o,t),O(o,e),o==="core-native"){let s=await I(t,e,r,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage}}let i=l(t)?t:await c(t),n=l(e)?e:await c(e),f=r!==void 0;if(b(o)){let s=M(i,n,o,f,a);return {score:s.score,diffOutput:s.diffOutput}}if(o==="gmsd"){let s=x(i,n,f,a);return {score:s.score,diffOutput:s.diffOutput}}if(o==="core-wasm"){let s=await P(i,n,f,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage,diffOutput:s.diffOutput}}let m=y(i,n,f,a);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage,diffOutput:m.diffOutput}}function $(t){return t.data instanceof Uint8Array?t:{data:new Uint8Array(t.data),width:t.width,height:t.height}}async function j(t){switch(t.type){case "normalize":{let{input:e}=t.payload;return c(e)}case "loadPNG":{let{filePath:e}=t.payload;return w(e)}case "compare":{let{received:e,baseline:o,method:a,options:r,diffOutputPath:i}=t.payload;return D($(e),o,a,r,i)}default:throw new Error(`Unknown request type: ${t.type}`)}}parentPort&&parentPort.on("message",async t=>{try{let e=await j(t);parentPort?.postMessage({id:t.id,success:!0,result:e});}catch(e){parentPort?.postMessage({id:t.id,success:false,error:e instanceof Error?e.message:String(e)});}});
1
+ import {parentPort}from'worker_threads';import {existsSync}from'fs';import'path';import {codecPngjs}from'@blazediff/codec-pngjs';import {diff as diff$1}from'@blazediff/core';import {diff}from'@blazediff/core-native';import {readFile}from'fs/promises';import {createRequire}from'module';import {gmsd}from'@blazediff/gmsd';import {ssim}from'@blazediff/ssim';import {hitchhikersSSIM}from'@blazediff/ssim/hitchhikers-ssim';import {msssim}from'@blazediff/ssim/msssim';function U(e){return typeof e=="string"}function A(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function h(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function y(e){if(!existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await codecPngjs.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function c(e){if(U(e))return y(e);if(A(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await codecPngjs.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}function p(e,t){if(e.kind==="dimension-mismatch"){let{a:r,b:o}=e;return {diffCount:Math.max(r.width*r.height,o.width*o.height),diffPercentage:100}}return {diffCount:e.count,diffPercentage:e.percentage,diffOutput:t?.data}}function f({width:e,height:t}){return {data:new Uint8Array(e*t*4),width:e,height:t}}function I(e,t,r,o){let a=r?f(e):void 0;return p(diff$1(e,t,{...o.diff,output:a}),a)}async function w(e,t,r,o){let a=await diff(e,t,{...o.diff,output:r});if(a.kind==="io-error")throw new Error(a.path?`Image file not found or unreadable: ${a.path}. ${a.message}`:a.message);return p(a)}var B=createRequire(import.meta.url),P;function W(){return P||(P=import('@blazediff/core-wasm').then(async e=>{let t=B.resolve("@blazediff/core-wasm/wasm/blazediff_bg.wasm");return await e.initBlazediff(await readFile(t)),e})),P}async function C(e,t,r,o){let a=r?f(e):void 0,{diff:i}=await W();return p(await i(e,t,{...o.diff,output:a}),a)}function x(e,t,r,o){let a=r?f(e):void 0,i=gmsd(e,t,{...o.gmsd,output:a});return i.kind==="dimension-mismatch"?{score:1}:{score:i.score,diffOutput:a?.data}}var M={ssim:ssim,msssim:msssim,"hitchhikers-ssim":hitchhikersSSIM};function D(e,t,r,o,a){let i=o?f(e):void 0,u=M[r](e,t,{...a.ssim,output:i});return u.kind==="dimension-mismatch"?{score:0}:{score:u.score,diffOutput:i?.data}}function b(e){return e in M}async function O(e,t,r,o,a){if(r==="core-native"){let n=await w(e,t,a,o);return {diffCount:n.diffCount,diffPercentage:n.diffPercentage}}let i=h(e)?e:await c(e),u=h(t)?t:await c(t),d=a!==void 0;if(b(r)){let n=D(i,u,r,d,o);return {score:n.score,diffOutput:n.diffOutput}}if(r==="gmsd"){let n=x(i,u,d,o);return {score:n.score,diffOutput:n.diffOutput}}if(r==="core-wasm"){let n=await C(i,u,d,o);return {diffCount:n.diffCount,diffPercentage:n.diffPercentage,diffOutput:n.diffOutput}}let l=I(i,u,d,o);return {diffCount:l.diffCount,diffPercentage:l.diffPercentage,diffOutput:l.diffOutput}}function $(e){return e.data instanceof Uint8Array?e:{data:new Uint8Array(e.data),width:e.width,height:e.height}}async function j(e){switch(e.type){case "normalize":{let{input:t}=e.payload;return c(t)}case "loadPNG":{let{filePath:t}=e.payload;return y(t)}case "compare":{let{received:t,baseline:r,method:o,options:a,diffOutputPath:i}=e.payload;return O($(t),r,o,a,i)}default:throw new Error(`Unknown request type: ${e.type}`)}}parentPort&&parentPort.on("message",async e=>{try{let t=await j(e);parentPort?.postMessage({id:e.id,success:!0,result:t});}catch(t){parentPort?.postMessage({id:e.id,success:false,error:t instanceof Error?t.message:String(t)});}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazediff/matcher",
3
- "version": "2.0.8",
3
+ "version": "3.0.0",
4
4
  "description": "Core matcher logic for visual regression testing with blazediff",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -33,12 +33,12 @@
33
33
  "license": "MIT",
34
34
  "dependencies": {
35
35
  "picocolors": "^1.1.1",
36
- "@blazediff/core-native": "6.0.2",
37
- "@blazediff/core": "1.10.0",
38
- "@blazediff/core-wasm": "6.0.2",
36
+ "@blazediff/core": "2.0.0",
37
+ "@blazediff/core-native": "7.0.0",
38
+ "@blazediff/gmsd": "2.0.0",
39
+ "@blazediff/core-wasm": "7.0.0",
39
40
  "@blazediff/codec-pngjs": "4.0.0",
40
- "@blazediff/ssim": "1.7.1",
41
- "@blazediff/gmsd": "1.7.1"
41
+ "@blazediff/ssim": "2.0.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^24.3.0",