@blazediff/matcher 0.0.0-fix-testing-matcher-performance-20260223113219

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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Teimur Gasanov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,353 @@
1
+ # @blazediff/matcher
2
+
3
+ <div align="center">
4
+
5
+ [![npm bundle size](https://img.shields.io/bundlephobia/min/%40blazediff%2Fmatcher)](https://www.npmjs.com/package/@blazediff/matcher)
6
+ [![NPM Downloads](https://img.shields.io/npm/dy/%40blazediff%2Fmatcher)](https://www.npmjs.com/package/@blazediff/matcher)
7
+
8
+ </div>
9
+
10
+ Core matcher logic for visual regression testing. Provides snapshot comparison with multiple algorithms, framework-agnostic APIs, and snapshot state tracking.
11
+
12
+ ## Features
13
+
14
+ - **Multiple comparison methods**: `core`, `bin`, `ssim`, `msssim`, `hitchhikers-ssim`, `gmsd`
15
+ - **Flexible input types**: File paths or image buffers
16
+ - **Snapshot state tracking**: Reports added/matched/updated/failed status
17
+ - **Configurable thresholds**: Pixel count or percentage-based
18
+ - **Framework-agnostic**: Core logic for Jest, Vitest, Bun integrations
19
+ - **Rich comparison results**: Diff counts, percentages, and similarity scores
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @blazediff/matcher
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ```typescript
30
+ import { getOrCreateSnapshot } from '@blazediff/matcher';
31
+
32
+ const result = await getOrCreateSnapshot(
33
+ imageBuffer, // or file path
34
+ {
35
+ method: 'core',
36
+ failureThreshold: 0.01,
37
+ failureThresholdType: 'percent',
38
+ },
39
+ {
40
+ testPath: '/path/to/test.spec.ts',
41
+ testName: 'should render correctly',
42
+ }
43
+ );
44
+
45
+ console.log(result.pass); // true/false
46
+ console.log(result.snapshotStatus); // 'added' | 'matched' | 'updated' | 'failed'
47
+ console.log(result.diffPercentage); // e.g., 0.05
48
+ ```
49
+
50
+ ## API Reference
51
+
52
+ ### getOrCreateSnapshot(received, options, testContext)
53
+
54
+ Main function for snapshot comparison.
55
+
56
+ <table>
57
+ <tr>
58
+ <th width="500">Parameter</th>
59
+ <th width="500">Type</th>
60
+ <th width="500">Description</th>
61
+ </tr>
62
+ <tr>
63
+ <td><code>received</code></td>
64
+ <td>ImageInput</td>
65
+ <td>Image to compare (file path or buffer with dimensions)</td>
66
+ </tr>
67
+ <tr>
68
+ <td><code>options</code></td>
69
+ <td>MatcherOptions</td>
70
+ <td>Comparison options (see below)</td>
71
+ </tr>
72
+ <tr>
73
+ <td><code>testContext</code></td>
74
+ <td>TestContext</td>
75
+ <td>Test information (testPath, testName)</td>
76
+ </tr>
77
+ </table>
78
+
79
+ **Returns:** `Promise<ComparisonResult>`
80
+
81
+ ### MatcherOptions
82
+
83
+ <table>
84
+ <tr>
85
+ <th width="500">Option</th>
86
+ <th width="500">Type</th>
87
+ <th width="500">Default</th>
88
+ <th width="500">Description</th>
89
+ </tr>
90
+ <tr>
91
+ <td><code>method</code></td>
92
+ <td>ComparisonMethod</td>
93
+ <td>-</td>
94
+ <td>Comparison algorithm to use</td>
95
+ </tr>
96
+ <tr>
97
+ <td><code>failureThreshold</code></td>
98
+ <td>number</td>
99
+ <td>0</td>
100
+ <td>Number of pixels or percentage difference allowed</td>
101
+ </tr>
102
+ <tr>
103
+ <td><code>failureThresholdType</code></td>
104
+ <td>'pixel' | 'percent'</td>
105
+ <td>'pixel'</td>
106
+ <td>How to interpret failureThreshold</td>
107
+ </tr>
108
+ <tr>
109
+ <td><code>snapshotsDir</code></td>
110
+ <td>string</td>
111
+ <td>'__snapshots__'</td>
112
+ <td>Directory to store snapshots (relative to test file)</td>
113
+ </tr>
114
+ <tr>
115
+ <td><code>snapshotIdentifier</code></td>
116
+ <td>string</td>
117
+ <td>-</td>
118
+ <td>Custom identifier for the snapshot file</td>
119
+ </tr>
120
+ <tr>
121
+ <td><code>updateSnapshots</code></td>
122
+ <td>boolean</td>
123
+ <td>false</td>
124
+ <td>Force update snapshots (like running with -u flag)</td>
125
+ </tr>
126
+ <tr>
127
+ <td><code>threshold</code></td>
128
+ <td>number</td>
129
+ <td>0.1</td>
130
+ <td>Color difference threshold for core/bin 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 (bin 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>
155
+ </tr>
156
+ <tr>
157
+ <td><code>k2</code></td>
158
+ <td>number</td>
159
+ <td>0.03</td>
160
+ <td>k2 constant for SSIM</td>
161
+ </tr>
162
+ <tr>
163
+ <td><code>downsample</code></td>
164
+ <td>0 | 1</td>
165
+ <td>0</td>
166
+ <td>Downsample factor for GMSD</td>
167
+ </tr>
168
+ <tr>
169
+ <td><code>runInWorker</code></td>
170
+ <td>boolean</td>
171
+ <td>true</td>
172
+ <td>Run image I/O and comparison in a worker thread for better performance</td>
173
+ </tr>
174
+ </table>
175
+
176
+ ### ComparisonResult
177
+
178
+ <table>
179
+ <tr>
180
+ <th width="500">Field</th>
181
+ <th width="500">Type</th>
182
+ <th width="500">Description</th>
183
+ </tr>
184
+ <tr>
185
+ <td><code>pass</code></td>
186
+ <td>boolean</td>
187
+ <td>Whether the comparison passed</td>
188
+ </tr>
189
+ <tr>
190
+ <td><code>message</code></td>
191
+ <td>string</td>
192
+ <td>Human-readable message describing the result</td>
193
+ </tr>
194
+ <tr>
195
+ <td><code>snapshotStatus</code></td>
196
+ <td>SnapshotStatus</td>
197
+ <td>'added' | 'matched' | 'updated' | 'failed'</td>
198
+ </tr>
199
+ <tr>
200
+ <td><code>diffCount</code></td>
201
+ <td>number</td>
202
+ <td>Number of different pixels (pixel-based methods)</td>
203
+ </tr>
204
+ <tr>
205
+ <td><code>diffPercentage</code></td>
206
+ <td>number</td>
207
+ <td>Percentage of different pixels</td>
208
+ </tr>
209
+ <tr>
210
+ <td><code>score</code></td>
211
+ <td>number</td>
212
+ <td>Similarity score (SSIM: 1 = identical, GMSD: 0 = identical)</td>
213
+ </tr>
214
+ <tr>
215
+ <td><code>baselinePath</code></td>
216
+ <td>string</td>
217
+ <td>Path to baseline snapshot</td>
218
+ </tr>
219
+ <tr>
220
+ <td><code>receivedPath</code></td>
221
+ <td>string</td>
222
+ <td>Path to received image (saved for debugging on failure)</td>
223
+ </tr>
224
+ <tr>
225
+ <td><code>diffPath</code></td>
226
+ <td>string</td>
227
+ <td>Path to diff visualization</td>
228
+ </tr>
229
+ </table>
230
+
231
+ ### ImageInput
232
+
233
+ ```typescript
234
+ type ImageInput =
235
+ | string // File path
236
+ | {
237
+ data: Uint8Array | Uint8ClampedArray | Buffer;
238
+ width: number;
239
+ height: number;
240
+ };
241
+ ```
242
+
243
+ ## Comparison Methods
244
+
245
+ ### `bin`
246
+ Rust-native comparison via N-API bindings. **Fastest method** with native performance.
247
+ - **Input**: File paths only
248
+ - **Algorithm**: YIQ color space with block-based optimization
249
+ - **Best for**: Production testing, large images
250
+
251
+ ### `core`
252
+ Pixel-by-pixel comparison in JavaScript. Pure JS implementation with no native dependencies.
253
+ - **Input**: File paths or buffers
254
+ - **Algorithm**: YIQ color space with anti-aliasing detection
255
+ - **Best for**: Cross-platform compatibility
256
+
257
+ ### `ssim`
258
+ Structural Similarity Index. Measures perceptual similarity.
259
+ - **Input**: File paths or buffers
260
+ - **Algorithm**: Standard SSIM with configurable window size
261
+ - **Best for**: Perceptual quality assessment
262
+ - **Score**: 1 = identical, lower = more different
263
+
264
+ ### `msssim`
265
+ Multi-Scale Structural Similarity Index.
266
+ - **Input**: File paths or buffers
267
+ - **Algorithm**: SSIM across multiple scales
268
+ - **Best for**: Images with varying resolutions or scales
269
+
270
+ ### `hitchhikers-ssim`
271
+ Fast SSIM approximation from Hitchhiker's Guide.
272
+ - **Input**: File paths or buffers
273
+ - **Algorithm**: Optimized SSIM calculation
274
+ - **Best for**: Faster SSIM with acceptable accuracy trade-off
275
+
276
+ ### `gmsd`
277
+ Gradient Magnitude Similarity Deviation.
278
+ - **Input**: File paths or buffers
279
+ - **Algorithm**: Gradient-based perceptual similarity
280
+ - **Best for**: Detecting structural changes
281
+ - **Score**: 0 = identical, higher = more different
282
+
283
+ ## Usage Examples
284
+
285
+ ### With File Paths
286
+
287
+ ```typescript
288
+ const result = await getOrCreateSnapshot(
289
+ '/path/to/screenshot.png',
290
+ { method: 'bin' },
291
+ { testPath: __filename, testName: 'test name' }
292
+ );
293
+ ```
294
+
295
+ ### With Image Buffers
296
+
297
+ ```typescript
298
+ const imageData = {
299
+ data: new Uint8Array([...]),
300
+ width: 800,
301
+ height: 600,
302
+ };
303
+
304
+ const result = await getOrCreateSnapshot(
305
+ imageData,
306
+ { method: 'core' },
307
+ { testPath: __filename, testName: 'test name' }
308
+ );
309
+ ```
310
+
311
+ ### Custom Threshold
312
+
313
+ ```typescript
314
+ const result = await getOrCreateSnapshot(
315
+ imagePath,
316
+ {
317
+ method: 'core',
318
+ failureThreshold: 0.1,
319
+ failureThresholdType: 'percent', // Allow 0.1% difference
320
+ },
321
+ { testPath: __filename, testName: 'test name' }
322
+ );
323
+ ```
324
+
325
+ ### Different Comparison Methods
326
+
327
+ ```typescript
328
+ // Fastest - Rust native (file paths only)
329
+ await getOrCreateSnapshot(imagePath, { method: 'bin' }, context);
330
+
331
+ // Pure JavaScript
332
+ await getOrCreateSnapshot(imageBuffer, { method: 'core' }, context);
333
+
334
+ // Perceptual similarity
335
+ await getOrCreateSnapshot(imageBuffer, { method: 'ssim' }, context);
336
+
337
+ // Gradient-based
338
+ await getOrCreateSnapshot(imageBuffer, { method: 'gmsd' }, context);
339
+ ```
340
+
341
+ ## Framework Integrations
342
+
343
+ This package provides the core logic for framework-specific integrations:
344
+
345
+ - [@blazediff/jest](https://www.npmjs.com/package/@blazediff/jest) - Jest matcher
346
+ - [@blazediff/vitest](https://www.npmjs.com/package/@blazediff/vitest) - Vitest matcher
347
+ - [@blazediff/bun](https://www.npmjs.com/package/@blazediff/bun) - Bun test matcher
348
+
349
+ ## Links
350
+
351
+ - [GitHub Repository](https://github.com/teimurjan/blazediff)
352
+ - [Documentation](https://blazediff.dev/docs/matcher)
353
+ - [NPM Package](https://www.npmjs.com/package/@blazediff/matcher)
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Comparison methods available in blazediff
3
+ */
4
+ type ComparisonMethod = "bin" | "core" | "ssim" | "msssim" | "hitchhikers-ssim" | "gmsd";
5
+ /**
6
+ * Status of a snapshot operation
7
+ */
8
+ type SnapshotStatus = "added" | "matched" | "updated" | "failed";
9
+ /**
10
+ * Image input - file path, raw PNG buffer, or buffer with dimensions
11
+ */
12
+ type ImageInput = string | Buffer | Uint8Array | {
13
+ data: Uint8Array | Uint8ClampedArray | Buffer;
14
+ width: number;
15
+ height: number;
16
+ };
17
+ /**
18
+ * Options for the matcher
19
+ */
20
+ interface MatcherOptions {
21
+ /** Comparison method to use */
22
+ method: ComparisonMethod;
23
+ /**
24
+ * Failure threshold - number of pixels or percentage difference allowed
25
+ * @default 0
26
+ */
27
+ failureThreshold?: number;
28
+ /**
29
+ * How to interpret failureThreshold
30
+ * @default 'pixel'
31
+ */
32
+ failureThresholdType?: "pixel" | "percent";
33
+ /**
34
+ * Directory to store snapshots relative to test file
35
+ * @default '__snapshots__'
36
+ */
37
+ snapshotsDir?: string;
38
+ /**
39
+ * Custom identifier for the snapshot file
40
+ * If not provided, derived from test name
41
+ */
42
+ snapshotIdentifier?: string;
43
+ /**
44
+ * Snapshot update mode (following Vitest's logic)
45
+ * - 'all': update all snapshots (vitest -u)
46
+ * - 'new': create new snapshots only, don't update existing (default)
47
+ * - 'none': don't create or update any snapshots
48
+ * - true: same as 'all' (backwards compatibility)
49
+ * - false: same as 'new' (backwards compatibility)
50
+ * @default 'new'
51
+ */
52
+ updateSnapshots?: boolean | "all" | "new" | "none";
53
+ /**
54
+ * Custom update command to display in error messages
55
+ * @default '--update'
56
+ */
57
+ updateCommand?: string;
58
+ /**
59
+ * Color difference threshold for core/bin methods (0-1)
60
+ * Lower = more strict
61
+ * @default 0.1
62
+ */
63
+ threshold?: number;
64
+ /**
65
+ * Enable anti-aliasing detection (bin method)
66
+ * @default false
67
+ */
68
+ antialiasing?: boolean;
69
+ /**
70
+ * Include anti-aliased pixels in diff count (core method)
71
+ * @default false
72
+ */
73
+ includeAA?: boolean;
74
+ /**
75
+ * Window size for SSIM variants
76
+ * @default 11
77
+ */
78
+ windowSize?: number;
79
+ /**
80
+ * k1 constant for SSIM
81
+ * @default 0.01
82
+ */
83
+ k1?: number;
84
+ /**
85
+ * k2 constant for SSIM
86
+ * @default 0.03
87
+ */
88
+ k2?: number;
89
+ /**
90
+ * Downsample factor for GMSD (0 or 1)
91
+ * @default 0
92
+ */
93
+ downsample?: 0 | 1;
94
+ /**
95
+ * Run image I/O and comparison in a worker thread
96
+ * Worker threads provide better performance by avoiding V8 heap contention
97
+ * @default true
98
+ */
99
+ runInWorker?: boolean;
100
+ }
101
+ /**
102
+ * Result of a comparison operation
103
+ */
104
+ interface ComparisonResult {
105
+ /** Whether the comparison passed */
106
+ pass: boolean;
107
+ /** Human-readable message describing the result */
108
+ message: string;
109
+ /** Number of different pixels (for pixel-based methods) */
110
+ diffCount?: number;
111
+ /** Percentage of different pixels */
112
+ diffPercentage?: number;
113
+ /** Similarity score (for SSIM/GMSD - 1 = identical for SSIM, 0 = identical for GMSD) */
114
+ score?: number;
115
+ /** Path to baseline snapshot */
116
+ baselinePath?: string;
117
+ /** Path to received image (saved for debugging) */
118
+ receivedPath?: string;
119
+ /** Path to diff visualization */
120
+ diffPath?: string;
121
+ /** Status of the snapshot operation */
122
+ snapshotStatus?: SnapshotStatus;
123
+ }
124
+ /**
125
+ * Context provided by test frameworks
126
+ */
127
+ interface TestContext {
128
+ /** Absolute path to the test file */
129
+ testPath: string;
130
+ /** Name of the current test */
131
+ testName: string;
132
+ }
133
+ /**
134
+ * Image data with dimensions
135
+ */
136
+ interface ImageData {
137
+ data: Uint8Array;
138
+ width: number;
139
+ height: number;
140
+ }
141
+
142
+ interface RunComparisonResult {
143
+ /** Number of different pixels (for pixel-based methods) */
144
+ diffCount?: number;
145
+ /** Percentage of different pixels */
146
+ diffPercentage?: number;
147
+ /** Score for perceptual methods (SSIM: 1=identical, GMSD: 0=identical) */
148
+ score?: number;
149
+ /** Diff visualization output buffer */
150
+ diffOutput?: Uint8Array;
151
+ }
152
+ /**
153
+ * Validate that the comparison method supports the given input type
154
+ */
155
+ declare function validateMethodSupportsInput(method: ComparisonMethod, input: ImageInput): void;
156
+ /**
157
+ * Run comparison using the specified method
158
+ */
159
+ declare function runComparison(received: ImageInput, baseline: ImageInput, method: ComparisonMethod, options: MatcherOptions, diffOutputPath?: string): Promise<RunComparisonResult>;
160
+
161
+ /**
162
+ * Check if input is a file path
163
+ */
164
+ declare function isFilePath(input: ImageInput): input is string;
165
+ /**
166
+ * Check if input is a raw PNG buffer (Buffer or Uint8Array without dimensions)
167
+ */
168
+ declare function isRawPngBuffer(input: ImageInput): input is Buffer | Uint8Array;
169
+ /**
170
+ * Check if input is an image buffer with dimensions
171
+ */
172
+ declare function isImageBuffer(input: ImageInput): input is {
173
+ data: Uint8Array | Uint8ClampedArray | Buffer;
174
+ width: number;
175
+ height: number;
176
+ };
177
+ /**
178
+ * Type guard for ImageData
179
+ */
180
+ declare function isImageData(input: ImageInput): input is ImageData;
181
+ /**
182
+ * Load a PNG image from file path
183
+ */
184
+ declare function loadPNG(filePath: string): Promise<ImageData>;
185
+ /**
186
+ * Save image data to a PNG file
187
+ */
188
+ declare function savePNG(filePath: string, data: Uint8Array | Uint8ClampedArray | Buffer, width: number, height: number): Promise<void>;
189
+ /**
190
+ * Save a raw PNG buffer directly to file (no decode/encode cycle)
191
+ */
192
+ declare function saveRawPNGBuffer(filePath: string, buffer: Buffer | Uint8Array): void;
193
+ /**
194
+ * Normalize image input to ImageData
195
+ * - File path: loads the PNG
196
+ * - Raw PNG buffer: decodes to get dimensions
197
+ * - Buffer with dimensions: returns as-is (avoids unnecessary copy if already Uint8Array)
198
+ */
199
+ declare function normalizeImageInput(input: ImageInput): Promise<ImageData>;
200
+ /**
201
+ * Check if a file exists
202
+ */
203
+ declare function fileExists(filePath: string): boolean;
204
+
205
+ interface FormatOptions {
206
+ pass: boolean;
207
+ method: ComparisonMethod;
208
+ snapshotCreated: boolean;
209
+ baselinePath: string;
210
+ receivedPath: string;
211
+ diffPath: string;
212
+ diffCount?: number;
213
+ diffPercentage?: number;
214
+ score?: number;
215
+ threshold: number;
216
+ thresholdType: "pixel" | "percent";
217
+ updateCommand?: string;
218
+ }
219
+ declare function formatMessage(opts: FormatOptions): string;
220
+
221
+ /**
222
+ * Main snapshot comparison function
223
+ */
224
+ declare function getOrCreateSnapshot(received: ImageInput, options: MatcherOptions, testContext: TestContext): Promise<ComparisonResult>;
225
+ /**
226
+ * Compare two images directly without snapshot management
227
+ */
228
+ declare function compareImages(received: ImageInput, baseline: ImageInput, options: MatcherOptions): Promise<ComparisonResult>;
229
+
230
+ declare function terminateWorker(): Promise<number>;
231
+
232
+ 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 };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';var fs=require('fs'),path=require('path'),pngjsTransformer=require('@blazediff/pngjs-transformer'),bin=require('@blazediff/bin'),core=require('@blazediff/core'),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 we=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var r in t)we(e,r,{get:t[r],enumerable:true});};var u=b(()=>{});var fe={};ne(fe,{ensureDir:()=>ee,fileExists:()=>N,isFilePath:()=>I,isImageBuffer:()=>se,isImageData:()=>C,isRawPngBuffer:()=>E,loadPNG:()=>B,normalizeImageInput:()=>S,savePNG:()=>P,saveRawPNGBuffer:()=>R});function I(e){return typeof e=="string"}function E(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function se(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}function C(e){return typeof e=="object"&&e!==null&&"data"in e&&"width"in e&&"height"in e}async function B(e){if(!fs.existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await pngjsTransformer.pngjsTransformer.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function P(e,t,r,o){let n=path.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true}),await pngjsTransformer.pngjsTransformer.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(I(e))return B(e);if(E(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await pngjsTransformer.pngjsTransformer.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 N(e){return fs.existsSync(e)}function ee(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:true});}var k=b(()=>{u();});async function z(e,t,r,o){if(!I(e))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!I(t))throw new Error("Method 'bin' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let n=await bin.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 te=b(()=>{u();k();});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,h=core.diff(e.data,t.data,f,n,a,{threshold:o.threshold??.1,includeAA:o.includeAA??false});return {diffCount:h,diffPercentage:h/i*100,diffOutput:f}}var re=b(()=>{u();});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 {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 ae=b(()=>{u();});function _(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 h=o?new Uint8Array(f*4):void 0,m={windowSize:n.windowSize,k1:n.k1,k2:n.k2},x;switch(r){case "ssim":x=ssim.ssim(e.data,t.data,h,a,i,m);break;case "msssim":x=msssim.msssim(e.data,t.data,h,a,i,m);break;case "hitchhikers-ssim":x=hitchhikersSsim.hitchhikersSSIM(e.data,t.data,h,a,i,m);break;default:throw new Error(`Unknown SSIM method: ${r}`)}return {score:x,diffOutput:h}}function $(e){return e==="ssim"||e==="msssim"||e==="hitchhikers-ssim"}var v=b(()=>{u();});var me={};ne(me,{compareBin:()=>z,compareCore:()=>F,compareGmsd:()=>j,compareSsim:()=>_,isSsimMethod:()=>$,runComparison:()=>O,validateMethodSupportsInput:()=>q});function q(e,t){if(e==="bin"&&!I(t))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function O(e,t,r,o,n){if(q(r,e),q(r,t),r==="bin"){let m=await z(e,t,n,o);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage}}let a=C(e)?e:await S(e),i=C(t)?t:await S(t),f=n!==void 0;if($(r)){let m=_(a,i,r,f,o);return {score:m.score,diffOutput:m.diffOutput}}if(r==="gmsd"){let m=j(a,i,f,o);return {score:m.score,diffOutput:m.diffOutput}}let h=F(a,i,f,o);return {diffCount:h.diffCount,diffPercentage:h.diffPercentage,diffOutput:h.diffOutput}}var L=b(()=>{u();k();te();re();ae();v();te();re();ae();v();});u();L();k();u();var W={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":"'-"},Se=new Set(["ssim","msssim","hitchhikers-ssim"]);function T(e){return e.snapshotCreated?De(e.baselinePath):e.pass?Re():ke(e)}function De(e){return [`${s__default.default.green(W.success)} ${s__default.default.green("New snapshot created")}`,` ${s__default.default.dim(W.arrow)} ${s__default.default.dim(e)}`].join(`
2
+ `)}function Re(){return `${s__default.default.green(W.success)} ${s__default.default.green("Image matches snapshot")}`}function ke(e){let{method:t,baselinePath:r,receivedPath:o,diffPath:n,diffCount:a=0,diffPercentage:i,score:f=0,threshold:h,thresholdType:m,updateCommand:x}=e,p=[`${s__default.default.red(W.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(""),Se.has(t)){let U=((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(`${U}%`)}`);}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 U=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(`(${U}%)`)}`);}let J=m==="percent"?"%":"pixels";return p.push(` ${s__default.default.dim("Threshold".padEnd(g))}${h} ${J}`),p.push(""),p.push(` ${s__default.default.cyan(W.info)} ${s__default.default.cyan(`Run with ${x??"--update"} to update the snapshot`)}`),p.join(`
3
+ `)}u();L();v();k();u();var y=null,Oe=0,pe=false,D=new Map;function Te(){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 Ue(){if(pe)return null;if(!y){let e=Te();if(!e)return pe=true,null;y=new worker_threads.Worker(e),y.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)));}),y.on("error",t=>{for(let r of D.values())r.reject(t);D.clear(),y=null;}),y.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();}y=null;});}return y}async function oe(e,t){let r=Ue();if(!r){let{runComparison:o}=await Promise.resolve().then(()=>(L(),me)),{loadPNG:n,normalizeImageInput:a}=await Promise.resolve().then(()=>(k(),fe));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=++Oe;D.set(a,{resolve:o,reject:n});let i={id:a,type:e,payload:t};r.postMessage(i);})}function he(e){return oe("normalize",{input:e})}function ce(e){return oe("loadPNG",{filePath:e})}function le(e,t,r,o,n){return oe("compare",{received:e,baseline:t,method:r,options:o,diffOutputPath:n})}function Ae(){if(y){let e=y;return y=null,e.terminate()}return Promise.resolve(0)}function We(e){return e.testName.replace(/[^a-zA-Z0-9-_\s]/g,"").replace(/\s+/g,"-").toLowerCase()||"snapshot"}function Ge(e,t){let r=path.dirname(e.testPath),o=t.snapshotsDir??"__snapshots__",n=path.isAbsolute(o)?o:path.join(r,o),a=t.snapshotIdentifier??We(e);return {snapshotDir:n,baselinePath:path.join(n,`${a}.png`),receivedPath:path.join(n,`${a}.received.png`),diffPath:path.join(n,`${a}.diff.png`)}}function ge(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 Ne(e,t,r){let o=Ge(r,t),{snapshotDir:n,baselinePath:a,receivedPath:i,diffPath:f}=o,h=E(e),m=h?e:null,x=t.runInWorker!==false,p=x?he:S,g=x?ce:B,J=x?(w,l,Q)=>le(w,l,t.method,t,Q):(w,l,Q)=>O(w,l,t.method,t,Q);ee(n);let U=N(a),G=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!U&&G!=="none"&&(G==="new"||G==="all")){if(m)R(a,m);else if(I(e)){let l=await g(e);await P(a,l.data,l.width,l.height);}else if(C(e))await P(a,e.data,e.width,e.height);else {let l=await p(e);await P(a,l.data,l.width,l.height);}return {pass:true,message:T({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 c,d;t.method==="bin"?(c=await O(e,a,t.method,t,f),d=e):(d=h?await p(e):e,c=await J(C(d)?d:await p(d),a,f));let K=ge(t.method,c,t);if(K)return fs.existsSync(i)&&fs.unlinkSync(i),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:T({pass:K,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,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:a,snapshotStatus:"matched"};if(G==="all"){if(m)R(a,m);else if(I(d)){let l=await g(d);await P(a,l.data,l.width,l.height);}else C(d)&&await P(a,d.data,d.width,d.height);return fs.existsSync(i)&&fs.unlinkSync(i),fs.existsSync(f)&&fs.unlinkSync(f),{pass:true,message:T({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(I(d)){let w=await g(d);await P(i,w.data,w.width,w.height);}else C(d)&&await P(i,d.data,d.width,d.height);if(c.diffOutput&&t.method!=="bin"){let w=C(d)?d:await p(d);await P(f,c.diffOutput,w.width,w.height);}return {pass:false,message:T({pass:K,method:t.method,snapshotCreated:false,baselinePath:a,receivedPath:i,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:a,receivedPath:i,diffPath:f,snapshotStatus:"failed"}}async function ze(e,t,r){let o=await O(e,t,r.method,r),n=ge(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=N;exports.formatReport=T;exports.getOrCreateSnapshot=Ne;exports.isFilePath=I;exports.isImageBuffer=se;exports.isImageData=C;exports.isRawPngBuffer=E;exports.loadPNG=B;exports.normalizeImageInput=S;exports.runComparison=O;exports.savePNG=P;exports.saveRawPNGBuffer=R;exports.terminateWorker=Ae;exports.validateMethodSupportsInput=q;
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import Ce,{dirname,isAbsolute,join}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,unlinkSync}from'fs';import {pngjsTransformer}from'@blazediff/pngjs-transformer';import {compare}from'@blazediff/bin';import {diff}from'@blazediff/core';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 Ie=Object.defineProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{for(var r in t)Ie(e,r,{get:t[r],enumerable:true});};var ye,xe,I,u=S(()=>{ye=()=>fileURLToPath(import.meta.url),xe=()=>Ce.dirname(ye()),I=xe();});var me={};ie(me,{ensureDir:()=>te,fileExists:()=>z,isFilePath:()=>C,isImageBuffer:()=>fe,isImageData:()=>P,isRawPngBuffer:()=>B,loadPNG:()=>W,normalizeImageInput:()=>D,savePNG:()=>y,saveRawPNGBuffer:()=>R});function C(e){return typeof e=="string"}function B(e){return (Buffer.isBuffer(e)||e instanceof Uint8Array)&&!("width"in e)}function fe(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 W(e){if(!existsSync(e))throw new Error(`Image file not found: ${e}`);let t=await pngjsTransformer.read(e);return {data:new Uint8Array(t.data),width:t.width,height:t.height}}async function y(e,t,r,a){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true}),await pngjsTransformer.write({data:t instanceof Uint8Array?t:new Uint8Array(t),width:r,height:a},e);}function R(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t);}async function D(e){if(C(e))return W(e);if(B(e)){let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=await pngjsTransformer.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 te(e){existsSync(e)||mkdirSync(e,{recursive:true});}var $=S(()=>{u();});async function F(e,t,r,a){if(!C(e))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!C(t))throw new Error("Method 'bin' 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:a.threshold,antialiasing:a.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 re=S(()=>{u();$();});function j(e,t,r,a){let{width:n,height:o}=e,i=n*o;if(e.width!==t.width||e.height!==t.height)return {diffCount:i,diffPercentage:100};let f=r?new Uint8Array(i*4):void 0,h=diff(e.data,t.data,f,n,o,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:h,diffPercentage:h/i*100,diffOutput:f}}var oe=S(()=>{u();});function v(e,t,r,a){let{width:n,height:o}=e,i=n*o;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,o,{downsample:a.downsample}),diffOutput:f}}var ae=S(()=>{u();});function _(e,t,r,a,n){let{width:o,height:i}=e,f=o*i;if(e.width!==t.width||e.height!==t.height)return {score:0};let h=a?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,h,o,i,m);break;case "msssim":M=msssim(e.data,t.data,h,o,i,m);break;case "hitchhikers-ssim":M=hitchhikersSSIM(e.data,t.data,h,o,i,m);break;default:throw new Error(`Unknown SSIM method: ${r}`)}return {score:M,diffOutput:h}}function O(e){return e==="ssim"||e==="msssim"||e==="hitchhikers-ssim"}var q=S(()=>{u();});var ue={};ie(ue,{compareBin:()=>F,compareCore:()=>j,compareGmsd:()=>v,compareSsim:()=>_,isSsimMethod:()=>O,runComparison:()=>T,validateMethodSupportsInput:()=>L});function L(e,t){if(e==="bin"&&!C(t))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function T(e,t,r,a,n){if(L(r,e),L(r,t),r==="bin"){let m=await F(e,t,n,a);return {diffCount:m.diffCount,diffPercentage:m.diffPercentage}}let o=P(e)?e:await D(e),i=P(t)?t:await D(t),f=n!==void 0;if(O(r)){let m=_(o,i,r,f,a);return {score:m.score,diffOutput:m.diffOutput}}if(r==="gmsd"){let m=v(o,i,f,a);return {score:m.score,diffOutput:m.diffOutput}}let h=j(o,i,f,a);return {diffCount:h.diffCount,diffPercentage:h.diffPercentage,diffOutput:h.diffOutput}}var H=S(()=>{u();$();re();oe();ae();q();re();oe();ae();q();});u();H();$();u();var G={success:s.isColorSupported?"\u2714":"\u221A",error:s.isColorSupported?"\u2716":"\xD7",info:s.isColorSupported?"\u2139":"i",arrow:s.isColorSupported?"\u2514\u2500":"'-"},Oe=new Set(["ssim","msssim","hitchhikers-ssim"]);function A(e){return e.snapshotCreated?Te(e.baselinePath):e.pass?Ae():Ee(e)}function Te(e){return [`${s.green(G.success)} ${s.green("New snapshot created")}`,` ${s.dim(G.arrow)} ${s.dim(e)}`].join(`
2
+ `)}function Ae(){return `${s.green(G.success)} ${s.green("Image matches snapshot")}`}function Ee(e){let{method:t,baselinePath:r,receivedPath:a,diffPath:n,diffCount:o=0,diffPercentage:i,score:f=0,threshold:h,thresholdType:m,updateCommand:M}=e,p=[`${s.red(G.error)} ${s.red(s.bold("Image snapshot mismatch"))}`,""],g=12;if(p.push(` ${s.dim("Method".padEnd(g))}${t}`),p.push(` ${s.dim("Baseline".padEnd(g))}${s.dim(r)}`),p.push(` ${s.dim("Received".padEnd(g))}${s.dim(a)}`),p.push(` ${s.dim("Diff".padEnd(g))}${s.dim(n)}`),p.push(""),Oe.has(t)){let E=((1-f)*100).toFixed(2);p.push(` ${s.dim("SSIM Score".padEnd(g))}${s.yellow(f.toFixed(4))} ${s.dim("(1.0 = identical)")}`),p.push(` ${s.dim("Difference".padEnd(g))}${s.yellow(`${E}%`)}`);}else if(t==="gmsd")p.push(` ${s.dim("GMSD Score".padEnd(g))}${s.yellow(f.toFixed(4))} ${s.dim("(0.0 = identical)")}`);else {let E=i?.toFixed(2)??"0.00";p.push(` ${s.dim("Difference".padEnd(g))}${s.yellow(o.toLocaleString())} pixels ${s.dim(`(${E}%)`)}`);}let K=m==="percent"?"%":"pixels";return p.push(` ${s.dim("Threshold".padEnd(g))}${h} ${K}`),p.push(""),p.push(` ${s.cyan(G.info)} ${s.cyan(`Run with ${M??"--update"} to update the snapshot`)}`),p.join(`
3
+ `)}u();H();q();$();u();var x=null,Be=0,he=false,k=new Map;function We(){let e=join(I,"worker.js");if(existsSync(e))return e;let t=join(I,"../dist/worker.js");return existsSync(t)?t:null}function Ge(){if(he)return null;if(!x){let e=We();if(!e)return he=true,null;x=new Worker(e),x.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)));}),x.on("error",t=>{for(let r of k.values())r.reject(t);k.clear(),x=null;}),x.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();}x=null;});}return x}async function ne(e,t){let r=Ge();if(!r){let{runComparison:a}=await Promise.resolve().then(()=>(H(),ue)),{loadPNG:n,normalizeImageInput:o}=await Promise.resolve().then(()=>($(),me));switch(e){case "normalize":return o(t.input);case "loadPNG":return n(t.filePath);case "compare":{let i=t;return a(i.received,i.baseline,i.method,i.options,i.diffOutputPath)}default:throw new Error(`Unknown request type: ${e}`)}}return new Promise((a,n)=>{let o=++Be;k.set(o,{resolve:a,reject:n});let i={id:o,type:e,payload:t};r.postMessage(i);})}function ce(e){return ne("normalize",{input:e})}function le(e){return ne("loadPNG",{filePath:e})}function ge(e,t,r,a,n){return ne("compare",{received:e,baseline:t,method:r,options:a,diffOutputPath:n})}function Ne(){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 ve(e,t){let r=dirname(e.testPath),a=t.snapshotsDir??"__snapshots__",n=isAbsolute(a)?a:join(r,a),o=t.snapshotIdentifier??je(e);return {snapshotDir:n,baselinePath:join(n,`${o}.png`),receivedPath:join(n,`${o}.received.png`),diffPath:join(n,`${o}.diff.png`)}}function we(e,t,r){let a=r.failureThreshold??0,n=r.failureThresholdType??"pixel";if(O(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 _e(e,t,r){let a=ve(r,t),{snapshotDir:n,baselinePath:o,receivedPath:i,diffPath:f}=a,h=B(e),m=h?e:null,M=t.runInWorker!==false,p=M?ce:D,g=M?le:W,K=M?(w,l,V)=>ge(w,l,t.method,t,V):(w,l,V)=>T(w,l,t.method,t,V);te(n);let E=z(o),N=t.updateSnapshots===true?"all":t.updateSnapshots===false||t.updateSnapshots===void 0?"new":t.updateSnapshots;if(!E&&N!=="none"&&(N==="new"||N==="all")){if(m)R(o,m);else if(C(e)){let l=await g(e);await y(o,l.data,l.width,l.height);}else if(P(e))await y(o,e.data,e.width,e.height);else {let l=await p(e);await y(o,l.data,l.width,l.height);}return {pass:true,message:A({pass:true,method:t.method,snapshotCreated:true,baselinePath:o,receivedPath:i,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==="bin"?(c=await T(e,o,t.method,t,f),d=e):(d=h?await p(e):e,c=await K(P(d)?d:await p(d),o,f));let Q=we(t.method,c,t);if(Q)return existsSync(i)&&unlinkSync(i),existsSync(f)&&unlinkSync(f),{pass:true,message:A({pass:Q,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:i,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(N==="all"){if(m)R(o,m);else if(C(d)){let l=await g(d);await y(o,l.data,l.width,l.height);}else P(d)&&await y(o,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:o,receivedPath:i,diffPath:f,diffCount:0,diffPercentage:0,score:0,threshold:t.failureThreshold??0,thresholdType:t.failureThresholdType??"pixel",updateCommand:t.updateCommand}),baselinePath:o,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(c.diffOutput&&t.method!=="bin"){let w=P(d)?d:await p(d);await y(f,c.diffOutput,w.width,w.height);}return {pass:false,message:A({pass:Q,method:t.method,snapshotCreated:false,baselinePath:o,receivedPath:i,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:i,diffPath:f,snapshotStatus:"failed"}}async function qe(e,t,r){let a=await T(e,t,r.method,r),n=we(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{qe as compareImages,z as fileExists,A as formatReport,_e as getOrCreateSnapshot,C as isFilePath,fe as isImageBuffer,P as isImageData,B as isRawPngBuffer,W as loadPNG,D as normalizeImageInput,T as runComparison,y as savePNG,R as saveRawPNGBuffer,Ne as terminateWorker,L as validateMethodSupportsInput};
package/dist/worker.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var worker_threads=require('worker_threads'),fs=require('fs');require('path');var pngjsTransformer=require('@blazediff/pngjs-transformer'),bin=require('@blazediff/bin'),core=require('@blazediff/core'),gmsd=require('@blazediff/gmsd'),ssim=require('@blazediff/ssim'),hitchhikersSsim=require('@blazediff/ssim/hitchhikers-ssim'),msssim=require('@blazediff/ssim/msssim');function p(t){return typeof t=="string"}function A(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 r=await pngjsTransformer.pngjsTransformer.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}async function d(t){if(p(t))return l(t);if(A(t)){let r=Buffer.isBuffer(t)?t:Buffer.from(t),o=await pngjsTransformer.pngjsTransformer.read(r);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}}async function y(t,r,o,a){if(!p(t))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!p(r))throw new Error("Method 'bin' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let e=await bin.compare(t,r,o,{threshold:a.threshold,antialiasing:a.antialiasing});if(e.match)return {diffCount:0,diffPercentage:0};if(e.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(e.reason==="pixel-diff")return {diffCount:e.diffCount,diffPercentage:e.diffPercentage};if(e.reason==="file-not-exists")throw new Error(`Image file not found: ${e.file}`);return {diffCount:0,diffPercentage:0}}function I(t,r,o,a){let{width:e,height:i}=t,n=e*i;if(t.width!==r.width||t.height!==r.height)return {diffCount:n,diffPercentage:100};let m=o?new Uint8Array(n*4):void 0,s=core.diff(t.data,r.data,m,e,i,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:s,diffPercentage:s/n*100,diffOutput:m}}function w(t,r,o,a){let{width:e,height:i}=t,n=e*i;if(t.width!==r.width||t.height!==r.height)return {score:1};let m=o?new Uint8Array(n*4):void 0;return {score:gmsd.gmsd(t.data,r.data,m,e,i,{downsample:a.downsample}),diffOutput:m}}function P(t,r,o,a,e){let{width:i,height:n}=t,m=i*n;if(t.width!==r.width||t.height!==r.height)return {score:0};let s=a?new Uint8Array(m*4):void 0,f={windowSize:e.windowSize,k1:e.k1,k2:e.k2},c;switch(o){case "ssim":c=ssim.ssim(t.data,r.data,s,i,n,f);break;case "msssim":c=msssim.msssim(t.data,r.data,s,i,n,f);break;case "hitchhikers-ssim":c=hitchhikersSsim.hitchhikersSSIM(t.data,r.data,s,i,n,f);break;default:throw new Error(`Unknown SSIM method: ${o}`)}return {score:c,diffOutput:s}}function C(t){return t==="ssim"||t==="msssim"||t==="hitchhikers-ssim"}function M(t,r){if(t==="bin"&&!p(r))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function b(t,r,o,a,e){if(M(o,t),M(o,r),o==="bin"){let f=await y(t,r,e,a);return {diffCount:f.diffCount,diffPercentage:f.diffPercentage}}let i=g(t)?t:await d(t),n=g(r)?r:await d(r),m=e!==void 0;if(C(o)){let f=P(i,n,o,m,a);return {score:f.score,diffOutput:f.diffOutput}}if(o==="gmsd"){let f=w(i,n,m,a);return {score:f.score,diffOutput:f.diffOutput}}let s=I(i,n,m,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage,diffOutput:s.diffOutput}}async function G(t){switch(t.type){case "normalize":{let{input:r}=t.payload;return d(r)}case "loadPNG":{let{filePath:r}=t.payload;return l(r)}case "compare":{let{received:r,baseline:o,method:a,options:e,diffOutputPath:i}=t.payload;return b(r,o,a,e,i)}default:throw new Error(`Unknown request type: ${t.type}`)}}worker_threads.parentPort&&worker_threads.parentPort.on("message",async t=>{try{let r=await G(t);worker_threads.parentPort.postMessage({id:t.id,success:!0,result:r});}catch(r){worker_threads.parentPort.postMessage({id:t.id,success:false,error:r instanceof Error?r.message:String(r)});}});
@@ -0,0 +1 @@
1
+ import {parentPort}from'worker_threads';import {existsSync}from'fs';import'path';import {pngjsTransformer}from'@blazediff/pngjs-transformer';import {compare}from'@blazediff/bin';import {diff}from'@blazediff/core';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 D(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 y(t){if(!existsSync(t))throw new Error(`Image file not found: ${t}`);let r=await pngjsTransformer.read(t);return {data:new Uint8Array(r.data),width:r.width,height:r.height}}async function c(t){if(d(t))return y(t);if(D(t)){let r=Buffer.isBuffer(t)?t:Buffer.from(t),o=await pngjsTransformer.read(r);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}}async function I(t,r,o,a){if(!d(t))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");if(!d(r))throw new Error("Method 'bin' only supports file paths for baseline, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.");let e=await compare(t,r,o,{threshold:a.threshold,antialiasing:a.antialiasing});if(e.match)return {diffCount:0,diffPercentage:0};if(e.reason==="layout-diff")return {diffCount:Number.MAX_SAFE_INTEGER,diffPercentage:100};if(e.reason==="pixel-diff")return {diffCount:e.diffCount,diffPercentage:e.diffPercentage};if(e.reason==="file-not-exists")throw new Error(`Image file not found: ${e.file}`);return {diffCount:0,diffPercentage:0}}function w(t,r,o,a){let{width:e,height:i}=t,n=e*i;if(t.width!==r.width||t.height!==r.height)return {diffCount:n,diffPercentage:100};let m=o?new Uint8Array(n*4):void 0,s=diff(t.data,r.data,m,e,i,{threshold:a.threshold??.1,includeAA:a.includeAA??false});return {diffCount:s,diffPercentage:s/n*100,diffOutput:m}}function P(t,r,o,a){let{width:e,height:i}=t,n=e*i;if(t.width!==r.width||t.height!==r.height)return {score:1};let m=o?new Uint8Array(n*4):void 0;return {score:gmsd(t.data,r.data,m,e,i,{downsample:a.downsample}),diffOutput:m}}function C(t,r,o,a,e){let{width:i,height:n}=t,m=i*n;if(t.width!==r.width||t.height!==r.height)return {score:0};let s=a?new Uint8Array(m*4):void 0,f={windowSize:e.windowSize,k1:e.k1,k2:e.k2},h;switch(o){case "ssim":h=ssim(t.data,r.data,s,i,n,f);break;case "msssim":h=msssim(t.data,r.data,s,i,n,f);break;case "hitchhikers-ssim":h=hitchhikersSSIM(t.data,r.data,s,i,n,f);break;default:throw new Error(`Unknown SSIM method: ${o}`)}return {score:h,diffOutput:s}}function x(t){return t==="ssim"||t==="msssim"||t==="hitchhikers-ssim"}function b(t,r){if(t==="bin"&&!d(r))throw new Error("Method 'bin' only supports file paths, but received a buffer. Use method 'core', 'ssim', or 'gmsd' for buffer inputs.")}async function O(t,r,o,a,e){if(b(o,t),b(o,r),o==="bin"){let f=await I(t,r,e,a);return {diffCount:f.diffCount,diffPercentage:f.diffPercentage}}let i=l(t)?t:await c(t),n=l(r)?r:await c(r),m=e!==void 0;if(x(o)){let f=C(i,n,o,m,a);return {score:f.score,diffOutput:f.diffOutput}}if(o==="gmsd"){let f=P(i,n,m,a);return {score:f.score,diffOutput:f.diffOutput}}let s=w(i,n,m,a);return {diffCount:s.diffCount,diffPercentage:s.diffPercentage,diffOutput:s.diffOutput}}async function N(t){switch(t.type){case "normalize":{let{input:r}=t.payload;return c(r)}case "loadPNG":{let{filePath:r}=t.payload;return y(r)}case "compare":{let{received:r,baseline:o,method:a,options:e,diffOutputPath:i}=t.payload;return O(r,o,a,e,i)}default:throw new Error(`Unknown request type: ${t.type}`)}}parentPort&&parentPort.on("message",async t=>{try{let r=await N(t);parentPort.postMessage({id:t.id,success:!0,result:r});}catch(r){parentPort.postMessage({id:t.id,success:false,error:r instanceof Error?r.message:String(r)});}});
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@blazediff/matcher",
3
+ "version": "0.0.0-fix-testing-matcher-performance-20260223113219",
4
+ "description": "Core matcher logic for visual regression testing with blazediff",
5
+ "private": false,
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "main": "dist/index.js",
10
+ "module": "dist/index.mjs",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.mjs",
16
+ "require": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "image",
24
+ "comparison",
25
+ "diff",
26
+ "visual-testing",
27
+ "matcher",
28
+ "snapshot"
29
+ ],
30
+ "author": "Teimur Gasanov <me@teimurjan.dev> (https://github.com/teimurjan)",
31
+ "repository": "https://github.com/teimurjan/blazediff",
32
+ "homepage": "https://blazediff.dev",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "picocolors": "^1.1.1",
36
+ "@blazediff/bin": "3.5.0",
37
+ "@blazediff/core": "1.9.1",
38
+ "@blazediff/pngjs-transformer": "2.1.1",
39
+ "@blazediff/gmsd": "1.7.1",
40
+ "@blazediff/ssim": "1.7.1"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^24.3.0",
44
+ "@types/pngjs": "^6.0.5",
45
+ "@vitest/coverage-v8": "^3.2.4",
46
+ "tsup": "8.5.0",
47
+ "typescript": "5.9.2",
48
+ "vitest": "^3.2.4"
49
+ },
50
+ "scripts": {
51
+ "typecheck": "tsc --noEmit",
52
+ "build": "tsup",
53
+ "dev": "tsup --watch",
54
+ "clean": "rm -rf dist",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest",
57
+ "test:coverage": "vitest run --coverage"
58
+ }
59
+ }