@cappa/core 0.11.0 → 0.12.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.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Logger } from "@cappa/logger";
2
+ import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/core-native";
2
3
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
3
4
 
4
5
  //#region src/compare/pixel.d.ts
@@ -10,6 +11,7 @@ interface CompareResult$1 {
10
11
  passed: boolean;
11
12
  error?: string;
12
13
  differentSizes: boolean;
14
+ interpretation?: InterpretResult$1;
13
15
  }
14
16
  /**
15
17
  * Compare two PNG images and return the difference
@@ -30,6 +32,15 @@ declare function compareImages(image1: string | Buffer, image2: string | Buffer,
30
32
  declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
31
33
  //#endregion
32
34
  //#region src/filesystem.d.ts
35
+ /**
36
+ * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
37
+ */
38
+ declare function toDiffMetaPath(diffImagePath: string): string;
39
+ /**
40
+ * Read a diff metadata sidecar, returning `undefined` when it is missing or
41
+ * cannot be parsed (so callers can degrade gracefully).
42
+ */
43
+ declare function readDiffMeta(diffImagePath: string): Promise<DiffMetadata | undefined>;
33
44
  /**
34
45
  * Class for interacting with the local file system to store the screenshots.
35
46
  */
@@ -122,6 +133,14 @@ declare class ScreenshotFileSystem {
122
133
  * Write a file to the diff directory
123
134
  */
124
135
  writeDiffFile(filename: string, data: Buffer): Promise<void>;
136
+ /**
137
+ * Get the path to a diff metadata sidecar file (`<name>.json`)
138
+ */
139
+ getDiffMetaFilePath(filename: string): string;
140
+ /**
141
+ * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.
142
+ */
143
+ writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void>;
125
144
  /**
126
145
  * Check if an expected file exists
127
146
  */
@@ -251,7 +270,7 @@ declare class ScreenshotTool {
251
270
  * Takes a screenshot and returns the buffer (for comparison purposes)
252
271
  */
253
272
  takeScreenshotBuffer(page: Page, options: ScreenshotSettings): Promise<Buffer>;
254
- takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotSettings & {
273
+ takeScreenshotWithComparison(page: Page, filename: string, referenceImage: string | Buffer, options: ScreenshotSettings & {
255
274
  saveDiffImage?: boolean;
256
275
  diffImageFilename?: string;
257
276
  }, diffOverride?: DiffOptions): Promise<{
@@ -259,7 +278,7 @@ declare class ScreenshotTool {
259
278
  comparisonResult: CompareResult$1 | CompareResult;
260
279
  diffImagePath?: string;
261
280
  }>;
262
- retryScreenshot(page: Page, referenceImage: Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
281
+ retryScreenshot(page: Page, referenceImage: string | Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
263
282
  screenshotPath: Buffer<ArrayBufferLike>;
264
283
  comparisonResult: CompareResult | CompareResult$1;
265
284
  passed: boolean;
@@ -382,6 +401,15 @@ interface DiffConfig {
382
401
  * this can mean that small changes still slip through.
383
402
  */
384
403
  maxDiffPercentage?: number;
404
+ /**
405
+ * Run structured interpretation after the raw pixel diff.
406
+ * Default = false
407
+ *
408
+ * When enabled, changed screenshots get a `diff/<name>.json` sidecar describing
409
+ * *what* changed (additions, deletions, color shifts) grouped into regions, with a
410
+ * human-readable summary and severity. Pixel diff only — ignored when `type: 'gmsd'`.
411
+ */
412
+ interpret?: boolean;
385
413
  }
386
414
  /**
387
415
  * Configuration for the comparison of images using GMSD
@@ -534,11 +562,29 @@ type DeletedScreenshot = {
534
562
  category: "deleted";
535
563
  expectedPath: string;
536
564
  };
565
+ /**
566
+ * Pixel-diff statistics and optional structured interpretation for a changed
567
+ * screenshot. Persisted as a `diff/<name>.json` sidecar next to the diff image
568
+ * and read back when the review UI / CLI rebuild state from disk.
569
+ */
570
+ interface DiffMetadata {
571
+ /** Number of differing pixels reported by the pixel diff. */
572
+ numDiffPixels: number;
573
+ /** Percentage of differing pixels (0-100). */
574
+ percentDifference: number;
575
+ /** Structured interpretation, present only when `diff.interpret` is enabled. */
576
+ interpretation?: InterpretResult$1;
577
+ }
537
578
  type ChangedScreenshot = {
538
579
  category: "changed";
539
580
  diffPath: string;
540
581
  actualPath: string;
541
582
  expectedPath: string;
583
+ /**
584
+ * Diff statistics and optional interpretation loaded from the
585
+ * `diff/<name>.json` sidecar. Absent if the sidecar was not written.
586
+ */
587
+ diffMeta?: DiffMetadata;
542
588
  };
543
589
  type PassedScreenshot = {
544
590
  category: "passed";
@@ -596,5 +642,13 @@ declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffe
596
642
  */
597
643
  declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
598
644
  //#endregion
599
- export { type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type NewScreenshot, type PassedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD };
645
+ //#region src/mapWithConcurrency.d.ts
646
+ /**
647
+ * Run async work over `items` with at most `concurrency` tasks in flight.
648
+ * Preserves failure behavior: the first rejection rejects the returned promise.
649
+ * Results are returned in the same order as the input items.
650
+ */
651
+ declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
652
+ //#endregion
653
+ export { type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type InterpretResult, type NewScreenshot, type PassedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, mapWithConcurrency, readDiffMeta, toDiffMetaPath };
600
654
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import gmsd from "@blazediff/gmsd";
3
3
  import { getLogger } from "@cappa/logger";
4
- import fsp, { glob, readFile, writeFile } from "node:fs/promises";
4
+ import fsp, { glob, open, readFile, writeFile } from "node:fs/promises";
5
5
  import sharp from "sharp";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
@@ -104,6 +104,28 @@ function injectTextMetadata(buffer, metadata) {
104
104
  buffer.subarray(iendChunk.offset)
105
105
  ]);
106
106
  }
107
+ function isValidPngSignature(buffer) {
108
+ if (buffer.length < pngSignature.length) return false;
109
+ return buffer.subarray(0, pngSignature.length).equals(pngSignature);
110
+ }
111
+ const IHDR_MIN_BYTES = 24;
112
+ async function readIhdrDimensions(source) {
113
+ let buf;
114
+ if (typeof source === "string") {
115
+ const fh = await open(source, "r");
116
+ try {
117
+ buf = Buffer.alloc(IHDR_MIN_BYTES);
118
+ await fh.read(buf, 0, IHDR_MIN_BYTES, 0);
119
+ } finally {
120
+ await fh.close();
121
+ }
122
+ } else buf = source;
123
+ if (buf.length < IHDR_MIN_BYTES || !buf.subarray(0, pngSignature.length).equals(pngSignature)) throw new Error("Not a valid PNG");
124
+ return {
125
+ width: buf.readUInt32BE(16),
126
+ height: buf.readUInt32BE(20)
127
+ };
128
+ }
107
129
  /**
108
130
  * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.
109
131
  */
@@ -220,7 +242,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
220
242
  });
221
243
  return {
222
244
  gmsd,
223
- diffBuffer: diff ? await annotateDiffImage$1(diff, options).toBuffer() : void 0,
245
+ diffBuffer: diff ? await annotateDiffImage(diff, options).toBuffer() : void 0,
224
246
  passed: gmsd <= (options.threshold ?? .1)
225
247
  };
226
248
  } catch (error) {
@@ -238,7 +260,7 @@ async function compareImagesGMSD(image1, image2, withDiff = false, options = {})
238
260
  async function loadPNG(source) {
239
261
  return PNG.load(source);
240
262
  }
241
- function annotateDiffImage$1(image, options) {
263
+ function annotateDiffImage(image, options) {
242
264
  image.setMetadata("cappa.diff.algorithm", "gmsd");
243
265
  for (const [key, value] of Object.entries(options)) {
244
266
  if (value === void 0) continue;
@@ -267,18 +289,19 @@ async function resolveInputPath(source, fileName, state) {
267
289
  await fsp.access(source, fs.constants.R_OK);
268
290
  return path.resolve(source);
269
291
  }
270
- await PNG.load(source);
292
+ if (!isValidPngSignature(source)) throw new Error("Invalid PNG buffer: missing PNG signature");
271
293
  const root = await ensureTempRoot(state);
272
294
  const dest = path.join(root, fileName);
273
295
  await fsp.writeFile(dest, source);
274
296
  return dest;
275
297
  }
276
- function toNativeOptions(config) {
298
+ function toNativeOptions(config, withDiff) {
277
299
  const extra = config;
278
300
  const out = {
279
301
  threshold: extra.threshold,
280
302
  antialiasing: extra.includeAA ?? false
281
303
  };
304
+ if (extra.interpret && withDiff) out.interpret = true;
282
305
  if (extra.diffMask !== void 0) out.diffMask = extra.diffMask;
283
306
  if (extra.compression !== void 0) out.compression = extra.compression;
284
307
  if (extra.quality !== void 0) out.quality = extra.quality;
@@ -304,7 +327,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
304
327
  }
305
328
  let nativeResult;
306
329
  try {
307
- nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options));
330
+ nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options, withDiff));
308
331
  } catch (error) {
309
332
  getLogger().error(error.message || "Unknown error");
310
333
  return {
@@ -326,7 +349,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
326
349
  differentSizes: true
327
350
  };
328
351
  }
329
- const { width, height } = await PNG.load(p1);
352
+ const { width, height } = await readIhdrDimensions(p1);
330
353
  const totalPixels = width * height;
331
354
  if (nativeResult.match) return {
332
355
  numDiffPixels: 0,
@@ -338,8 +361,10 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
338
361
  };
339
362
  let diffBuffer;
340
363
  if (withDiff && diffPath) {
341
- const raw = await fsp.readFile(diffPath);
342
- diffBuffer = await annotateDiffImage(await PNG.load(raw), options).toBuffer();
364
+ const rawDiff = await fsp.readFile(diffPath);
365
+ const diffMetadata = { "cappa.diff.algorithm": "pixel" };
366
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) diffMetadata[`cappa.diff.${key}`] = String(value);
367
+ diffBuffer = injectTextMetadata(rawDiff, diffMetadata);
343
368
  }
344
369
  const numDiffPixels = nativeResult.diffCount;
345
370
  const percentDifference = nativeResult.diffPercentage;
@@ -349,7 +374,8 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
349
374
  percentDifference,
350
375
  diffBuffer,
351
376
  passed: isPassed(percentDifference, numDiffPixels, options),
352
- differentSizes: false
377
+ differentSizes: false,
378
+ interpretation: nativeResult.interpretation
353
379
  };
354
380
  } finally {
355
381
  if (state.tempRoot) await fsp.rm(state.tempRoot, {
@@ -358,14 +384,6 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
358
384
  }).catch(() => {});
359
385
  }
360
386
  }
361
- function annotateDiffImage(image, options) {
362
- image.setMetadata("cappa.diff.algorithm", "pixel");
363
- for (const [key, value] of Object.entries(options)) {
364
- if (value === void 0) continue;
365
- image.setMetadata(`cappa.diff.${key}`, String(value));
366
- }
367
- return image;
368
- }
369
387
  /**
370
388
  * Quick comparison function that returns only pass/fail
371
389
  * @param image1 - First image (file path or Buffer)
@@ -417,26 +435,48 @@ function defineConfig(options) {
417
435
  /**
418
436
  * Run async work over `items` with at most `concurrency` tasks in flight.
419
437
  * Preserves failure behavior: the first rejection rejects the returned promise.
438
+ * Results are returned in the same order as the input items.
420
439
  */
421
440
  async function mapWithConcurrency(concurrency, items, fn) {
422
- if (items.length === 0) return;
441
+ if (items.length === 0) return [];
423
442
  const workerCount = Math.min(Math.max(1, concurrency), items.length);
443
+ const results = new Array(items.length);
424
444
  let next = 0;
425
- const worker = async () => {
445
+ const worker = async (workerIndex) => {
426
446
  while (true) {
427
447
  const i = next++;
428
448
  if (i >= items.length) return;
429
449
  const item = items[i];
430
450
  if (item === void 0) return;
431
- await fn(item);
451
+ results[i] = await fn(item, workerIndex);
432
452
  }
433
453
  };
434
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
454
+ await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));
455
+ return results;
435
456
  }
436
457
  //#endregion
437
458
  //#region src/filesystem.ts
438
459
  const APPROVE_SCREENSHOTS_CONCURRENCY = 8;
439
460
  /**
461
+ * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
462
+ */
463
+ function toDiffMetaPath(diffImagePath) {
464
+ const ext = path.extname(diffImagePath);
465
+ return ext ? `${diffImagePath.slice(0, -ext.length)}.json` : `${diffImagePath}.json`;
466
+ }
467
+ /**
468
+ * Read a diff metadata sidecar, returning `undefined` when it is missing or
469
+ * cannot be parsed (so callers can degrade gracefully).
470
+ */
471
+ async function readDiffMeta(diffImagePath) {
472
+ try {
473
+ const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), "utf8");
474
+ return JSON.parse(raw);
475
+ } catch {
476
+ return;
477
+ }
478
+ }
479
+ /**
440
480
  * Class for interacting with the local file system to store the screenshots.
441
481
  */
442
482
  var ScreenshotFileSystem = class {
@@ -503,7 +543,9 @@ var ScreenshotFileSystem = class {
503
543
  }
504
544
  if (screenshot.category === "changed") {
505
545
  logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);
506
- await fsp.unlink(path.resolve(outputDir, screenshot.diffPath));
546
+ const diffPath = path.resolve(outputDir, screenshot.diffPath);
547
+ await fsp.unlink(diffPath);
548
+ await fsp.rm(toDiffMetaPath(diffPath), { force: true });
507
549
  await this.approveFromActualPath(path.resolve(outputDir, screenshot.actualPath));
508
550
  return;
509
551
  }
@@ -543,6 +585,7 @@ var ScreenshotFileSystem = class {
543
585
  }
544
586
  await this.copyDiffMetadataToExpected(diffPath, expectedPath);
545
587
  await fsp.unlink(diffPath);
588
+ await fsp.rm(toDiffMetaPath(diffPath), { force: true });
546
589
  return {
547
590
  actualPath,
548
591
  expectedPath,
@@ -642,6 +685,20 @@ var ScreenshotFileSystem = class {
642
685
  await fsp.writeFile(filepath, data);
643
686
  }
644
687
  /**
688
+ * Get the path to a diff metadata sidecar file (`<name>.json`)
689
+ */
690
+ getDiffMetaFilePath(filename) {
691
+ return toDiffMetaPath(this.getDiffFilePath(filename));
692
+ }
693
+ /**
694
+ * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.
695
+ */
696
+ async writeDiffMetaFile(filename, meta) {
697
+ const filepath = this.getDiffMetaFilePath(filename);
698
+ await this.ensureParentDir(filepath);
699
+ await fsp.writeFile(filepath, JSON.stringify(meta));
700
+ }
701
+ /**
645
702
  * Check if an expected file exists
646
703
  */
647
704
  async hasExpectedFile(filename) {
@@ -907,6 +964,12 @@ var ScreenshotTool = class {
907
964
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
908
965
  await this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
909
966
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
967
+ const result = retryScreenshot.comparisonResult;
968
+ if ("numDiffPixels" in result && result.interpretation) await this.filesystem.writeDiffMetaFile(diffFilename, {
969
+ numDiffPixels: result.numDiffPixels,
970
+ percentDifference: result.percentDifference,
971
+ interpretation: result.interpretation
972
+ });
910
973
  }
911
974
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
912
975
  this.logger.warn(`Screenshot has different sizes than reference image`);
@@ -986,7 +1049,7 @@ var ScreenshotTool = class {
986
1049
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
987
1050
  result.filepath = await this.takeScreenshot(page, filename, options);
988
1051
  } else {
989
- const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, await this.filesystem.readExpectedFile(filename), {
1052
+ const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.getExpectedFilePath(filename), {
990
1053
  ...options,
991
1054
  saveDiffImage: saveDiff,
992
1055
  diffImageFilename: diffFilename
@@ -1178,6 +1241,6 @@ var ScreenshotTool = class {
1178
1241
  }
1179
1242
  };
1180
1243
  //#endregion
1181
- export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD };
1244
+ export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, mapWithConcurrency, readDiffMeta, toDiffMetaPath };
1182
1245
 
1183
1246
  //# sourceMappingURL=index.mjs.map