@cappa/core 0.4.2 → 0.4.3

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/src/compare.ts DELETED
@@ -1,191 +0,0 @@
1
- import fs from "node:fs";
2
- import blazediff from "@blazediff/core";
3
- import type { BlazeDiffOptions } from "@blazediff/types";
4
- import { getLogger } from "@cappa/logger";
5
- import { PNG } from "pngjs";
6
- import type { DiffConfig } from "./types";
7
-
8
- export type CompareOptions = BlazeDiffOptions;
9
-
10
- export interface CompareResult {
11
- numDiffPixels: number;
12
- totalPixels: number;
13
- percentDifference: number;
14
- diffBuffer?: Buffer; // PNG buffer of the diff image
15
- passed: boolean; // Whether the comparison passed based on threshold
16
- error?: string; // Error message if the comparison failed
17
- differentSizes: boolean; // Whether the images have different sizes
18
- }
19
-
20
- const compare = (
21
- image1: Uint8Array | Uint8ClampedArray,
22
- image2: Uint8Array | Uint8ClampedArray,
23
- diff: Uint8Array | Uint8ClampedArray | undefined,
24
- width: number,
25
- height: number,
26
- options?: BlazeDiffOptions,
27
- ) => {
28
- return blazediff(image1, image2, diff, width, height, options);
29
- };
30
-
31
- /**
32
- * Compare two PNG images and return the difference
33
- * @param image1 - First image (file path or Buffer)
34
- * @param image2 - Second image (file path or Buffer)
35
- * @param withDiff - Whether to create a diff image
36
- * @param options - Comparison options
37
- * @returns Comparison result
38
- */
39
- export async function compareImages(
40
- image1: string | Buffer,
41
- image2: string | Buffer,
42
- withDiff: boolean = false,
43
- options: DiffConfig = {},
44
- ): Promise<CompareResult> {
45
- const png1 = await loadPNG(image1);
46
- const png2 = await loadPNG(image2);
47
-
48
- const { width, height } = png1;
49
-
50
- if (width !== png2.width || height !== png2.height) {
51
- return {
52
- numDiffPixels: 0,
53
- totalPixels: 0,
54
- percentDifference: 0,
55
- passed: false,
56
- differentSizes: true,
57
- };
58
- }
59
-
60
- const diff = withDiff ? new PNG({ width, height }) : undefined;
61
-
62
- try {
63
- const numDiffPixels = compare(
64
- png1.data,
65
- png2.data,
66
- diff?.data,
67
- width,
68
- height,
69
- options,
70
- );
71
-
72
- const totalPixels = width * height;
73
- const percentDifference = (numDiffPixels / totalPixels) * 100;
74
-
75
- // Convert diff image to buffer
76
- const diffBuffer = diff ? PNG.sync.write(diff) : undefined;
77
-
78
- return {
79
- numDiffPixels,
80
- totalPixels,
81
- percentDifference,
82
- diffBuffer,
83
- passed: isPassed(percentDifference, numDiffPixels, options),
84
- differentSizes: false,
85
- };
86
- } catch (error) {
87
- getLogger().error((error as Error).message || "Unknown error");
88
-
89
- return {
90
- numDiffPixels: 0,
91
- totalPixels: 0,
92
- percentDifference: 0,
93
- passed: false,
94
- differentSizes: false,
95
- error: (error as Error).message || "Unknown error",
96
- };
97
- }
98
- }
99
-
100
- /**
101
- * Load a PNG image from file path or Buffer
102
- */
103
- async function loadPNG(source: string | Buffer): Promise<PNG> {
104
- if (Buffer.isBuffer(source)) {
105
- return PNG.sync.read(source);
106
- } else {
107
- const buffer = fs.readFileSync(source);
108
- return PNG.sync.read(buffer);
109
- }
110
- }
111
-
112
- /**
113
- * Save a comparison result diff image to file
114
- * @param result - Comparison result containing diffBuffer
115
- * @param outputPath - Path to save the diff image
116
- */
117
- export function saveDiffImage(result: CompareResult, outputPath: string): void {
118
- if (!result.diffBuffer) {
119
- throw new Error("No diff buffer available in comparison result");
120
- }
121
-
122
- fs.writeFileSync(outputPath, result.diffBuffer);
123
- }
124
-
125
- /**
126
- * Quick comparison function that returns only pass/fail
127
- * @param image1 - First image (file path or Buffer)
128
- * @param image2 - Second image (file path or Buffer)
129
- * @param options - Comparison options
130
- * @returns Whether the images match
131
- */
132
- export async function imagesMatch(
133
- image1: string | Buffer,
134
- image2: string | Buffer,
135
- options: DiffConfig = {},
136
- ): Promise<boolean> {
137
- const result = await compareImages(image1, image2, false, options);
138
-
139
- return result.passed;
140
- }
141
-
142
- /**
143
- * Check if the comparison passed based on the options
144
- * @param percentDifference - Percentage difference between the images
145
- * @param numDiffPixels - Number of different pixels
146
- * @param options - Comparison options
147
- * @returns Whether the comparison passed
148
- */
149
- const isPassed = (
150
- percentDifference: number,
151
- numDiffPixels: number,
152
- options: DiffConfig,
153
- ) => {
154
- if (options.maxDiffPercentage && options.maxDiffPixels) {
155
- return (
156
- percentDifference <= options.maxDiffPercentage &&
157
- numDiffPixels <= options.maxDiffPixels
158
- );
159
- }
160
-
161
- if (options.maxDiffPercentage) {
162
- return percentDifference <= options.maxDiffPercentage;
163
- }
164
-
165
- if (options.maxDiffPixels) {
166
- return numDiffPixels <= options.maxDiffPixels;
167
- }
168
-
169
- // fallback to 0 pixels
170
- return numDiffPixels === 0;
171
- };
172
-
173
- /**
174
- * Create different size png image with all pixels red
175
- * @returns
176
- */
177
- export function createDiffSizePngImage(width: number, height: number): Buffer {
178
- const png = new PNG({ width, height });
179
-
180
- for (let y = 0; y < height; y++) {
181
- for (let x = 0; x < width; x++) {
182
- const idx = (width * y + x) << 2;
183
- png.data[idx] = 255; // red
184
- png.data[idx + 1] = 0; // green
185
- png.data[idx + 2] = 0; // blue
186
- png.data[idx + 3] = 255; // alpha
187
- }
188
- }
189
-
190
- return PNG.sync.write(png);
191
- }
package/src/config.ts DELETED
@@ -1,12 +0,0 @@
1
- import type { ConfigEnv, PossiblePromise, UserConfig } from "./types";
2
-
3
- /**
4
- * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
5
- */
6
- export function defineConfig(
7
- options:
8
- | PossiblePromise<UserConfig>
9
- | ((env: ConfigEnv) => PossiblePromise<UserConfig>),
10
- ): typeof options {
11
- return options;
12
- }
@@ -1,83 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
- import { ScreenshotFileSystem } from "./filesystem";
6
-
7
- let tempDir: string;
8
-
9
- beforeEach(() => {
10
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "cappa-fs-"));
11
- fs.mkdirSync(path.join(tempDir, "actual"), { recursive: true });
12
- fs.mkdirSync(path.join(tempDir, "expected"), { recursive: true });
13
- fs.mkdirSync(path.join(tempDir, "diff"), { recursive: true });
14
- });
15
-
16
- afterEach(() => {
17
- fs.rmSync(tempDir, { recursive: true, force: true });
18
- });
19
-
20
- describe("ScreenshotFileSystem", () => {
21
- it("clears existing actual and diff directories", () => {
22
- const fileSystem = new ScreenshotFileSystem(tempDir);
23
-
24
- const actualFile = path.join(tempDir, "actual", "example.png");
25
- const diffFile = path.join(tempDir, "diff", "example.png");
26
-
27
- fs.writeFileSync(actualFile, "actual");
28
- fs.writeFileSync(diffFile, "diff");
29
-
30
- fileSystem.clearActual();
31
- fileSystem.clearDiff();
32
-
33
- expect(fs.existsSync(path.join(tempDir, "actual"))).toBe(false);
34
- expect(fs.existsSync(path.join(tempDir, "diff"))).toBe(false);
35
- });
36
-
37
- it("approves screenshots from absolute actual paths and removes diffs", () => {
38
- const fileSystem = new ScreenshotFileSystem(tempDir);
39
-
40
- const actualPath = path.join(tempDir, "actual", "component", "button.png");
41
- const expectedPath = path.join(
42
- tempDir,
43
- "expected",
44
- "component",
45
- "button.png",
46
- );
47
- const diffPath = path.join(tempDir, "diff", "component", "button.png");
48
-
49
- fs.mkdirSync(path.dirname(actualPath), { recursive: true });
50
- fs.mkdirSync(path.dirname(diffPath), { recursive: true });
51
-
52
- fs.writeFileSync(actualPath, "button");
53
- fs.writeFileSync(diffPath, "diff");
54
-
55
- const result = fileSystem.approveFromActualPath(actualPath);
56
-
57
- expect(fs.readFileSync(expectedPath, "utf-8")).toBe("button");
58
- expect(fs.existsSync(diffPath)).toBe(false);
59
- expect(result).toEqual({
60
- actualPath,
61
- expectedPath,
62
- diffPath,
63
- });
64
- });
65
-
66
- it("approves screenshots by logical name", () => {
67
- const fileSystem = new ScreenshotFileSystem(tempDir);
68
-
69
- const actualPath = path.join(
70
- tempDir,
71
- "actual",
72
- "pages",
73
- "home",
74
- "hero.png",
75
- );
76
- fs.mkdirSync(path.dirname(actualPath), { recursive: true });
77
- fs.writeFileSync(actualPath, "hero");
78
-
79
- const { expectedPath } = fileSystem.approveByName("pages/home/hero");
80
-
81
- expect(fs.readFileSync(expectedPath, "utf-8")).toBe("hero");
82
- });
83
- });
package/src/filesystem.ts DELETED
@@ -1,227 +0,0 @@
1
- import fs from "node:fs";
2
- import { glob } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- /**
6
- * Class for interacting with the local file system to store the screenshots.
7
- */
8
- export class ScreenshotFileSystem {
9
- private readonly actual: string;
10
- private readonly expected: string;
11
- private readonly diff: string;
12
-
13
- constructor(outputDir: string) {
14
- this.actual = path.resolve(outputDir, "actual");
15
- this.expected = path.resolve(outputDir, "expected");
16
- this.diff = path.resolve(outputDir, "diff");
17
-
18
- this.ensureParentDir(this.actual);
19
- this.ensureParentDir(this.expected);
20
- this.ensureParentDir(this.diff);
21
- }
22
-
23
- clearActual() {
24
- this.removeDir(this.actual);
25
- }
26
-
27
- clearDiff() {
28
- this.removeDir(this.diff);
29
- }
30
-
31
- getActualScreenshots(): Promise<string[]> {
32
- return Array.fromAsync(glob(path.resolve(this.actual, "**/*.png")));
33
- }
34
-
35
- getExpectedScreenshots(): Promise<string[]> {
36
- return Array.fromAsync(glob(path.resolve(this.expected, "**/*.png")));
37
- }
38
-
39
- getDiffScreenshots(): Promise<string[]> {
40
- return Array.fromAsync(glob(path.resolve(this.diff, "**/*.png")));
41
- }
42
-
43
- clearActualAndDiff() {
44
- this.clearActual();
45
- this.clearDiff();
46
- }
47
-
48
- /**
49
- * Approve a screenshot based on its actual file path.
50
- * @param actualFilePath - The path to the actual screenshot file.
51
- * @returns The paths to the actual, expected, and diff screenshot files.
52
- */
53
- approveFromActualPath(actualFilePath: string) {
54
- const actualAbsolute = this.resolveActualPath(actualFilePath);
55
- const relativePath = path.relative(this.actual, actualAbsolute);
56
-
57
- if (relativePath.startsWith("..")) {
58
- throw new Error(
59
- `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,
60
- );
61
- }
62
-
63
- return this.approveRelative(relativePath);
64
- }
65
-
66
- /**
67
- * Approve a screenshot based on its name.
68
- * @param name - The name of the screenshot. Can include '.png' extension.
69
- * @returns The paths to the actual, expected, and diff screenshot files.
70
- */
71
- approveByName(name: string) {
72
- const relativeWithExtension = name.endsWith(".png") ? name : `${name}.png`;
73
-
74
- return this.approveRelative(relativeWithExtension);
75
- }
76
-
77
- /**
78
- * Approve a screenshot based on a relative path.
79
- * @param relativePath - The relative path to the screenshot.
80
- * @returns The paths to the actual, expected, and diff screenshot files.
81
- */
82
- private approveRelative(relativePath: string) {
83
- const actualPath = path.resolve(this.actual, relativePath);
84
- const expectedPath = path.resolve(this.expected, relativePath);
85
- const diffPath = path.resolve(this.diff, relativePath);
86
-
87
- this.ensureParentDir(expectedPath);
88
-
89
- fs.copyFileSync(actualPath, expectedPath);
90
-
91
- if (fs.existsSync(diffPath)) {
92
- fs.unlinkSync(diffPath);
93
- }
94
-
95
- return {
96
- actualPath,
97
- expectedPath,
98
- diffPath,
99
- };
100
- }
101
-
102
- /**
103
- * Ensure the parent directory of a file exists. If not, it creates it.
104
- * @param filePath - The path to the file.
105
- */
106
- ensureParentDir(filePath: string) {
107
- const dir = path.dirname(filePath);
108
-
109
- if (!fs.existsSync(dir)) {
110
- fs.mkdirSync(dir, { recursive: true });
111
- }
112
- }
113
-
114
- /**
115
- * Remove a directory and all its contents.
116
- * @param dir - The path to the directory.
117
- */
118
- private removeDir(dir: string) {
119
- if (fs.existsSync(dir)) {
120
- fs.rmSync(dir, { recursive: true, force: true });
121
- }
122
- }
123
-
124
- /**
125
- * Get the actual directory path
126
- */
127
- getActualDir(): string {
128
- return this.actual;
129
- }
130
-
131
- /**
132
- * Get the expected directory path
133
- */
134
- getExpectedDir(): string {
135
- return this.expected;
136
- }
137
-
138
- /**
139
- * Get the diff directory path
140
- */
141
- getDiffDir(): string {
142
- return this.diff;
143
- }
144
-
145
- /**
146
- * Get the path to an actual screenshot file
147
- */
148
- getActualFilePath(filename: string): string {
149
- return path.resolve(this.actual, filename);
150
- }
151
-
152
- /**
153
- * Get the path to an expected screenshot file
154
- */
155
- getExpectedFilePath(filename: string): string {
156
- return path.resolve(this.expected, filename);
157
- }
158
-
159
- /**
160
- * Get the path to a diff screenshot file
161
- */
162
- getDiffFilePath(filename: string): string {
163
- return path.resolve(this.diff, filename);
164
- }
165
-
166
- /**
167
- * Write a file to the actual directory
168
- */
169
- writeActualFile(filename: string, data: Buffer): void {
170
- const filepath = this.getActualFilePath(filename);
171
- this.ensureParentDir(filepath);
172
- fs.writeFileSync(filepath, data);
173
- }
174
-
175
- /**
176
- * Write a file to the diff directory
177
- */
178
- writeDiffFile(filename: string, data: Buffer): void {
179
- const filepath = this.getDiffFilePath(filename);
180
- this.ensureParentDir(filepath);
181
- fs.writeFileSync(filepath, data);
182
- }
183
-
184
- /**
185
- * Check if an expected file exists
186
- */
187
- hasExpectedFile(filename: string): boolean {
188
- const expectedPath = this.getExpectedFilePath(filename);
189
- return fs.existsSync(expectedPath);
190
- }
191
-
192
- /**
193
- * Read an expected file
194
- */
195
- readExpectedFile(filename: string): Buffer {
196
- const expectedPath = this.getExpectedFilePath(filename);
197
- if (!fs.existsSync(expectedPath)) {
198
- throw new Error(`Expected image not found: ${expectedPath}`);
199
- }
200
- return fs.readFileSync(expectedPath);
201
- }
202
-
203
- /**
204
- * Resolve the actual path of a screenshot file.
205
- * @param filePath - The path to the screenshot file.
206
- * @returns The actual path of the screenshot file.
207
- */
208
- private resolveActualPath(filePath: string) {
209
- if (path.isAbsolute(filePath)) {
210
- return filePath;
211
- }
212
-
213
- return path.resolve(this.actual, filePath);
214
- }
215
-
216
- getRelativePath(directory: "actual" | "expected" | "diff", filePath: string) {
217
- const relativePath = path.relative(this[directory], filePath);
218
-
219
- if (relativePath.startsWith("..")) {
220
- throw new Error(
221
- `Cannot resolve relative path outside of ${directory} directory: ${filePath}`,
222
- );
223
- }
224
-
225
- return relativePath;
226
- }
227
- }
package/src/index.ts DELETED
@@ -1,53 +0,0 @@
1
- import { compareImages, imagesMatch } from "./compare";
2
- import { defineConfig } from "./config";
3
- import { ScreenshotFileSystem } from "./filesystem";
4
- import type { Plugin, PluginDef, PluginFunction } from "./plugin";
5
- import ScreenshotTool, {
6
- type ScreenshotCaptureDetails,
7
- type ScreenshotCaptureExtras,
8
- type ScreenshotCaptureResult,
9
- type ScreenshotVariantCaptureDetails,
10
- } from "./screenshot";
11
- import type {
12
- ChangedScreenshot,
13
- ConfigEnv,
14
- DeletedScreenshot,
15
- FailedScreenshot,
16
- NewScreenshot,
17
- PassedScreenshot,
18
- Screenshot,
19
- ScreenshotOptions,
20
- ScreenshotSettings,
21
- ScreenshotVariant,
22
- ScreenshotVariantWithUrl,
23
- UserConfig,
24
- Viewport,
25
- } from "./types";
26
-
27
- export {
28
- ScreenshotTool,
29
- ScreenshotFileSystem,
30
- defineConfig,
31
- compareImages,
32
- imagesMatch,
33
- type PluginFunction,
34
- type Plugin,
35
- type PluginDef,
36
- type ConfigEnv,
37
- type UserConfig,
38
- type ScreenshotOptions,
39
- type ScreenshotSettings,
40
- type ScreenshotVariant,
41
- type ScreenshotVariantWithUrl,
42
- type Screenshot,
43
- type NewScreenshot,
44
- type DeletedScreenshot,
45
- type ChangedScreenshot,
46
- type PassedScreenshot,
47
- type FailedScreenshot,
48
- type ScreenshotCaptureResult,
49
- type ScreenshotCaptureDetails,
50
- type ScreenshotVariantCaptureDetails,
51
- type ScreenshotCaptureExtras,
52
- type Viewport,
53
- };
package/src/plugin.ts DELETED
@@ -1,43 +0,0 @@
1
- import type { Page } from "playwright-core";
2
- import type ScreenshotTool from "./screenshot";
3
-
4
- /**
5
- * Plugin task interface
6
- */
7
- export type PluginTask<TData = any> = {
8
- id: string; // unique identifier for logging
9
- url: string; // url of the task
10
- data?: TData; // plugin-specific task data
11
- };
12
-
13
- /**
14
- * Plugin function type definition (legacy)
15
- */
16
- export type PluginFunction = (screenshotTool: ScreenshotTool) => Promise<any[]>;
17
-
18
- /**
19
- * Plugin definition interface
20
- */
21
- export type PluginDef<TResult = any, TContext = any, TData = any> = {
22
- name: string;
23
- description: string;
24
-
25
- // Phase 1: Discover all tasks
26
- discover: (screenshotTool: ScreenshotTool) => Promise<PluginTask<TData>[]>;
27
-
28
- // Phase 2: Execute a single task
29
- execute: (
30
- task: PluginTask<TData>,
31
- page: Page,
32
- screenshotTool: ScreenshotTool,
33
- context: TContext,
34
- ) => Promise<TResult>;
35
-
36
- // Optional: called once per page before executing tasks on that page
37
- initPage?: (page: Page, screenshotTool: ScreenshotTool) => Promise<TContext>;
38
- };
39
-
40
- /**
41
- * Plugin function type definition
42
- */
43
- export type Plugin<Config = any> = (config?: Config) => PluginDef;
@@ -1,40 +0,0 @@
1
- import { initLogger } from "@cappa/logger";
2
- import { beforeAll, describe, expect, it } from "vitest";
3
- import ScreenshotTool from "./screenshot";
4
-
5
- beforeAll(() => {
6
- initLogger(0);
7
- });
8
-
9
- describe("ScreenshotTool getVariantFilename", () => {
10
- it("appends the variant id as a suffix", () => {
11
- const tool = new ScreenshotTool({ outputDir: "/tmp" });
12
-
13
- const filename = tool.getVariantFilename("components/Button.png", {
14
- id: "mobile",
15
- });
16
-
17
- expect(filename).toBe("components/Button--mobile.png");
18
- });
19
-
20
- it("sanitizes invalid characters in the variant id", () => {
21
- const tool = new ScreenshotTool({ outputDir: "/tmp" });
22
-
23
- const filename = tool.getVariantFilename("Badge.png", {
24
- id: "📱 mobile view",
25
- });
26
-
27
- expect(filename).toBe("Badge--mobile-view.png");
28
- });
29
-
30
- it("uses a provided filename when present", () => {
31
- const tool = new ScreenshotTool({ outputDir: "/tmp" });
32
-
33
- const filename = tool.getVariantFilename("Badge.png", {
34
- id: "mobile",
35
- filename: "Badge/mobile-custom.png",
36
- });
37
-
38
- expect(filename).toBe("Badge/mobile-custom.png");
39
- });
40
- });