@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.mjs CHANGED
@@ -1,12 +1,193 @@
1
1
  import fs from "node:fs";
2
2
  import gmsd from "@blazediff/gmsd";
3
3
  import { getLogger } from "@cappa/logger";
4
+ import { glob, readFile, writeFile } from "node:fs/promises";
4
5
  import { PNG } from "pngjs";
5
6
  import blazediff from "@blazediff/core";
6
- import { glob } from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { chromium, firefox, webkit } from "playwright-core";
9
9
 
10
+ //#region src/features/png/util.ts
11
+ const pngSignature = Buffer.from([
12
+ 137,
13
+ 80,
14
+ 78,
15
+ 71,
16
+ 13,
17
+ 10,
18
+ 26,
19
+ 10
20
+ ]);
21
+ const crcTable = new Uint32Array(256).map((_, index) => {
22
+ let c = index;
23
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
24
+ return c >>> 0;
25
+ });
26
+ /**
27
+ * Chunk Parser Generator
28
+ *
29
+ * A PNG file is essentially a list of chunks.
30
+ * Structure of a chunk:
31
+ * 1. Length (4 bytes): The size of the data field.
32
+ * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').
33
+ * 3. Data (Length bytes): The actual payload.
34
+ * 4. CRC (4 bytes): Checksum.
35
+ */
36
+ function* readChunks(buffer) {
37
+ let offset = pngSignature.length;
38
+ while (offset + 8 <= buffer.length) {
39
+ const length = buffer.readUInt32BE(offset);
40
+ const type = buffer.toString("ascii", offset + 4, offset + 8);
41
+ const dataStart = offset + 8;
42
+ const dataEnd = dataStart + length;
43
+ if (dataEnd > buffer.length) return;
44
+ yield {
45
+ type,
46
+ data: buffer.subarray(dataStart, dataEnd),
47
+ length,
48
+ offset
49
+ };
50
+ offset = dataEnd + 4;
51
+ if (type === "IEND") return;
52
+ }
53
+ }
54
+ /**
55
+ * Constructs a raw binary `tEXt` chunk.
56
+ */
57
+ function createTextChunk(key, value) {
58
+ const keyBuffer = Buffer.from(key, "latin1");
59
+ const valueBuffer = Buffer.from(value, "latin1");
60
+ const data = Buffer.concat([
61
+ keyBuffer,
62
+ Buffer.from([0]),
63
+ valueBuffer
64
+ ]);
65
+ const lengthBuffer = Buffer.alloc(4);
66
+ const typeBuffer = Buffer.from("tEXt");
67
+ lengthBuffer.writeUInt32BE(data.length, 0);
68
+ const crcBuffer = Buffer.alloc(4);
69
+ crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);
70
+ return Buffer.concat([
71
+ lengthBuffer,
72
+ typeBuffer,
73
+ data,
74
+ crcBuffer
75
+ ]);
76
+ }
77
+ /**
78
+ * Calculates the CRC32 checksum for a buffer.
79
+ * Used to ensure data integrity.
80
+ */
81
+ function crc32(buffer) {
82
+ let crc = -1;
83
+ for (let i = 0; i < buffer.length; i++) crc = crc >>> 8 ^ crcTable[(crc ^ buffer[i]) & 255];
84
+ return (crc ^ -1) >>> 0;
85
+ }
86
+ /**
87
+ * Helper to locate the IEND chunk, which marks the end of a PNG stream.
88
+ */
89
+ function findIendChunk(buffer) {
90
+ for (const chunk of readChunks(buffer)) if (chunk.type === "IEND") return chunk;
91
+ }
92
+ /**
93
+ * Inserts metadata chunks into a PNG buffer.
94
+ * It places them right before the final `IEND` chunk.
95
+ */
96
+ function injectTextMetadata(buffer, metadata) {
97
+ if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) return buffer;
98
+ const iendChunk = findIendChunk(buffer);
99
+ if (!iendChunk) return buffer;
100
+ const textChunks = Object.entries(metadata).map(([key, value]) => createTextChunk(key, value));
101
+ return Buffer.concat([
102
+ buffer.subarray(0, iendChunk.offset),
103
+ ...textChunks,
104
+ buffer.subarray(iendChunk.offset)
105
+ ]);
106
+ }
107
+ /**
108
+ * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.
109
+ */
110
+ function extractTextMetadata(buffer) {
111
+ if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) return {};
112
+ const metadata = {};
113
+ for (const chunk of readChunks(buffer)) {
114
+ if (chunk.type !== "tEXt") continue;
115
+ const separatorIndex = chunk.data.indexOf(0);
116
+ if (separatorIndex < 0) continue;
117
+ const key = chunk.data.toString("latin1", 0, separatorIndex);
118
+ metadata[key] = chunk.data.toString("latin1", separatorIndex + 1);
119
+ }
120
+ return metadata;
121
+ }
122
+
123
+ //#endregion
124
+ //#region src/features/png/png.ts
125
+ /**
126
+ * A wrapper around `pngjs` that adds support for reading and writing
127
+ * textual metadata (tEXt chunks).
128
+ */
129
+ var PNG$1 = class PNG$1 {
130
+ image;
131
+ sourcePath;
132
+ metadataEntries;
133
+ constructor(image, sourcePath, metadata) {
134
+ this.image = image;
135
+ this.sourcePath = sourcePath;
136
+ this.metadataEntries = { ...metadata ?? {} };
137
+ }
138
+ static create(width, height) {
139
+ return new PNG$1(new PNG({
140
+ width,
141
+ height
142
+ }));
143
+ }
144
+ static async load(source) {
145
+ const buffer = typeof source === "string" ? await readFile(source) : source;
146
+ const png = PNG.sync.read(buffer);
147
+ const metadata = extractTextMetadata(buffer);
148
+ return new PNG$1(png, typeof source === "string" ? source : void 0, metadata);
149
+ }
150
+ get width() {
151
+ return this.image.width;
152
+ }
153
+ get height() {
154
+ return this.image.height;
155
+ }
156
+ get data() {
157
+ return this.image.data;
158
+ }
159
+ get metadata() {
160
+ return { ...this.metadataEntries };
161
+ }
162
+ setMetadata(key, value) {
163
+ this.metadataEntries = {
164
+ ...this.metadataEntries,
165
+ [key]: value
166
+ };
167
+ }
168
+ replaceMetadata(metadata) {
169
+ this.metadataEntries = { ...metadata };
170
+ }
171
+ removeMetadata(key) {
172
+ const { [key]: _, ...remaining } = this.metadataEntries;
173
+ this.metadataEntries = remaining;
174
+ }
175
+ clearMetadata() {
176
+ this.metadataEntries = {};
177
+ }
178
+ toBuffer(options) {
179
+ const baseBuffer = PNG.sync.write(this.image, options);
180
+ if (Object.keys(this.metadataEntries).length === 0) return baseBuffer;
181
+ return injectTextMetadata(baseBuffer, this.metadataEntries);
182
+ }
183
+ async save(filepath, options) {
184
+ const targetPath = filepath ?? this.sourcePath;
185
+ if (!targetPath) throw new Error("No filepath provided for saving PNG");
186
+ await writeFile(targetPath, this.toBuffer(options));
187
+ }
188
+ };
189
+
190
+ //#endregion
10
191
  //#region src/compare/gmsd.ts
11
192
  const compare$1 = (image1, image2, diff, width, height, options) => {
12
193
  return gmsd(image1, image2, diff, width, height, options);
@@ -23,10 +204,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
23
204
  const png1 = await loadPNG$1(image1);
24
205
  const png2 = await loadPNG$1(image2);
25
206
  const { width, height } = png1;
26
- const diff = withDiff ? new PNG({
27
- width,
28
- height
29
- }) : void 0;
207
+ const diff = withDiff ? PNG$1.create(width, height) : void 0;
30
208
  try {
31
209
  const gmsd$1 = compare$1(png1.data, png2.data, diff?.data, width, height, {
32
210
  downsample: options.downsample ?? 0,
@@ -34,7 +212,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
34
212
  });
35
213
  return {
36
214
  gmsd: gmsd$1,
37
- diffBuffer: diff ? PNG.sync.write(diff) : void 0,
215
+ diffBuffer: diff ? annotateDiffImage$1(diff, options).toBuffer() : void 0,
38
216
  passed: gmsd$1 <= (options.threshold ?? .1)
39
217
  };
40
218
  } catch (error) {
@@ -50,11 +228,15 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
50
228
  * Load a PNG image from file path or Buffer
51
229
  */
52
230
  async function loadPNG$1(source) {
53
- if (Buffer.isBuffer(source)) return PNG.sync.read(source);
54
- else {
55
- const buffer = fs.readFileSync(source);
56
- return PNG.sync.read(buffer);
231
+ return PNG$1.load(source);
232
+ }
233
+ function annotateDiffImage$1(image, options) {
234
+ image.setMetadata("cappa.diff.algorithm", "gmsd");
235
+ for (const [key, value] of Object.entries(options)) {
236
+ if (value === void 0) continue;
237
+ image.setMetadata(`cappa.diff.${key}`, String(value));
57
238
  }
239
+ return image;
58
240
  }
59
241
  /**
60
242
  * Quick comparison function that returns only pass/fail
@@ -91,10 +273,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
91
273
  passed: false,
92
274
  differentSizes: true
93
275
  };
94
- const diff = withDiff ? new PNG({
95
- width,
96
- height
97
- }) : void 0;
276
+ const diff = withDiff ? PNG$1.create(width, height) : void 0;
98
277
  try {
99
278
  const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
100
279
  const totalPixels = width * height;
@@ -103,7 +282,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
103
282
  numDiffPixels,
104
283
  totalPixels,
105
284
  percentDifference,
106
- diffBuffer: diff ? PNG.sync.write(diff) : void 0,
285
+ diffBuffer: diff ? annotateDiffImage(diff, options).toBuffer() : void 0,
107
286
  passed: isPassed(percentDifference, numDiffPixels, options),
108
287
  differentSizes: false
109
288
  };
@@ -123,11 +302,15 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
123
302
  * Load a PNG image from file path or Buffer
124
303
  */
125
304
  async function loadPNG(source) {
126
- if (Buffer.isBuffer(source)) return PNG.sync.read(source);
127
- else {
128
- const buffer = fs.readFileSync(source);
129
- return PNG.sync.read(buffer);
305
+ return PNG$1.load(source);
306
+ }
307
+ function annotateDiffImage(image, options) {
308
+ image.setMetadata("cappa.diff.algorithm", "pixel");
309
+ for (const [key, value] of Object.entries(options)) {
310
+ if (value === void 0) continue;
311
+ image.setMetadata(`cappa.diff.${key}`, String(value));
130
312
  }
313
+ return image;
131
314
  }
132
315
  /**
133
316
  * Quick comparison function that returns only pass/fail
@@ -157,10 +340,7 @@ const isPassed = (percentDifference, numDiffPixels, options) => {
157
340
  * @returns
158
341
  */
159
342
  function createDiffSizePngImage(width, height) {
160
- const png = new PNG({
161
- width,
162
- height
163
- });
343
+ const png = PNG$1.create(width, height);
164
344
  for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
165
345
  const idx = width * y + x << 2;
166
346
  png.data[idx] = 255;
@@ -168,7 +348,7 @@ function createDiffSizePngImage(width, height) {
168
348
  png.data[idx + 2] = 0;
169
349
  png.data[idx + 3] = 255;
170
350
  }
171
- return PNG.sync.write(png);
351
+ return png.toBuffer();
172
352
  }
173
353
 
174
354
  //#endregion
@@ -247,13 +427,31 @@ var ScreenshotFileSystem = class {
247
427
  const diffPath = path.resolve(this.diff, relativePath);
248
428
  this.ensureParentDir(expectedPath);
249
429
  fs.copyFileSync(actualPath, expectedPath);
250
- if (fs.existsSync(diffPath)) fs.unlinkSync(diffPath);
430
+ if (fs.existsSync(diffPath)) {
431
+ this.copyDiffMetadataToExpected(diffPath, expectedPath);
432
+ fs.unlinkSync(diffPath);
433
+ }
251
434
  return {
252
435
  actualPath,
253
436
  expectedPath,
254
437
  diffPath
255
438
  };
256
439
  }
440
+ copyDiffMetadataToExpected(diffPath, expectedPath) {
441
+ const diffExtension = path.extname(diffPath).toLowerCase();
442
+ const expectedExtension = path.extname(expectedPath).toLowerCase();
443
+ if (diffExtension !== ".png" || expectedExtension !== ".png") return;
444
+ try {
445
+ const diffMetadata = extractTextMetadata(fs.readFileSync(diffPath));
446
+ if (Object.keys(diffMetadata).length === 0) return;
447
+ const expectedBuffer = fs.readFileSync(expectedPath);
448
+ const expectedWithMetadata = injectTextMetadata(expectedBuffer, {
449
+ ...extractTextMetadata(expectedBuffer),
450
+ ...diffMetadata
451
+ });
452
+ fs.writeFileSync(expectedPath, expectedWithMetadata);
453
+ } catch {}
454
+ }
257
455
  /**
258
456
  * Ensure the parent directory of a file exists. If not, it creates it.
259
457
  * @param filePath - The path to the file.
@@ -513,7 +711,7 @@ var ScreenshotTool = class {
513
711
  throw error;
514
712
  }
515
713
  }
516
- async takeScreenshotWithComparison(page, filename, referenceImage, options) {
714
+ async takeScreenshotWithComparison(page, filename, referenceImage, options, diffOverride) {
517
715
  if (!this.browser) throw new Error("Browser not initialized");
518
716
  try {
519
717
  const filepath = this.filesystem.getActualFilePath(filename);
@@ -524,7 +722,7 @@ var ScreenshotTool = class {
524
722
  delay: options.delay,
525
723
  viewport: options.viewport
526
724
  };
527
- const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings);
725
+ const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings, diffOverride);
528
726
  if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
529
727
  this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
530
728
  this.logger.debug(`Actual screenshot saved: ${filepath}`);
@@ -555,14 +753,18 @@ var ScreenshotTool = class {
555
753
  throw error;
556
754
  }
557
755
  }
558
- async retryScreenshot(page, referenceImage, options) {
756
+ async retryScreenshot(page, referenceImage, options, diffOverride) {
757
+ const diffConfig = diffOverride ? {
758
+ ...this.diff,
759
+ ...diffOverride
760
+ } : this.diff;
559
761
  for (let i = 0; i < this.retries; i++) try {
560
762
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
561
763
  ...options,
562
764
  delay: this.getIncBackoffDelay(i, options.delay || 0)
563
765
  });
564
766
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
565
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, this.diff);
767
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, diffConfig);
566
768
  if (comparisonResult.differentSizes) return {
567
769
  screenshotPath: screenshotBuffer,
568
770
  comparisonResult,
@@ -610,6 +812,7 @@ var ScreenshotTool = class {
610
812
  }
611
813
  const saveDiff = extras.saveDiffImage ?? false;
612
814
  const diffFilename = extras.diffImageFilename ?? filename;
815
+ const diffOverride = extras.diff;
613
816
  if (!this.filesystem.hasExpectedFile(filename)) {
614
817
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
615
818
  result.filepath = await this.takeScreenshot(page, filename, options);
@@ -618,7 +821,7 @@ var ScreenshotTool = class {
618
821
  ...options,
619
822
  saveDiffImage: saveDiff,
620
823
  diffImageFilename: diffFilename
621
- });
824
+ }, diffOverride);
622
825
  result.filepath = screenshotPath;
623
826
  result.comparisonResult = comparisonResult;
624
827
  result.diffImagePath = diffImagePath;
@@ -632,6 +835,7 @@ var ScreenshotTool = class {
632
835
  const variantResults = [];
633
836
  const baseSaveDiff = extras.saveDiffImage ?? false;
634
837
  const baseDiffFilename = extras.diffImageFilename ?? filename;
838
+ const baseDiffOverride = extras.diff;
635
839
  if (baseOptions.skip) return {
636
840
  base: {
637
841
  ...baseResult,
@@ -646,7 +850,8 @@ var ScreenshotTool = class {
646
850
  };
647
851
  const baseCaptureResult = await this.captureSingleScreenshot(page, filename, baseOptions, {
648
852
  saveDiffImage: baseSaveDiff,
649
- diffImageFilename: baseDiffFilename
853
+ diffImageFilename: baseDiffFilename,
854
+ diff: baseDiffOverride
650
855
  });
651
856
  baseResult.filepath = baseCaptureResult.filepath;
652
857
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -671,9 +876,11 @@ var ScreenshotTool = class {
671
876
  const variantExtra = extras.variants?.[variant.id];
672
877
  const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
673
878
  const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
879
+ const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;
674
880
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
675
881
  saveDiffImage: variantSaveDiff,
676
- diffImageFilename: variantDiffFilename
882
+ diffImageFilename: variantDiffFilename,
883
+ diff: variantDiffOverride
677
884
  });
678
885
  variantResult.filepath = variantCaptureResult.filepath;
679
886
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;
@@ -721,12 +928,14 @@ var ScreenshotTool = class {
721
928
  const variantResults = [];
722
929
  const baseSaveDiff = extras.saveDiffImage ?? false;
723
930
  const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
931
+ const baseDiffOverride = extras.diff;
724
932
  getLogger().debug(`Going to base URL: ${baseUrl}`);
725
933
  await page.goto(baseUrl);
726
934
  await this.applyScreenshotOptimizations(page);
727
935
  const baseCaptureResult = await this.captureSingleScreenshot(page, baseFilename, baseOptions, {
728
936
  saveDiffImage: baseSaveDiff,
729
- diffImageFilename: baseDiffFilename
937
+ diffImageFilename: baseDiffFilename,
938
+ diff: baseDiffOverride
730
939
  });
731
940
  baseResult.filepath = baseCaptureResult.filepath;
732
941
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -754,9 +963,11 @@ var ScreenshotTool = class {
754
963
  const variantExtra = extras.variants?.[variant.id];
755
964
  const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
756
965
  const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
966
+ const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;
757
967
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
758
968
  saveDiffImage: variantSaveDiff,
759
- diffImageFilename: variantDiffFilename
969
+ diffImageFilename: variantDiffFilename,
970
+ diff: variantDiffOverride
760
971
  });
761
972
  variantResult.filepath = variantCaptureResult.filepath;
762
973
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;