@cappa/core 0.4.7 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,14 +30,195 @@ node_fs = __toESM(node_fs);
30
30
  let _blazediff_gmsd = require("@blazediff/gmsd");
31
31
  _blazediff_gmsd = __toESM(_blazediff_gmsd);
32
32
  let _cappa_logger = require("@cappa/logger");
33
+ let node_fs_promises = require("node:fs/promises");
33
34
  let pngjs = require("pngjs");
34
35
  let _blazediff_core = require("@blazediff/core");
35
36
  _blazediff_core = __toESM(_blazediff_core);
36
- let node_fs_promises = require("node:fs/promises");
37
37
  let node_path = require("node:path");
38
38
  node_path = __toESM(node_path);
39
39
  let playwright_core = require("playwright-core");
40
40
 
41
+ //#region src/features/png/util.ts
42
+ const pngSignature = Buffer.from([
43
+ 137,
44
+ 80,
45
+ 78,
46
+ 71,
47
+ 13,
48
+ 10,
49
+ 26,
50
+ 10
51
+ ]);
52
+ const crcTable = new Uint32Array(256).map((_, index) => {
53
+ let c = index;
54
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
55
+ return c >>> 0;
56
+ });
57
+ /**
58
+ * Chunk Parser Generator
59
+ *
60
+ * A PNG file is essentially a list of chunks.
61
+ * Structure of a chunk:
62
+ * 1. Length (4 bytes): The size of the data field.
63
+ * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').
64
+ * 3. Data (Length bytes): The actual payload.
65
+ * 4. CRC (4 bytes): Checksum.
66
+ */
67
+ function* readChunks(buffer) {
68
+ let offset = pngSignature.length;
69
+ while (offset + 8 <= buffer.length) {
70
+ const length = buffer.readUInt32BE(offset);
71
+ const type = buffer.toString("ascii", offset + 4, offset + 8);
72
+ const dataStart = offset + 8;
73
+ const dataEnd = dataStart + length;
74
+ if (dataEnd > buffer.length) return;
75
+ yield {
76
+ type,
77
+ data: buffer.subarray(dataStart, dataEnd),
78
+ length,
79
+ offset
80
+ };
81
+ offset = dataEnd + 4;
82
+ if (type === "IEND") return;
83
+ }
84
+ }
85
+ /**
86
+ * Constructs a raw binary `tEXt` chunk.
87
+ */
88
+ function createTextChunk(key, value) {
89
+ const keyBuffer = Buffer.from(key, "latin1");
90
+ const valueBuffer = Buffer.from(value, "latin1");
91
+ const data = Buffer.concat([
92
+ keyBuffer,
93
+ Buffer.from([0]),
94
+ valueBuffer
95
+ ]);
96
+ const lengthBuffer = Buffer.alloc(4);
97
+ const typeBuffer = Buffer.from("tEXt");
98
+ lengthBuffer.writeUInt32BE(data.length, 0);
99
+ const crcBuffer = Buffer.alloc(4);
100
+ crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);
101
+ return Buffer.concat([
102
+ lengthBuffer,
103
+ typeBuffer,
104
+ data,
105
+ crcBuffer
106
+ ]);
107
+ }
108
+ /**
109
+ * Calculates the CRC32 checksum for a buffer.
110
+ * Used to ensure data integrity.
111
+ */
112
+ function crc32(buffer) {
113
+ let crc = -1;
114
+ for (let i = 0; i < buffer.length; i++) crc = crc >>> 8 ^ crcTable[(crc ^ buffer[i]) & 255];
115
+ return (crc ^ -1) >>> 0;
116
+ }
117
+ /**
118
+ * Helper to locate the IEND chunk, which marks the end of a PNG stream.
119
+ */
120
+ function findIendChunk(buffer) {
121
+ for (const chunk of readChunks(buffer)) if (chunk.type === "IEND") return chunk;
122
+ }
123
+ /**
124
+ * Inserts metadata chunks into a PNG buffer.
125
+ * It places them right before the final `IEND` chunk.
126
+ */
127
+ function injectTextMetadata(buffer, metadata) {
128
+ if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) return buffer;
129
+ const iendChunk = findIendChunk(buffer);
130
+ if (!iendChunk) return buffer;
131
+ const textChunks = Object.entries(metadata).map(([key, value]) => createTextChunk(key, value));
132
+ return Buffer.concat([
133
+ buffer.subarray(0, iendChunk.offset),
134
+ ...textChunks,
135
+ buffer.subarray(iendChunk.offset)
136
+ ]);
137
+ }
138
+ /**
139
+ * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.
140
+ */
141
+ function extractTextMetadata(buffer) {
142
+ if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) return {};
143
+ const metadata = {};
144
+ for (const chunk of readChunks(buffer)) {
145
+ if (chunk.type !== "tEXt") continue;
146
+ const separatorIndex = chunk.data.indexOf(0);
147
+ if (separatorIndex < 0) continue;
148
+ const key = chunk.data.toString("latin1", 0, separatorIndex);
149
+ metadata[key] = chunk.data.toString("latin1", separatorIndex + 1);
150
+ }
151
+ return metadata;
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/features/png/png.ts
156
+ /**
157
+ * A wrapper around `pngjs` that adds support for reading and writing
158
+ * textual metadata (tEXt chunks).
159
+ */
160
+ var PNG = class PNG {
161
+ image;
162
+ sourcePath;
163
+ metadataEntries;
164
+ constructor(image, sourcePath, metadata) {
165
+ this.image = image;
166
+ this.sourcePath = sourcePath;
167
+ this.metadataEntries = { ...metadata ?? {} };
168
+ }
169
+ static create(width, height) {
170
+ return new PNG(new pngjs.PNG({
171
+ width,
172
+ height
173
+ }));
174
+ }
175
+ static async load(source) {
176
+ const buffer = typeof source === "string" ? await (0, node_fs_promises.readFile)(source) : source;
177
+ const png = pngjs.PNG.sync.read(buffer);
178
+ const metadata = extractTextMetadata(buffer);
179
+ return new PNG(png, typeof source === "string" ? source : void 0, metadata);
180
+ }
181
+ get width() {
182
+ return this.image.width;
183
+ }
184
+ get height() {
185
+ return this.image.height;
186
+ }
187
+ get data() {
188
+ return this.image.data;
189
+ }
190
+ get metadata() {
191
+ return { ...this.metadataEntries };
192
+ }
193
+ setMetadata(key, value) {
194
+ this.metadataEntries = {
195
+ ...this.metadataEntries,
196
+ [key]: value
197
+ };
198
+ }
199
+ replaceMetadata(metadata) {
200
+ this.metadataEntries = { ...metadata };
201
+ }
202
+ removeMetadata(key) {
203
+ const { [key]: _, ...remaining } = this.metadataEntries;
204
+ this.metadataEntries = remaining;
205
+ }
206
+ clearMetadata() {
207
+ this.metadataEntries = {};
208
+ }
209
+ toBuffer(options) {
210
+ const baseBuffer = pngjs.PNG.sync.write(this.image, options);
211
+ if (Object.keys(this.metadataEntries).length === 0) return baseBuffer;
212
+ return injectTextMetadata(baseBuffer, this.metadataEntries);
213
+ }
214
+ async save(filepath, options) {
215
+ const targetPath = filepath ?? this.sourcePath;
216
+ if (!targetPath) throw new Error("No filepath provided for saving PNG");
217
+ await (0, node_fs_promises.writeFile)(targetPath, this.toBuffer(options));
218
+ }
219
+ };
220
+
221
+ //#endregion
41
222
  //#region src/compare/gmsd.ts
42
223
  const compare$1 = (image1, image2, diff, width, height, options) => {
43
224
  return (0, _blazediff_gmsd.default)(image1, image2, diff, width, height, options);
@@ -54,10 +235,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
54
235
  const png1 = await loadPNG$1(image1);
55
236
  const png2 = await loadPNG$1(image2);
56
237
  const { width, height } = png1;
57
- const diff = withDiff ? new pngjs.PNG({
58
- width,
59
- height
60
- }) : void 0;
238
+ const diff = withDiff ? PNG.create(width, height) : void 0;
61
239
  try {
62
240
  const gmsd$1 = compare$1(png1.data, png2.data, diff?.data, width, height, {
63
241
  downsample: options.downsample ?? 0,
@@ -65,7 +243,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
65
243
  });
66
244
  return {
67
245
  gmsd: gmsd$1,
68
- diffBuffer: diff ? pngjs.PNG.sync.write(diff) : void 0,
246
+ diffBuffer: diff ? annotateDiffImage$1(diff, options).toBuffer() : void 0,
69
247
  passed: gmsd$1 <= (options.threshold ?? .1)
70
248
  };
71
249
  } catch (error) {
@@ -81,11 +259,15 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
81
259
  * Load a PNG image from file path or Buffer
82
260
  */
83
261
  async function loadPNG$1(source) {
84
- if (Buffer.isBuffer(source)) return pngjs.PNG.sync.read(source);
85
- else {
86
- const buffer = node_fs.default.readFileSync(source);
87
- return pngjs.PNG.sync.read(buffer);
262
+ return PNG.load(source);
263
+ }
264
+ function annotateDiffImage$1(image, options) {
265
+ image.setMetadata("cappa.diff.algorithm", "gmsd");
266
+ for (const [key, value] of Object.entries(options)) {
267
+ if (value === void 0) continue;
268
+ image.setMetadata(`cappa.diff.${key}`, String(value));
88
269
  }
270
+ return image;
89
271
  }
90
272
  /**
91
273
  * Quick comparison function that returns only pass/fail
@@ -122,10 +304,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
122
304
  passed: false,
123
305
  differentSizes: true
124
306
  };
125
- const diff = withDiff ? new pngjs.PNG({
126
- width,
127
- height
128
- }) : void 0;
307
+ const diff = withDiff ? PNG.create(width, height) : void 0;
129
308
  try {
130
309
  const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
131
310
  const totalPixels = width * height;
@@ -134,7 +313,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
134
313
  numDiffPixels,
135
314
  totalPixels,
136
315
  percentDifference,
137
- diffBuffer: diff ? pngjs.PNG.sync.write(diff) : void 0,
316
+ diffBuffer: diff ? annotateDiffImage(diff, options).toBuffer() : void 0,
138
317
  passed: isPassed(percentDifference, numDiffPixels, options),
139
318
  differentSizes: false
140
319
  };
@@ -154,11 +333,15 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
154
333
  * Load a PNG image from file path or Buffer
155
334
  */
156
335
  async function loadPNG(source) {
157
- if (Buffer.isBuffer(source)) return pngjs.PNG.sync.read(source);
158
- else {
159
- const buffer = node_fs.default.readFileSync(source);
160
- return pngjs.PNG.sync.read(buffer);
336
+ return PNG.load(source);
337
+ }
338
+ function annotateDiffImage(image, options) {
339
+ image.setMetadata("cappa.diff.algorithm", "pixel");
340
+ for (const [key, value] of Object.entries(options)) {
341
+ if (value === void 0) continue;
342
+ image.setMetadata(`cappa.diff.${key}`, String(value));
161
343
  }
344
+ return image;
162
345
  }
163
346
  /**
164
347
  * Quick comparison function that returns only pass/fail
@@ -188,10 +371,7 @@ const isPassed = (percentDifference, numDiffPixels, options) => {
188
371
  * @returns
189
372
  */
190
373
  function createDiffSizePngImage(width, height) {
191
- const png = new pngjs.PNG({
192
- width,
193
- height
194
- });
374
+ const png = PNG.create(width, height);
195
375
  for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
196
376
  const idx = width * y + x << 2;
197
377
  png.data[idx] = 255;
@@ -199,7 +379,7 @@ function createDiffSizePngImage(width, height) {
199
379
  png.data[idx + 2] = 0;
200
380
  png.data[idx + 3] = 255;
201
381
  }
202
- return pngjs.PNG.sync.write(png);
382
+ return png.toBuffer();
203
383
  }
204
384
 
205
385
  //#endregion
@@ -278,13 +458,31 @@ var ScreenshotFileSystem = class {
278
458
  const diffPath = node_path.default.resolve(this.diff, relativePath);
279
459
  this.ensureParentDir(expectedPath);
280
460
  node_fs.default.copyFileSync(actualPath, expectedPath);
281
- if (node_fs.default.existsSync(diffPath)) node_fs.default.unlinkSync(diffPath);
461
+ if (node_fs.default.existsSync(diffPath)) {
462
+ this.copyDiffMetadataToExpected(diffPath, expectedPath);
463
+ node_fs.default.unlinkSync(diffPath);
464
+ }
282
465
  return {
283
466
  actualPath,
284
467
  expectedPath,
285
468
  diffPath
286
469
  };
287
470
  }
471
+ copyDiffMetadataToExpected(diffPath, expectedPath) {
472
+ const diffExtension = node_path.default.extname(diffPath).toLowerCase();
473
+ const expectedExtension = node_path.default.extname(expectedPath).toLowerCase();
474
+ if (diffExtension !== ".png" || expectedExtension !== ".png") return;
475
+ try {
476
+ const diffMetadata = extractTextMetadata(node_fs.default.readFileSync(diffPath));
477
+ if (Object.keys(diffMetadata).length === 0) return;
478
+ const expectedBuffer = node_fs.default.readFileSync(expectedPath);
479
+ const expectedWithMetadata = injectTextMetadata(expectedBuffer, {
480
+ ...extractTextMetadata(expectedBuffer),
481
+ ...diffMetadata
482
+ });
483
+ node_fs.default.writeFileSync(expectedPath, expectedWithMetadata);
484
+ } catch {}
485
+ }
288
486
  /**
289
487
  * Ensure the parent directory of a file exists. If not, it creates it.
290
488
  * @param filePath - The path to the file.
@@ -544,7 +742,7 @@ var ScreenshotTool = class {
544
742
  throw error;
545
743
  }
546
744
  }
547
- async takeScreenshotWithComparison(page, filename, referenceImage, options) {
745
+ async takeScreenshotWithComparison(page, filename, referenceImage, options, diffOverride) {
548
746
  if (!this.browser) throw new Error("Browser not initialized");
549
747
  try {
550
748
  const filepath = this.filesystem.getActualFilePath(filename);
@@ -555,7 +753,7 @@ var ScreenshotTool = class {
555
753
  delay: options.delay,
556
754
  viewport: options.viewport
557
755
  };
558
- const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings);
756
+ const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings, diffOverride);
559
757
  if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
560
758
  this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
561
759
  this.logger.debug(`Actual screenshot saved: ${filepath}`);
@@ -586,14 +784,18 @@ var ScreenshotTool = class {
586
784
  throw error;
587
785
  }
588
786
  }
589
- async retryScreenshot(page, referenceImage, options) {
787
+ async retryScreenshot(page, referenceImage, options, diffOverride) {
788
+ const diffConfig = diffOverride ? {
789
+ ...this.diff,
790
+ ...diffOverride
791
+ } : this.diff;
590
792
  for (let i = 0; i < this.retries; i++) try {
591
793
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
592
794
  ...options,
593
795
  delay: this.getIncBackoffDelay(i, options.delay || 0)
594
796
  });
595
797
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
596
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, this.diff);
798
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, diffConfig);
597
799
  if (comparisonResult.differentSizes) return {
598
800
  screenshotPath: screenshotBuffer,
599
801
  comparisonResult,
@@ -641,6 +843,7 @@ var ScreenshotTool = class {
641
843
  }
642
844
  const saveDiff = extras.saveDiffImage ?? false;
643
845
  const diffFilename = extras.diffImageFilename ?? filename;
846
+ const diffOverride = extras.diff;
644
847
  if (!this.filesystem.hasExpectedFile(filename)) {
645
848
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
646
849
  result.filepath = await this.takeScreenshot(page, filename, options);
@@ -649,7 +852,7 @@ var ScreenshotTool = class {
649
852
  ...options,
650
853
  saveDiffImage: saveDiff,
651
854
  diffImageFilename: diffFilename
652
- });
855
+ }, diffOverride);
653
856
  result.filepath = screenshotPath;
654
857
  result.comparisonResult = comparisonResult;
655
858
  result.diffImagePath = diffImagePath;
@@ -663,6 +866,7 @@ var ScreenshotTool = class {
663
866
  const variantResults = [];
664
867
  const baseSaveDiff = extras.saveDiffImage ?? false;
665
868
  const baseDiffFilename = extras.diffImageFilename ?? filename;
869
+ const baseDiffOverride = extras.diff;
666
870
  if (baseOptions.skip) return {
667
871
  base: {
668
872
  ...baseResult,
@@ -677,7 +881,8 @@ var ScreenshotTool = class {
677
881
  };
678
882
  const baseCaptureResult = await this.captureSingleScreenshot(page, filename, baseOptions, {
679
883
  saveDiffImage: baseSaveDiff,
680
- diffImageFilename: baseDiffFilename
884
+ diffImageFilename: baseDiffFilename,
885
+ diff: baseDiffOverride
681
886
  });
682
887
  baseResult.filepath = baseCaptureResult.filepath;
683
888
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -702,9 +907,11 @@ var ScreenshotTool = class {
702
907
  const variantExtra = extras.variants?.[variant.id];
703
908
  const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
704
909
  const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
910
+ const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;
705
911
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
706
912
  saveDiffImage: variantSaveDiff,
707
- diffImageFilename: variantDiffFilename
913
+ diffImageFilename: variantDiffFilename,
914
+ diff: variantDiffOverride
708
915
  });
709
916
  variantResult.filepath = variantCaptureResult.filepath;
710
917
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;
@@ -752,12 +959,14 @@ var ScreenshotTool = class {
752
959
  const variantResults = [];
753
960
  const baseSaveDiff = extras.saveDiffImage ?? false;
754
961
  const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
962
+ const baseDiffOverride = extras.diff;
755
963
  (0, _cappa_logger.getLogger)().debug(`Going to base URL: ${baseUrl}`);
756
964
  await page.goto(baseUrl);
757
965
  await this.applyScreenshotOptimizations(page);
758
966
  const baseCaptureResult = await this.captureSingleScreenshot(page, baseFilename, baseOptions, {
759
967
  saveDiffImage: baseSaveDiff,
760
- diffImageFilename: baseDiffFilename
968
+ diffImageFilename: baseDiffFilename,
969
+ diff: baseDiffOverride
761
970
  });
762
971
  baseResult.filepath = baseCaptureResult.filepath;
763
972
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -785,9 +994,11 @@ var ScreenshotTool = class {
785
994
  const variantExtra = extras.variants?.[variant.id];
786
995
  const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
787
996
  const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
997
+ const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;
788
998
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
789
999
  saveDiffImage: variantSaveDiff,
790
- diffImageFilename: variantDiffFilename
1000
+ diffImageFilename: variantDiffFilename,
1001
+ diff: variantDiffOverride
791
1002
  });
792
1003
  variantResult.filepath = variantCaptureResult.filepath;
793
1004
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;