@cappa/core 0.19.0 → 0.20.0

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
@@ -2205,7 +2205,145 @@ var CaptureRunner = class {
2205
2205
  }
2206
2206
  };
2207
2207
  //#endregion
2208
+ //#region src/features/png/pixelRatio.ts
2209
+ /**
2210
+ * A screenshot's pixel ratio — image pixels per CSS pixel — stored in the PNG
2211
+ * itself.
2212
+ *
2213
+ * Kept in the file rather than beside it because `approve` is a plain copy:
2214
+ * the baseline carries the ratio it was captured at through approve, git and
2215
+ * CI artifacts with no bookkeeping.
2216
+ *
2217
+ * Two chunks, both before the image data:
2218
+ * - a `tEXt` chunk keyed `cappa:pixelRatio` — the source of truth. Only cappa
2219
+ * writes it, so an image another tool stamped with a DPI is never misread.
2220
+ * - a standard `pHYs` chunk, which image viewers read as DPI, so a 2×
2221
+ * screenshot opens at its CSS size in tools that honour it.
2222
+ *
2223
+ * Only written for ratios other than 1. A PNG without the key is 1×, which is
2224
+ * what every screenshot taken with `scale: "css"` is — so those stay
2225
+ * byte-for-byte what they were, and `fastBufferCheck` keeps matching them.
2226
+ */
2227
+ const PIXEL_RATIO_KEY = "cappa:pixelRatio";
2228
+ /** Pixels per metre at 96 DPI, the CSS reference pixel density. */
2229
+ const PPM_AT_1X = 96 / .0254;
2230
+ const IHDR_END = 33;
2231
+ /** Ancillary chunks before IDAT are few; bound every walk regardless. */
2232
+ const MAX_CHUNKS_BEFORE_IDAT = 64;
2233
+ const roundRatio = (ratio) => Math.round(ratio * 100) / 100;
2234
+ const createPhysChunk = (ratio) => {
2235
+ const ppm = Math.round(PPM_AT_1X * ratio);
2236
+ const chunk = Buffer.alloc(21);
2237
+ chunk.writeUInt32BE(9, 0);
2238
+ chunk.write("pHYs", 4, "ascii");
2239
+ chunk.writeUInt32BE(ppm, 8);
2240
+ chunk.writeUInt32BE(ppm, 12);
2241
+ chunk.writeUInt8(1, 16);
2242
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, 17)), 17);
2243
+ return chunk;
2244
+ };
2245
+ const isRatioText = (type, data) => type === "tEXt" && data.length > 16 && data.toString("latin1", 0, 17) === `cappa:pixelRatio\0`;
2246
+ const parseRatioText = (data) => {
2247
+ const value = Number(data.toString("latin1", 17));
2248
+ return Number.isFinite(value) && value > 0 ? roundRatio(value) : void 0;
2249
+ };
2250
+ /** The chunks between IHDR and the first IDAT. */
2251
+ function* chunksBeforeImage(buffer) {
2252
+ let offset = IHDR_END;
2253
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2254
+ if (offset + 8 > buffer.length) return;
2255
+ const length = buffer.readUInt32BE(offset);
2256
+ const type = buffer.toString("ascii", offset + 4, offset + 8);
2257
+ const end = offset + 12 + length;
2258
+ if (type === "IDAT" || type === "IEND" || end > buffer.length) return;
2259
+ yield {
2260
+ type,
2261
+ start: offset,
2262
+ end,
2263
+ data: buffer.subarray(offset + 8, offset + 8 + length)
2264
+ };
2265
+ offset = end;
2266
+ }
2267
+ }
2268
+ const hasIhdr = (buffer) => isValidPngSignature(buffer) && buffer.length >= IHDR_END && buffer.toString("ascii", 12, 16) === "IHDR";
2269
+ /**
2270
+ * Return `buffer` stamped with `ratio`, replacing any ratio it carried.
2271
+ *
2272
+ * Ratio 1 removes cappa's chunks instead (see above); a `pHYs` some other tool
2273
+ * wrote is left alone unless cappa is writing its own. Anything that is not a
2274
+ * PNG comes back untouched. No pixel data is re-encoded.
2275
+ */
2276
+ function withPixelRatio(buffer, ratio) {
2277
+ if (!hasIhdr(buffer)) return buffer;
2278
+ const stamp = ratio > 0 && roundRatio(ratio) !== 1;
2279
+ const chunks = [...chunksBeforeImage(buffer)];
2280
+ const ours = chunks.some((chunk) => isRatioText(chunk.type, chunk.data));
2281
+ if (!stamp && !ours) return buffer;
2282
+ const drop = chunks.filter((chunk) => isRatioText(chunk.type, chunk.data) || chunk.type === "pHYs" && (stamp || ours));
2283
+ const parts = [buffer.subarray(0, IHDR_END)];
2284
+ if (stamp) parts.push(createTextChunk(PIXEL_RATIO_KEY, String(roundRatio(ratio))), createPhysChunk(ratio));
2285
+ let copyFrom = IHDR_END;
2286
+ for (const chunk of drop) {
2287
+ parts.push(buffer.subarray(copyFrom, chunk.start));
2288
+ copyFrom = chunk.end;
2289
+ }
2290
+ parts.push(buffer.subarray(copyFrom));
2291
+ return Buffer.concat(parts);
2292
+ }
2293
+ async function readHead(path) {
2294
+ const fh = await open(path, "r");
2295
+ try {
2296
+ const head = Buffer.alloc(IHDR_END);
2297
+ const { bytesRead } = await fh.read(head, 0, IHDR_END, 0);
2298
+ if (bytesRead < IHDR_END || !hasIhdr(head)) return void 0;
2299
+ const parts = [head];
2300
+ const header = Buffer.alloc(8);
2301
+ let offset = IHDR_END;
2302
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2303
+ if ((await fh.read(header, 0, 8, offset)).bytesRead < 8) break;
2304
+ const length = header.readUInt32BE(0);
2305
+ const type = header.toString("ascii", 4, 8);
2306
+ if (type === "IDAT" || type === "IEND") break;
2307
+ const chunk = Buffer.alloc(12 + length);
2308
+ await fh.read(chunk, 0, chunk.length, offset);
2309
+ parts.push(chunk);
2310
+ offset += chunk.length;
2311
+ }
2312
+ return Buffer.concat(parts);
2313
+ } finally {
2314
+ await fh.close();
2315
+ }
2316
+ }
2317
+ /**
2318
+ * The pixel ratio a screenshot was captured at: 1 when the PNG carries no
2319
+ * ratio, and also when the file cannot be read — a missing ratio must never
2320
+ * break listing or comparing screenshots.
2321
+ */
2322
+ async function readPixelRatio(source) {
2323
+ try {
2324
+ const buffer = typeof source === "string" ? await readHead(source) : source;
2325
+ if (!buffer || !hasIhdr(buffer)) return 1;
2326
+ for (const chunk of chunksBeforeImage(buffer)) if (isRatioText(chunk.type, chunk.data)) return parseRatioText(chunk.data) ?? 1;
2327
+ return 1;
2328
+ } catch {
2329
+ return 1;
2330
+ }
2331
+ }
2332
+ const formatRatio = (ratio) => `${ratio}×`;
2333
+ /**
2334
+ * Why a screenshot cannot match its baseline when the two were captured at
2335
+ * different pixel ratios — `screenshot.scale` or `deviceScaleFactor` changed.
2336
+ */
2337
+ function describePixelRatioMismatch(expected, actual) {
2338
+ return `Baseline was captured at ${formatRatio(expected)} pixel ratio, this screenshot at ${formatRatio(actual)}, so their sizes cannot match. If the change of screenshot.scale or deviceScaleFactor is intended, approve the new screenshots; otherwise restore the previous setting.`;
2339
+ }
2340
+ //#endregion
2208
2341
  //#region src/screenshot.ts
2342
+ /**
2343
+ * `deviceScaleFactor` for contexts whose `contextOptions` set none. With the
2344
+ * default `scale: "css"` it only changes how the page renders, not the PNG.
2345
+ */
2346
+ const DEFAULT_DEVICE_SCALE_FACTOR = 2;
2209
2347
  const defaultPixelDiffConfig = {
2210
2348
  type: "pixel",
2211
2349
  threshold: .1,
@@ -2283,6 +2421,8 @@ var ScreenshotTool = class {
2283
2421
  fullPage;
2284
2422
  /** Default content crop; a screenshot's own `crop` overrides it. */
2285
2423
  crop;
2424
+ /** Default `scale`; a screenshot's own `scale` overrides it. */
2425
+ scale;
2286
2426
  outputDir;
2287
2427
  browser = null;
2288
2428
  context = null;
@@ -2323,6 +2463,7 @@ var ScreenshotTool = class {
2323
2463
  };
2324
2464
  this.fullPage = options.fullPage ?? true;
2325
2465
  this.crop = options.crop ?? false;
2466
+ this.scale = options.scale ?? "css";
2326
2467
  this.outputDir = options.outputDir || "./screenshots";
2327
2468
  this.diff = this.resolveDiffOptions(options.diff);
2328
2469
  this.concurrency = Math.max(1, options.concurrency || 1);
@@ -2464,7 +2605,7 @@ var ScreenshotTool = class {
2464
2605
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
2465
2606
  const context = await browser.newContext({
2466
2607
  reducedMotion: "reduce",
2467
- deviceScaleFactor: 2,
2608
+ deviceScaleFactor: DEFAULT_DEVICE_SCALE_FACTOR,
2468
2609
  ...extraContextOptions,
2469
2610
  userAgent: `${contextOptions?.userAgent ?? this.defaultUserAgent} CappaStorybook`,
2470
2611
  viewport: this.viewport
@@ -2588,21 +2729,33 @@ var ScreenshotTool = class {
2588
2729
  const clip = crop ? await measureContentClip(page, crop, fullPage) : void 0;
2589
2730
  if (crop && !clip) this.logger.debug(`Nothing painted inside "${crop.root}" to crop to; taking the uncropped screenshot`);
2590
2731
  const screenshotOptions = {
2591
- path: filepath,
2592
2732
  fullPage,
2593
2733
  clip,
2594
2734
  type: "png",
2595
2735
  timeout: 6e4,
2596
2736
  mask: options.mask,
2597
2737
  omitBackground: options.omitBackground,
2598
- scale: "css",
2738
+ scale: options.scale ?? this.scale,
2599
2739
  animations: "disabled",
2600
2740
  caret: "hide"
2601
2741
  };
2602
- return page.screenshot(screenshotOptions);
2742
+ const buffer = withPixelRatio(await page.screenshot(screenshotOptions), this.pixelRatioFor(options));
2743
+ if (filepath) await fsp.writeFile(filepath, buffer);
2744
+ return buffer;
2603
2745
  });
2604
2746
  }
2605
2747
  /**
2748
+ * Image pixels per CSS pixel for a screenshot taken with `options`: the
2749
+ * context's `deviceScaleFactor` with `scale: "device"`, else 1.
2750
+ *
2751
+ * Stamped into every PNG (see `features/png/pixelRatio.ts`) so a baseline
2752
+ * remembers the ratio it was captured at.
2753
+ */
2754
+ pixelRatioFor(options) {
2755
+ if ((options.scale ?? this.scale) !== "device") return 1;
2756
+ return this.browserConfig.provider.options.contextOptions?.deviceScaleFactor ?? DEFAULT_DEVICE_SCALE_FACTOR;
2757
+ }
2758
+ /**
2606
2759
  * Sets the viewport size and executes the action, ensuring the original viewport is restored
2607
2760
  * even if the action throws an error.
2608
2761
  */
@@ -2637,6 +2790,7 @@ var ScreenshotTool = class {
2637
2790
  const screenshotSettings = {
2638
2791
  fullPage: options.fullPage ?? this.fullPage,
2639
2792
  crop: options.crop,
2793
+ scale: options.scale,
2640
2794
  mask: options.mask,
2641
2795
  omitBackground: options.omitBackground,
2642
2796
  delay: options.delay,
@@ -2662,7 +2816,7 @@ var ScreenshotTool = class {
2662
2816
  });
2663
2817
  }
2664
2818
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
2665
- this.logger.warn(`Screenshot has different sizes than reference image`);
2819
+ if (!retryScreenshot.pixelRatio) this.logger.warn(`Screenshot has different sizes than reference image`);
2666
2820
  if (!diffImagePath) {
2667
2821
  const diffFilename = options.diffImageFilename || filename;
2668
2822
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
@@ -2674,7 +2828,8 @@ var ScreenshotTool = class {
2674
2828
  return {
2675
2829
  screenshotPath: filepath,
2676
2830
  comparisonResult: retryScreenshot.comparisonResult,
2677
- diffImagePath
2831
+ diffImagePath,
2832
+ ...retryScreenshot.pixelRatio ? { pixelRatio: retryScreenshot.pixelRatio } : {}
2678
2833
  };
2679
2834
  } catch (error) {
2680
2835
  this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
@@ -2683,19 +2838,27 @@ var ScreenshotTool = class {
2683
2838
  }
2684
2839
  async retryScreenshot(page, referenceImage, options, diffOverride) {
2685
2840
  const diffConfig = this.mergeDiffOptions(diffOverride);
2686
- for (let i = 0; i < this.retries; i++) try {
2841
+ const pixelRatio = {
2842
+ expected: await readPixelRatio(referenceImage),
2843
+ actual: this.pixelRatioFor(options)
2844
+ };
2845
+ const ratioMismatch = pixelRatio.expected !== pixelRatio.actual;
2846
+ if (ratioMismatch) this.logger.error(describePixelRatioMismatch(pixelRatio.expected, pixelRatio.actual));
2847
+ const attempts = ratioMismatch ? 1 : this.retries;
2848
+ for (let i = 0; i < attempts; i++) try {
2687
2849
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
2688
2850
  ...options,
2689
2851
  delay: this.getIncBackoffDelay(i, options.delay || 0)
2690
2852
  });
2691
2853
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
2692
2854
  const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
2693
- if (i === this.retries - 1 && !comparisonResult.passed) {
2694
- this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2855
+ if (i === attempts - 1 && !comparisonResult.passed) {
2856
+ if (!ratioMismatch) this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2695
2857
  return {
2696
2858
  screenshotPath: screenshotBuffer,
2697
2859
  comparisonResult,
2698
- passed: false
2860
+ passed: false,
2861
+ ...ratioMismatch ? { pixelRatio } : {}
2699
2862
  };
2700
2863
  }
2701
2864
  if (comparisonResult.passed) return {
@@ -3111,7 +3274,11 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3111
3274
  const id = createHash("sha256").update(relativePath).digest("hex");
3112
3275
  const expectedScreenshot = expectedByRelativePath.get(relativePath);
3113
3276
  const diffScreenshot = diffByRelativePath.get(relativePath);
3114
- const diffMeta = diffScreenshot ? await readDiffMeta(diffScreenshot) : void 0;
3277
+ const [diffMeta, actualPixelRatio, expectedPixelRatio] = await Promise.all([
3278
+ diffScreenshot ? readDiffMeta(diffScreenshot) : void 0,
3279
+ readPixelRatio(screenshot),
3280
+ expectedScreenshot ? readPixelRatio(expectedScreenshot) : 1
3281
+ ]);
3115
3282
  screenshotRepresentations.push({
3116
3283
  id,
3117
3284
  name,
@@ -3119,7 +3286,8 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3119
3286
  expectedPath: expectedScreenshot ? path.relative(outputDir, expectedScreenshot) : void 0,
3120
3287
  diffPath: diffScreenshot ? path.relative(outputDir, diffScreenshot) : void 0,
3121
3288
  actualPath: path.relative(outputDir, screenshot),
3122
- ...diffMeta ? { diffMeta } : {}
3289
+ ...diffMeta ? { diffMeta } : {},
3290
+ ...pixelRatios(actualPixelRatio, expectedPixelRatio)
3123
3291
  });
3124
3292
  }
3125
3293
  for (const expectedScreenshot of expectedScreenshots) {
@@ -3131,13 +3299,19 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3131
3299
  id,
3132
3300
  name,
3133
3301
  category: "deleted",
3134
- expectedPath: path.relative(outputDir, expectedScreenshot)
3302
+ expectedPath: path.relative(outputDir, expectedScreenshot),
3303
+ ...pixelRatios(1, await readPixelRatio(expectedScreenshot))
3135
3304
  });
3136
3305
  }
3137
3306
  return screenshotRepresentations.sort((a, b) => {
3138
3307
  return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
3139
3308
  });
3140
3309
  };
3310
+ /** Ratios other than 1 only: absent means 1, which keeps 1× listings as they were. */
3311
+ const pixelRatios = (actual, expected) => ({
3312
+ ...actual !== 1 ? { actualPixelRatio: actual } : {},
3313
+ ...expected !== 1 ? { expectedPixelRatio: expected } : {}
3314
+ });
3141
3315
  const buildCategory = (expectedScreenshot, diffScreenshot) => {
3142
3316
  if (expectedScreenshot && diffScreenshot) return "changed";
3143
3317
  if (expectedScreenshot) return "passed";
@@ -4327,6 +4501,7 @@ var LocalEngine = class {
4327
4501
  logConsoleEvents: this.options.logConsoleEvents,
4328
4502
  fullPage: this.options.fullPage ?? true,
4329
4503
  crop: this.options.crop ?? false,
4504
+ scale: this.options.scale ?? "css",
4330
4505
  viewport: this.options.viewport ?? {
4331
4506
  width: 1920,
4332
4507
  height: 1080
@@ -5369,6 +5544,6 @@ function resolveWebServerConfig(webServer, configDir, env = process.env) {
5369
5544
  });
5370
5545
  }
5371
5546
  //#endregion
5372
- export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CONTAINER_LABEL, CaptureRunner, DEFAULT_CONTAINER_IMAGE, DEFAULT_CROP_PADDING, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_KILL_GRACE_MS, DEFAULT_MAX_TASKS, DEFAULT_WEB_SERVER_TIMEOUT_MS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, NO_WEB_SERVER_HINT, OutputTail, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, describeChange, didScreenshotFail, ensurePlaywrightContainer, filterTasks, findRefusedConnection, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isUrlReady, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, measureContentClip, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, playwright, readAgentReport, readCaptureManifest, readDiffMeta, recordCaptureOrigins, removePlaywrightContainers, renderJudgmentTiles, renderOverview, resolveBrowserConfig, resolveContainerOptions, resolveCrop, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, writeAgentVerdict };
5547
+ export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CONTAINER_LABEL, CaptureRunner, DEFAULT_CONTAINER_IMAGE, DEFAULT_CROP_PADDING, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_KILL_GRACE_MS, DEFAULT_MAX_TASKS, DEFAULT_WEB_SERVER_TIMEOUT_MS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, NO_WEB_SERVER_HINT, OutputTail, PIXEL_RATIO_KEY, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, describeChange, describePixelRatioMismatch, didScreenshotFail, ensurePlaywrightContainer, filterTasks, findRefusedConnection, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isUrlReady, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, measureContentClip, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, playwright, readAgentReport, readCaptureManifest, readDiffMeta, readPixelRatio, recordCaptureOrigins, removePlaywrightContainers, renderJudgmentTiles, renderOverview, resolveBrowserConfig, resolveContainerOptions, resolveCrop, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, withPixelRatio, writeAgentVerdict };
5373
5548
 
5374
5549
  //# sourceMappingURL=index.mjs.map