@cappa/core 0.12.0 → 0.12.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.d.cts CHANGED
@@ -270,7 +270,7 @@ declare class ScreenshotTool {
270
270
  * Takes a screenshot and returns the buffer (for comparison purposes)
271
271
  */
272
272
  takeScreenshotBuffer(page: Page, options: ScreenshotSettings): Promise<Buffer>;
273
- takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotSettings & {
273
+ takeScreenshotWithComparison(page: Page, filename: string, referenceImage: string | Buffer, options: ScreenshotSettings & {
274
274
  saveDiffImage?: boolean;
275
275
  diffImageFilename?: string;
276
276
  }, diffOverride?: DiffOptions): Promise<{
@@ -278,7 +278,7 @@ declare class ScreenshotTool {
278
278
  comparisonResult: CompareResult$1 | CompareResult;
279
279
  diffImagePath?: string;
280
280
  }>;
281
- retryScreenshot(page: Page, referenceImage: Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
281
+ retryScreenshot(page: Page, referenceImage: string | Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
282
282
  screenshotPath: Buffer<ArrayBufferLike>;
283
283
  comparisonResult: CompareResult | CompareResult$1;
284
284
  passed: boolean;
@@ -642,5 +642,13 @@ declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffe
642
642
  */
643
643
  declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
644
644
  //#endregion
645
- 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, readDiffMeta, toDiffMetaPath };
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 };
646
654
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -270,7 +270,7 @@ declare class ScreenshotTool {
270
270
  * Takes a screenshot and returns the buffer (for comparison purposes)
271
271
  */
272
272
  takeScreenshotBuffer(page: Page, options: ScreenshotSettings): Promise<Buffer>;
273
- takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotSettings & {
273
+ takeScreenshotWithComparison(page: Page, filename: string, referenceImage: string | Buffer, options: ScreenshotSettings & {
274
274
  saveDiffImage?: boolean;
275
275
  diffImageFilename?: string;
276
276
  }, diffOverride?: DiffOptions): Promise<{
@@ -278,7 +278,7 @@ declare class ScreenshotTool {
278
278
  comparisonResult: CompareResult$1 | CompareResult;
279
279
  diffImagePath?: string;
280
280
  }>;
281
- retryScreenshot(page: Page, referenceImage: Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
281
+ retryScreenshot(page: Page, referenceImage: string | Buffer, options: ScreenshotSettings, diffOverride?: DiffOptions): Promise<{
282
282
  screenshotPath: Buffer<ArrayBufferLike>;
283
283
  comparisonResult: CompareResult | CompareResult$1;
284
284
  passed: boolean;
@@ -642,5 +642,13 @@ declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffe
642
642
  */
643
643
  declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
644
644
  //#endregion
645
- 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, readDiffMeta, toDiffMetaPath };
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 };
646
654
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
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";
8
- import { compare } from "@blazediff/core-native";
8
+ import { compare, interpret } from "@blazediff/core-native";
9
9
  import { chromium, firefox, webkit } from "playwright-core";
10
10
  //#region src/features/png/util.ts
11
11
  const pngSignature = Buffer.from([
@@ -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,19 +289,18 @@ 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, withDiff) {
298
+ function toNativeOptions(config) {
277
299
  const extra = config;
278
300
  const out = {
279
301
  threshold: extra.threshold,
280
302
  antialiasing: extra.includeAA ?? false
281
303
  };
282
- if (extra.interpret && withDiff) out.interpret = true;
283
304
  if (extra.diffMask !== void 0) out.diffMask = extra.diffMask;
284
305
  if (extra.compression !== void 0) out.compression = extra.compression;
285
306
  if (extra.quality !== void 0) out.quality = extra.quality;
@@ -303,9 +324,10 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
303
324
  const root = await ensureTempRoot(state);
304
325
  diffPath = path.join(root, "diff.png");
305
326
  }
327
+ const wantInterpret = !!options.interpret && withDiff;
306
328
  let nativeResult;
307
329
  try {
308
- nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options, withDiff));
330
+ nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options));
309
331
  } catch (error) {
310
332
  getLogger().error(error.message || "Unknown error");
311
333
  return {
@@ -327,7 +349,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
327
349
  differentSizes: true
328
350
  };
329
351
  }
330
- const { width, height } = await PNG.load(p1);
352
+ const { width, height } = await readIhdrDimensions(p1);
331
353
  const totalPixels = width * height;
332
354
  if (nativeResult.match) return {
333
355
  numDiffPixels: 0,
@@ -339,11 +361,20 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
339
361
  };
340
362
  let diffBuffer;
341
363
  if (withDiff && diffPath) {
342
- const raw = await fsp.readFile(diffPath);
343
- 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);
344
368
  }
345
369
  const numDiffPixels = nativeResult.diffCount;
346
370
  const percentDifference = nativeResult.diffPercentage;
371
+ let interpretation;
372
+ if (wantInterpret && !nativeResult.match) try {
373
+ interpretation = await interpret(p1, p2, {
374
+ threshold: options.threshold,
375
+ antialiasing: options.includeAA ?? false
376
+ });
377
+ } catch {}
347
378
  return {
348
379
  numDiffPixels,
349
380
  totalPixels,
@@ -351,7 +382,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
351
382
  diffBuffer,
352
383
  passed: isPassed(percentDifference, numDiffPixels, options),
353
384
  differentSizes: false,
354
- interpretation: nativeResult.interpretation
385
+ interpretation
355
386
  };
356
387
  } finally {
357
388
  if (state.tempRoot) await fsp.rm(state.tempRoot, {
@@ -360,14 +391,6 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
360
391
  }).catch(() => {});
361
392
  }
362
393
  }
363
- function annotateDiffImage(image, options) {
364
- image.setMetadata("cappa.diff.algorithm", "pixel");
365
- for (const [key, value] of Object.entries(options)) {
366
- if (value === void 0) continue;
367
- image.setMetadata(`cappa.diff.${key}`, String(value));
368
- }
369
- return image;
370
- }
371
394
  /**
372
395
  * Quick comparison function that returns only pass/fail
373
396
  * @param image1 - First image (file path or Buffer)
@@ -419,21 +442,24 @@ function defineConfig(options) {
419
442
  /**
420
443
  * Run async work over `items` with at most `concurrency` tasks in flight.
421
444
  * Preserves failure behavior: the first rejection rejects the returned promise.
445
+ * Results are returned in the same order as the input items.
422
446
  */
423
447
  async function mapWithConcurrency(concurrency, items, fn) {
424
- if (items.length === 0) return;
448
+ if (items.length === 0) return [];
425
449
  const workerCount = Math.min(Math.max(1, concurrency), items.length);
450
+ const results = new Array(items.length);
426
451
  let next = 0;
427
- const worker = async () => {
452
+ const worker = async (workerIndex) => {
428
453
  while (true) {
429
454
  const i = next++;
430
455
  if (i >= items.length) return;
431
456
  const item = items[i];
432
457
  if (item === void 0) return;
433
- await fn(item);
458
+ results[i] = await fn(item, workerIndex);
434
459
  }
435
460
  };
436
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
461
+ await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));
462
+ return results;
437
463
  }
438
464
  //#endregion
439
465
  //#region src/filesystem.ts
@@ -1030,7 +1056,7 @@ var ScreenshotTool = class {
1030
1056
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
1031
1057
  result.filepath = await this.takeScreenshot(page, filename, options);
1032
1058
  } else {
1033
- const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, await this.filesystem.readExpectedFile(filename), {
1059
+ const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.getExpectedFilePath(filename), {
1034
1060
  ...options,
1035
1061
  saveDiffImage: saveDiff,
1036
1062
  diffImageFilename: diffFilename
@@ -1222,6 +1248,6 @@ var ScreenshotTool = class {
1222
1248
  }
1223
1249
  };
1224
1250
  //#endregion
1225
- export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, readDiffMeta, toDiffMetaPath };
1251
+ export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, mapWithConcurrency, readDiffMeta, toDiffMetaPath };
1226
1252
 
1227
1253
  //# sourceMappingURL=index.mjs.map