@cappa/core 0.7.0 → 0.7.2

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
@@ -27,7 +27,9 @@ let _blazediff_gmsd = require("@blazediff/gmsd");
27
27
  _blazediff_gmsd = __toESM(_blazediff_gmsd);
28
28
  let _cappa_logger = require("@cappa/logger");
29
29
  let node_fs_promises = require("node:fs/promises");
30
- let pngjs = require("pngjs");
30
+ node_fs_promises = __toESM(node_fs_promises);
31
+ let sharp = require("sharp");
32
+ sharp = __toESM(sharp);
31
33
  let _blazediff_core = require("@blazediff/core");
32
34
  _blazediff_core = __toESM(_blazediff_core);
33
35
  let node_path = require("node:path");
@@ -148,38 +150,41 @@ function extractTextMetadata(buffer) {
148
150
  //#endregion
149
151
  //#region src/features/png/png.ts
150
152
  /**
151
- * A wrapper around `pngjs` that adds support for reading and writing
152
- * textual metadata (tEXt chunks).
153
+ * A wrapper around `sharp` that adds support for reading and writing
154
+ * textual metadata (tEXt chunks). Used for fast PNG decode/encode.
153
155
  */
154
156
  var PNG = class PNG {
155
- image;
157
+ width_;
158
+ height_;
159
+ data_;
156
160
  sourcePath;
157
161
  metadataEntries;
158
- constructor(image, sourcePath, metadata) {
159
- this.image = image;
162
+ constructor(width, height, data, sourcePath, metadata) {
163
+ this.width_ = width;
164
+ this.height_ = height;
165
+ this.data_ = data;
160
166
  this.sourcePath = sourcePath;
161
167
  this.metadataEntries = { ...metadata ?? {} };
162
168
  }
163
169
  static create(width, height) {
164
- return new PNG(new pngjs.PNG({
165
- width,
166
- height
167
- }));
170
+ return new PNG(width, height, Buffer.alloc(width * height * 4, 0));
168
171
  }
169
172
  static async load(source) {
170
173
  const buffer = typeof source === "string" ? await (0, node_fs_promises.readFile)(source) : source;
171
- const png = pngjs.PNG.sync.read(buffer);
172
174
  const metadata = extractTextMetadata(buffer);
173
- return new PNG(png, typeof source === "string" ? source : void 0, metadata);
175
+ const { data: raw, info } = await (0, sharp.default)(buffer).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
176
+ const data = Buffer.from(raw);
177
+ const sourcePath = typeof source === "string" ? source : void 0;
178
+ return new PNG(info.width, info.height, data, sourcePath, metadata);
174
179
  }
175
180
  get width() {
176
- return this.image.width;
181
+ return this.width_;
177
182
  }
178
183
  get height() {
179
- return this.image.height;
184
+ return this.height_;
180
185
  }
181
186
  get data() {
182
- return this.image.data;
187
+ return this.data_;
183
188
  }
184
189
  get metadata() {
185
190
  return { ...this.metadataEntries };
@@ -200,15 +205,19 @@ var PNG = class PNG {
200
205
  clearMetadata() {
201
206
  this.metadataEntries = {};
202
207
  }
203
- toBuffer(options) {
204
- const baseBuffer = pngjs.PNG.sync.write(this.image, options);
208
+ async toBuffer() {
209
+ const baseBuffer = await (0, sharp.default)(this.data_, { raw: {
210
+ width: this.width_,
211
+ height: this.height_,
212
+ channels: 4
213
+ } }).png().toBuffer();
205
214
  if (Object.keys(this.metadataEntries).length === 0) return baseBuffer;
206
215
  return injectTextMetadata(baseBuffer, this.metadataEntries);
207
216
  }
208
- async save(filepath, options) {
217
+ async save(filepath) {
209
218
  const targetPath = filepath ?? this.sourcePath;
210
219
  if (!targetPath) throw new Error("No filepath provided for saving PNG");
211
- await (0, node_fs_promises.writeFile)(targetPath, this.toBuffer(options));
220
+ await (0, node_fs_promises.writeFile)(targetPath, await this.toBuffer());
212
221
  }
213
222
  };
214
223
  //#endregion
@@ -225,8 +234,7 @@ const compare$1 = (image1, image2, diff, width, height, options) => {
225
234
  * @returns Comparison result
226
235
  */
227
236
  async function compareImagesGMSD(image1, image2, withDiff = false, options = {}) {
228
- const png1 = await loadPNG$1(image1);
229
- const png2 = await loadPNG$1(image2);
237
+ const [png1, png2] = await Promise.all([loadPNG$1(image1), loadPNG$1(image2)]);
230
238
  const { width, height } = png1;
231
239
  if (width !== png2.width || height !== png2.height) return {
232
240
  gmsd: Infinity,
@@ -240,7 +248,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
240
248
  });
241
249
  return {
242
250
  gmsd,
243
- diffBuffer: diff ? annotateDiffImage$1(diff, options).toBuffer() : void 0,
251
+ diffBuffer: diff ? await annotateDiffImage$1(diff, options).toBuffer() : void 0,
244
252
  passed: gmsd <= (options.threshold ?? .1)
245
253
  };
246
254
  } catch (error) {
@@ -290,8 +298,7 @@ const compare = (image1, image2, diff, width, height, options) => {
290
298
  * @returns Comparison result
291
299
  */
292
300
  async function compareImages(image1, image2, withDiff = false, options = {}) {
293
- const png1 = await loadPNG(image1);
294
- const png2 = await loadPNG(image2);
301
+ const [png1, png2] = await Promise.all([loadPNG(image1), loadPNG(image2)]);
295
302
  const { width, height } = png1;
296
303
  if (width !== png2.width || height !== png2.height) return {
297
304
  numDiffPixels: 0,
@@ -309,7 +316,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
309
316
  numDiffPixels,
310
317
  totalPixels,
311
318
  percentDifference,
312
- diffBuffer: diff ? annotateDiffImage(diff, options).toBuffer() : void 0,
319
+ diffBuffer: diff ? await annotateDiffImage(diff, options).toBuffer() : void 0,
313
320
  passed: isPassed(percentDifference, numDiffPixels, options),
314
321
  differentSizes: false
315
322
  };
@@ -366,7 +373,7 @@ const isPassed = (percentDifference, numDiffPixels, options) => {
366
373
  * Create different size png image with all pixels red
367
374
  * @returns
368
375
  */
369
- function createDiffSizePngImage(width, height) {
376
+ async function createDiffSizePngImage(width, height) {
370
377
  const png = PNG.create(width, height);
371
378
  for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
372
379
  const idx = width * y + x << 2;
@@ -398,9 +405,9 @@ var ScreenshotFileSystem = class {
398
405
  this.actual = node_path.default.resolve(outputDir, "actual");
399
406
  this.expected = node_path.default.resolve(outputDir, "expected");
400
407
  this.diff = node_path.default.resolve(outputDir, "diff");
401
- this.ensureParentDir(this.actual);
402
- this.ensureParentDir(this.expected);
403
- this.ensureParentDir(this.diff);
408
+ this.ensureParentDirSync(this.actual);
409
+ this.ensureParentDirSync(this.expected);
410
+ this.ensureParentDirSync(this.diff);
404
411
  }
405
412
  clearActual() {
406
413
  this.removeDir(this.actual);
@@ -450,7 +457,7 @@ var ScreenshotFileSystem = class {
450
457
  const actualPath = node_path.default.resolve(this.actual, relativePath);
451
458
  const expectedPath = node_path.default.resolve(this.expected, relativePath);
452
459
  const diffPath = node_path.default.resolve(this.diff, relativePath);
453
- this.ensureParentDir(expectedPath);
460
+ this.ensureParentDirSync(expectedPath);
454
461
  node_fs.default.copyFileSync(actualPath, expectedPath);
455
462
  if (node_fs.default.existsSync(diffPath)) {
456
463
  this.copyDiffMetadataToExpected(diffPath, expectedPath);
@@ -481,7 +488,14 @@ var ScreenshotFileSystem = class {
481
488
  * Ensure the parent directory of a file exists. If not, it creates it.
482
489
  * @param filePath - The path to the file.
483
490
  */
484
- ensureParentDir(filePath) {
491
+ async ensureParentDir(filePath) {
492
+ const dir = node_path.default.dirname(filePath);
493
+ await node_fs_promises.default.mkdir(dir, { recursive: true });
494
+ }
495
+ /**
496
+ * Synchronous version used only during constructor initialization.
497
+ */
498
+ ensureParentDirSync(filePath) {
485
499
  const dir = node_path.default.dirname(filePath);
486
500
  if (!node_fs.default.existsSync(dir)) node_fs.default.mkdirSync(dir, { recursive: true });
487
501
  }
@@ -534,33 +548,41 @@ var ScreenshotFileSystem = class {
534
548
  /**
535
549
  * Write a file to the actual directory
536
550
  */
537
- writeActualFile(filename, data) {
551
+ async writeActualFile(filename, data) {
538
552
  const filepath = this.getActualFilePath(filename);
539
- this.ensureParentDir(filepath);
540
- node_fs.default.writeFileSync(filepath, data);
553
+ await this.ensureParentDir(filepath);
554
+ await node_fs_promises.default.writeFile(filepath, data);
541
555
  }
542
556
  /**
543
557
  * Write a file to the diff directory
544
558
  */
545
- writeDiffFile(filename, data) {
559
+ async writeDiffFile(filename, data) {
546
560
  const filepath = this.getDiffFilePath(filename);
547
- this.ensureParentDir(filepath);
548
- node_fs.default.writeFileSync(filepath, data);
561
+ await this.ensureParentDir(filepath);
562
+ await node_fs_promises.default.writeFile(filepath, data);
549
563
  }
550
564
  /**
551
565
  * Check if an expected file exists
552
566
  */
553
- hasExpectedFile(filename) {
567
+ async hasExpectedFile(filename) {
554
568
  const expectedPath = this.getExpectedFilePath(filename);
555
- return node_fs.default.existsSync(expectedPath);
569
+ try {
570
+ await node_fs_promises.default.access(expectedPath);
571
+ return true;
572
+ } catch {
573
+ return false;
574
+ }
556
575
  }
557
576
  /**
558
577
  * Read an expected file
559
578
  */
560
- readExpectedFile(filename) {
579
+ async readExpectedFile(filename) {
561
580
  const expectedPath = this.getExpectedFilePath(filename);
562
- if (!node_fs.default.existsSync(expectedPath)) throw new Error(`Expected image not found: ${expectedPath}`);
563
- return node_fs.default.readFileSync(expectedPath);
581
+ try {
582
+ return await node_fs_promises.default.readFile(expectedPath);
583
+ } catch {
584
+ throw new Error(`Expected image not found: ${expectedPath}`);
585
+ }
564
586
  }
565
587
  /**
566
588
  * Resolve the actual path of a screenshot file.
@@ -705,7 +727,7 @@ var ScreenshotTool = class {
705
727
  if (options.skip) return;
706
728
  try {
707
729
  const filepath = this.filesystem.getActualFilePath(filename);
708
- this.filesystem.ensureParentDir(filepath);
730
+ await this.filesystem.ensureParentDir(filepath);
709
731
  const screenshotOptions = {
710
732
  path: filepath,
711
733
  fullPage: options.fullPage ?? this.fullPage,
@@ -788,7 +810,7 @@ var ScreenshotTool = class {
788
810
  };
789
811
  const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings, diffOverride);
790
812
  if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
791
- this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
813
+ await this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
792
814
  this.logger.debug(`Actual screenshot saved: ${filepath}`);
793
815
  if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
794
816
  else this.logger.error(`Screenshot failed visual comparison`);
@@ -796,15 +818,15 @@ var ScreenshotTool = class {
796
818
  if (options.saveDiffImage && retryScreenshot.comparisonResult?.diffBuffer && !retryScreenshot.passed) {
797
819
  const diffFilename = options.diffImageFilename || filename;
798
820
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
799
- this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
821
+ await this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
800
822
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
801
823
  }
802
824
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
803
825
  this.logger.warn(`Screenshot has different sizes than reference image`);
804
826
  const diffFilename = options.diffImageFilename || filename;
805
827
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
806
- const diffBuffer = createDiffSizePngImage(200, 200);
807
- this.filesystem.writeDiffFile(diffFilename, diffBuffer);
828
+ const diffBuffer = await createDiffSizePngImage(200, 200);
829
+ await this.filesystem.writeDiffFile(diffFilename, diffBuffer);
808
830
  this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
809
831
  }
810
832
  return {
@@ -869,14 +891,15 @@ var ScreenshotTool = class {
869
891
  result.skipped = true;
870
892
  return result;
871
893
  }
894
+ const start = extras.captureStart ?? performance.now();
872
895
  const saveDiff = extras.saveDiffImage ?? false;
873
896
  const diffFilename = extras.diffImageFilename ?? filename;
874
897
  const diffOverride = extras.diff;
875
- if (!this.filesystem.hasExpectedFile(filename)) {
898
+ if (!await this.filesystem.hasExpectedFile(filename)) {
876
899
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
877
900
  result.filepath = await this.takeScreenshot(page, filename, options);
878
901
  } else {
879
- const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.readExpectedFile(filename), {
902
+ const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, await this.filesystem.readExpectedFile(filename), {
880
903
  ...options,
881
904
  saveDiffImage: saveDiff,
882
905
  diffImageFilename: diffFilename
@@ -885,6 +908,8 @@ var ScreenshotTool = class {
885
908
  result.comparisonResult = comparisonResult;
886
909
  result.diffImagePath = diffImagePath;
887
910
  }
911
+ const duration = Math.round(performance.now() - start);
912
+ this.logger.debug(`${filename} captured in ${duration}ms`);
888
913
  return result;
889
914
  }
890
915
  async capture(page, filename, options, extras = {}) {
@@ -910,7 +935,8 @@ var ScreenshotTool = class {
910
935
  const baseCaptureResult = await this.captureSingleScreenshot(page, filename, baseOptions, {
911
936
  saveDiffImage: baseSaveDiff,
912
937
  diffImageFilename: baseDiffFilename,
913
- diff: baseDiffOverride
938
+ diff: baseDiffOverride,
939
+ captureStart: extras.captureStart
914
940
  });
915
941
  baseResult.filepath = baseCaptureResult.filepath;
916
942
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -988,16 +1014,19 @@ var ScreenshotTool = class {
988
1014
  const baseSaveDiff = extras.saveDiffImage ?? false;
989
1015
  const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
990
1016
  const baseDiffOverride = extras.diff;
1017
+ let baseStart;
991
1018
  if (!extras.skipBaseNavigation) {
1019
+ baseStart = performance.now();
992
1020
  (0, _cappa_logger.getLogger)().debug(`Going to base URL: ${baseUrl}`);
993
1021
  await page.goto(baseUrl);
994
1022
  await this.applyScreenshotOptimizations(page);
995
1023
  await extras.waitForStability?.(page);
996
- }
1024
+ } else baseStart = performance.now();
997
1025
  const baseCaptureResult = await this.captureSingleScreenshot(page, baseFilename, baseOptions, {
998
1026
  saveDiffImage: baseSaveDiff,
999
1027
  diffImageFilename: baseDiffFilename,
1000
- diff: baseDiffOverride
1028
+ diff: baseDiffOverride,
1029
+ captureStart: extras.captureStart ?? baseStart
1001
1030
  });
1002
1031
  baseResult.filepath = baseCaptureResult.filepath;
1003
1032
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -1019,6 +1048,7 @@ var ScreenshotTool = class {
1019
1048
  variantResults.push(variantResult);
1020
1049
  continue;
1021
1050
  }
1051
+ const variantStart = performance.now();
1022
1052
  (0, _cappa_logger.getLogger)().debug(`Going to variant URL: ${variant.url}`);
1023
1053
  await page.goto(variant.url);
1024
1054
  await this.applyScreenshotOptimizations(page);
@@ -1030,7 +1060,8 @@ var ScreenshotTool = class {
1030
1060
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
1031
1061
  saveDiffImage: variantSaveDiff,
1032
1062
  diffImageFilename: variantDiffFilename,
1033
- diff: variantDiffOverride
1063
+ diff: variantDiffOverride,
1064
+ captureStart: variantStart
1034
1065
  });
1035
1066
  variantResult.filepath = variantCaptureResult.filepath;
1036
1067
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;