@cappa/core 0.0.26 → 0.1.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/src/screenshot.ts CHANGED
@@ -5,40 +5,63 @@ import {
5
5
  type BrowserContext,
6
6
  chromium,
7
7
  firefox,
8
- Locator,
8
+ type Locator,
9
9
  type Page,
10
10
  type PageScreenshotOptions,
11
11
  webkit,
12
12
  } from "playwright-core";
13
+ import {
14
+ type CompareOptions,
15
+ type CompareResult,
16
+ compareImages,
17
+ } from "./compare";
18
+ import type { DiffConfig } from "./types";
19
+
20
+ const defaultDiffConfig: DiffConfig = {
21
+ threshold: 0.1,
22
+ includeAA: false,
23
+ fastBufferCheck: true,
24
+ maxDiffPixels: 0,
25
+ maxDiffPercentage: 0,
26
+ };
13
27
 
14
28
  class ScreenshotTool {
15
29
  browserType: string;
16
30
  headless: boolean;
17
31
  viewport: { width: number; height: number };
18
32
  outputDir: string;
33
+ actualDir: string;
34
+ diffDir: string;
35
+ expectedDir: string;
19
36
  fullPage: boolean;
20
37
  browser: Browser | null = null;
21
38
  context: BrowserContext | null = null;
22
39
  page: Page | null = null;
40
+ diff: DiffConfig;
41
+
23
42
  constructor(options: {
24
43
  browserType?: string;
25
44
  headless?: boolean;
26
45
  viewport?: { width: number; height: number };
27
46
  outputDir?: string;
28
47
  fullPage?: boolean;
48
+ diff?: DiffConfig;
29
49
  }) {
30
50
  this.browserType = options.browserType || "chromium";
31
51
  this.headless = options.headless !== false; // Default to headless
32
52
  this.viewport = options.viewport || { width: 1920, height: 1080 };
33
53
  this.outputDir = options.outputDir || "./screenshots";
34
54
  this.fullPage = options.fullPage !== false; // Default to full page
55
+ this.diff = { ...defaultDiffConfig, ...options.diff };
56
+ // Set up subdirectories
57
+ this.actualDir = path.join(this.outputDir, "actual");
58
+ this.diffDir = path.join(this.outputDir, "diff");
59
+ this.expectedDir = path.join(this.outputDir, "expected");
35
60
  }
36
61
 
37
62
  async init() {
38
- // Create output directory if it doesn't exist
39
- if (!fs.existsSync(this.outputDir)) {
40
- fs.mkdirSync(this.outputDir, { recursive: true });
41
- }
63
+ // Create output directories if they don't exist
64
+ this.createDirectories();
42
65
 
43
66
  // Launch browser based on type
44
67
  const browserMap = {
@@ -55,7 +78,6 @@ class ScreenshotTool {
55
78
 
56
79
  this.browser = await browserClass.launch({
57
80
  headless: this.headless,
58
- chromiumSandbox: true,
59
81
  });
60
82
 
61
83
  const defaultUserAgent = (await this.browser.newContext())
@@ -88,9 +110,38 @@ class ScreenshotTool {
88
110
  await page.goto(url, { waitUntil: "domcontentloaded" });
89
111
  }
90
112
 
113
+ private createDirectories() {
114
+ // Create main output directory and subdirectories
115
+ const directories = [
116
+ this.outputDir,
117
+ this.actualDir,
118
+ this.diffDir,
119
+ this.expectedDir,
120
+ ];
121
+
122
+ for (const dir of directories) {
123
+ if (!fs.existsSync(dir)) {
124
+ fs.mkdirSync(dir, { recursive: true });
125
+ console.log(`Created directory: ${dir}`);
126
+ }
127
+ }
128
+ }
129
+
130
+ getActualFilePath(filename: string): string {
131
+ return path.join(this.actualDir, filename);
132
+ }
133
+
134
+ getDiffFilePath(filename: string): string {
135
+ return path.join(this.diffDir, filename);
136
+ }
137
+
138
+ getExpectedFilePath(filename: string): string {
139
+ return path.join(this.expectedDir, filename);
140
+ }
141
+
142
+ // Keep original method for backward compatibility
91
143
  getFilePath(filename: string) {
92
- const filepath = path.join(this.outputDir, filename);
93
- return filepath;
144
+ return this.getActualFilePath(filename);
94
145
  }
95
146
 
96
147
  async takeScreenshot(
@@ -98,8 +149,6 @@ class ScreenshotTool {
98
149
  filename: string,
99
150
  options: {
100
151
  fullPage?: boolean;
101
- waitForSelector?: string;
102
- waitForTimeout?: number;
103
152
  mask?: Locator[];
104
153
  omitBackground?: boolean;
105
154
  } = {},
@@ -109,22 +158,8 @@ class ScreenshotTool {
109
158
  }
110
159
 
111
160
  try {
112
- // Wait for selector if specified
113
- if (options.waitForSelector) {
114
- console.log(`Waiting for selector: ${options.waitForSelector}`);
115
- await page.waitForSelector(options.waitForSelector, { timeout: 10000 });
116
- }
117
-
118
- // Wait for custom timeout or default
119
- const waitTime =
120
- options.waitForTimeout !== undefined ? options.waitForTimeout : 0;
121
- if (waitTime > 0) {
122
- console.log(`Waiting for ${waitTime}ms for dynamic content`);
123
- await page.waitForTimeout(waitTime);
124
- }
125
-
126
- // Generate filename
127
- const filepath = this.getFilePath(filename);
161
+ // Generate filename - save to actual directory
162
+ const filepath = this.getActualFilePath(filename);
128
163
 
129
164
  // Take screenshot
130
165
  const screenshotOptions = {
@@ -177,7 +212,8 @@ class ScreenshotTool {
177
212
  const filename =
178
213
  (options.filename as string | undefined) ||
179
214
  `${selector.replace(/[^a-zA-Z0-9]/g, "_")}.png`;
180
- const filepath = this.getFilePath(filename);
215
+ // Save to actual directory
216
+ const filepath = this.getActualFilePath(filename);
181
217
 
182
218
  const elementScreenshotOptions = {
183
219
  path: filepath,
@@ -199,6 +235,99 @@ class ScreenshotTool {
199
235
  }
200
236
  }
201
237
 
238
+ async takeScreenshotWithComparison(
239
+ page: Page,
240
+ filename: string,
241
+ referenceImage: Buffer,
242
+ options: {
243
+ fullPage?: boolean;
244
+ mask?: Locator[];
245
+ omitBackground?: boolean;
246
+ // Comparison options
247
+ compareOptions?: CompareOptions;
248
+ maxDifferencePercent?: number;
249
+ saveDiffImage?: boolean;
250
+ diffImageFilename?: string;
251
+ } = {},
252
+ ): Promise<{
253
+ screenshotPath: string;
254
+ comparisonResult: CompareResult;
255
+ diffImagePath?: string;
256
+ }> {
257
+ if (!this.browser) {
258
+ throw new Error("Browser not initialized");
259
+ }
260
+
261
+ try {
262
+ // Generate filename and take screenshot - save to actual directory
263
+ const filepath = this.getActualFilePath(filename);
264
+ fs.mkdirSync(path.dirname(filepath), { recursive: true });
265
+
266
+ // Take screenshot and get buffer
267
+ const screenshotOptions = {
268
+ fullPage:
269
+ (options.fullPage as boolean) !== undefined
270
+ ? options.fullPage
271
+ : this.fullPage,
272
+ type: "png" as const,
273
+ timeout: 60000,
274
+ mask: options.mask,
275
+ omitBackground: options.omitBackground,
276
+ scale: "css" as const,
277
+ } satisfies PageScreenshotOptions;
278
+
279
+ // Get screenshot as buffer for comparison
280
+ const screenshotBuffer = await page.screenshot(screenshotOptions);
281
+
282
+ // Save screenshot to actual directory
283
+ fs.writeFileSync(filepath, screenshotBuffer);
284
+
285
+ console.log(`Screenshot saved: ${filepath}`);
286
+
287
+ // Perform comparison
288
+ const comparisonResult = await compareImages(
289
+ screenshotBuffer,
290
+ referenceImage,
291
+ true,
292
+ { ...this.diff, ...options.compareOptions },
293
+ );
294
+
295
+ console.log(
296
+ `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${
297
+ comparisonResult.passed ? "PASSED" : "FAILED"
298
+ })`,
299
+ );
300
+
301
+ let diffImagePath: string | undefined;
302
+
303
+ // Save diff image if requested and there are differences
304
+ if (
305
+ options.saveDiffImage &&
306
+ comparisonResult.diffBuffer &&
307
+ !comparisonResult.passed
308
+ ) {
309
+ const diffFilename = options.diffImageFilename || filename;
310
+ // Save to diff directory
311
+ diffImagePath = this.getDiffFilePath(diffFilename);
312
+
313
+ fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
314
+ fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
315
+ }
316
+
317
+ return {
318
+ screenshotPath: filepath,
319
+ comparisonResult,
320
+ diffImagePath,
321
+ };
322
+ } catch (error) {
323
+ console.error(
324
+ `Error taking screenshot with comparison of ${page.url()}:`,
325
+ (error as Error).message,
326
+ );
327
+ throw error;
328
+ }
329
+ }
330
+
202
331
  async batchScreenshots(urls: string[], options = {}) {
203
332
  const results: {
204
333
  url: string;
@@ -260,7 +389,8 @@ class ScreenshotTool {
260
389
  await page.waitForTimeout(2000);
261
390
 
262
391
  const filename = `${viewport.name}.png`;
263
- const filepath = this.getFilePath(filename);
392
+ // Save to actual directory
393
+ const filepath = this.getActualFilePath(filename);
264
394
 
265
395
  const responsiveScreenshotOptions = {
266
396
  path: filepath,
@@ -293,6 +423,21 @@ class ScreenshotTool {
293
423
 
294
424
  return results;
295
425
  }
426
+
427
+ // Utility method to check if expected image exists
428
+ hasExpectedImage(filename: string): boolean {
429
+ const expectedPath = this.getExpectedFilePath(filename);
430
+ return fs.existsSync(expectedPath);
431
+ }
432
+
433
+ // Utility method to get expected image as buffer (for future approval process)
434
+ getExpectedImageBuffer(filename: string): Buffer {
435
+ const expectedPath = this.getExpectedFilePath(filename);
436
+ if (!fs.existsSync(expectedPath)) {
437
+ throw new Error(`Expected image not found: ${expectedPath}`);
438
+ }
439
+ return fs.readFileSync(expectedPath);
440
+ }
296
441
  }
297
442
 
298
443
  export default ScreenshotTool;
package/src/types.ts CHANGED
@@ -2,6 +2,48 @@ import type { Plugin, PluginDef } from "./plugin";
2
2
 
3
3
  export type PossiblePromise<T> = Promise<T> | T;
4
4
 
5
+ export interface DiffConfig {
6
+ /**
7
+ * Matching threshold (0-1). Lower = more sensitive
8
+ * Default = 0.1
9
+ *
10
+ * This affects how similar a pixel needs to be to the reference image to be considered the same.
11
+ */
12
+ threshold?: number;
13
+ /**
14
+ * Include anti-aliased pixels in diff count
15
+ * Default = false
16
+ *
17
+ * For most users this should be false, because it makes comparisons very sensitive to sub-pixel differences of
18
+ * fonts and other UI elements.
19
+ */
20
+ includeAA?: boolean;
21
+ /**
22
+ * Use fast buffer comparison for identical images
23
+ * Default = true
24
+ */
25
+ fastBufferCheck?: boolean;
26
+ /**
27
+ * Maximum number of different pixels
28
+ * Default = 0
29
+ *
30
+ * The amount of pixels that can be different before the comparison fails.
31
+ */
32
+ maxDiffPixels?: number;
33
+ /**
34
+ * Maximum percentage of pixels different
35
+ * Default = 0
36
+ *
37
+ * The amount of pixels that can be different before the comparison fails as a percentage of the total pixels.
38
+ * 0 = no difference, 100 = 100% difference.
39
+ *
40
+ * Since this is a relative value, it is affected by the size of the images. A 100px image with a 10% difference
41
+ * is 10 pixels different, but a 1000px image with a 10% difference is 100 pixels different. On very large full page screenshots
42
+ * this can mean that small changes still slip through.
43
+ */
44
+ maxDiffPercentage?: number;
45
+ }
46
+
5
47
  /**
6
48
  * Config used in `cappa.config.ts`
7
49
  *
@@ -18,6 +60,7 @@ export type UserConfig = {
18
60
  */
19
61
  root?: string;
20
62
  outputDir?: string;
63
+ diff?: DiffConfig;
21
64
  /**
22
65
  * An array of Cappa plugins used for generation. Each plugin may have additional configurable options (defined within the plugin itself). If a plugin relies on another plugin, an error will occur if the required dependency is missing. Refer to "pre" for more details.
23
66
  */
@@ -39,3 +82,13 @@ export interface Exposed {
39
82
  getBaseScreenshotOptions(): ScreenshotOptions;
40
83
  waitBrowserMetricsStable(): Promise<void>;
41
84
  }
85
+
86
+ export interface Screenshot {
87
+ id: string;
88
+ name: string;
89
+ category: "new" | "deleted" | "changed" | "passed";
90
+ actualPath?: string;
91
+ expectedPath?: string;
92
+ diffPath?: string;
93
+ approved?: boolean;
94
+ }
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: "node",
6
+ coverage: {
7
+ reporter: ["text", "json", "html"],
8
+ exclude: ["node_modules/", "dist/", "**/*.test.ts", "**/*.config.ts"],
9
+ },
10
+ },
11
+ });
@@ -1,5 +0,0 @@
1
-
2
-
3
- > @cappa/core@0.0.14 tsc /home/tim/code/work/cappa/packages/core
4
- > tsc
5
-