@cappa/core 0.4.2 → 0.4.4

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 DELETED
@@ -1,795 +0,0 @@
1
- import path from "node:path";
2
- import { getLogger, type Logger } from "@cappa/logger";
3
- import {
4
- type Browser,
5
- type BrowserContext,
6
- chromium,
7
- firefox,
8
- type Page,
9
- type PageScreenshotOptions,
10
- webkit,
11
- } from "playwright-core";
12
- import {
13
- type CompareResult,
14
- compareImages,
15
- createDiffSizePngImage,
16
- } from "./compare";
17
- import { ScreenshotFileSystem } from "./filesystem";
18
- import type {
19
- DiffConfig,
20
- ScreenshotOptions,
21
- ScreenshotSettings,
22
- ScreenshotVariant,
23
- ScreenshotVariantWithUrl,
24
- } from "./types";
25
-
26
- const defaultDiffConfig: DiffConfig = {
27
- threshold: 0.1,
28
- includeAA: false,
29
- fastBufferCheck: true,
30
- maxDiffPixels: 0,
31
- maxDiffPercentage: 0,
32
- };
33
-
34
- export interface ScreenshotCaptureDetails {
35
- filename: string;
36
- filepath?: string;
37
- comparisonResult?: CompareResult;
38
- diffImagePath?: string;
39
- skipped?: boolean;
40
- }
41
-
42
- export interface ScreenshotVariantCaptureDetails
43
- extends ScreenshotCaptureDetails {
44
- id: string;
45
- label?: string;
46
- }
47
-
48
- export interface ScreenshotCaptureResult {
49
- base: ScreenshotCaptureDetails;
50
- variants: ScreenshotVariantCaptureDetails[];
51
- }
52
-
53
- export interface ScreenshotCaptureExtras {
54
- saveDiffImage?: boolean;
55
- diffImageFilename?: string;
56
- variants?: Record<
57
- string,
58
- {
59
- saveDiffImage?: boolean;
60
- diffImageFilename?: string;
61
- }
62
- >;
63
- }
64
-
65
- class ScreenshotTool {
66
- browserType: "chromium" | "firefox" | "webkit";
67
- headless: boolean;
68
- viewport: { width: number; height: number };
69
- outputDir: string;
70
- browser: Browser | null = null;
71
- context: BrowserContext | null = null;
72
- page: Page | null = null;
73
- concurrency: number;
74
- contexts: BrowserContext[] = [];
75
- pages: Page[] = [];
76
- diff: DiffConfig;
77
- logger: Logger;
78
- retries: number;
79
- filesystem: ScreenshotFileSystem;
80
- logConsoleEvents: boolean;
81
-
82
- constructor(options: {
83
- browserType?: "chromium" | "firefox" | "webkit";
84
- headless?: boolean;
85
- viewport?: { width: number; height: number };
86
- outputDir?: string;
87
- diff?: DiffConfig;
88
- retries?: number;
89
- concurrency?: number;
90
- logConsoleEvents?: boolean;
91
- }) {
92
- this.browserType = options.browserType || "chromium";
93
- this.headless = options.headless !== false; // Default to headless
94
- this.viewport = options.viewport || { width: 1920, height: 1080 };
95
- this.outputDir = options.outputDir || "./screenshots";
96
- this.diff = { ...defaultDiffConfig, ...options.diff };
97
- this.concurrency = Math.max(1, options.concurrency || 1);
98
- this.logConsoleEvents = options.logConsoleEvents ?? true;
99
-
100
- this.logger = getLogger();
101
- this.retries = options.retries || 2;
102
- this.filesystem = new ScreenshotFileSystem(this.outputDir);
103
- }
104
-
105
- /**
106
- * Initialize playwright and page
107
- */
108
- async init() {
109
- // Launch browser based on type
110
- const browserMap = {
111
- chromium,
112
- firefox,
113
- webkit,
114
- };
115
-
116
- const browserClass = browserMap[this.browserType];
117
- if (!browserClass) {
118
- throw new Error(`Unsupported browser type: ${this.browserType}`);
119
- }
120
-
121
- this.browser = await browserClass.launch({
122
- headless: this.headless,
123
- });
124
-
125
- const defaultUserAgent = (await this.browser.newContext())
126
- .newPage()
127
- .then((page) => page.evaluate(() => navigator.userAgent));
128
-
129
- // Create N contexts and pages
130
- this.contexts = [];
131
- this.pages = [];
132
-
133
- for (let i = 0; i < this.concurrency; i++) {
134
- const context = await this.browser.newContext({
135
- reducedMotion: "reduce",
136
- deviceScaleFactor: 2,
137
- userAgent: `${await defaultUserAgent} CappaStorybook`,
138
- viewport: this.viewport,
139
- });
140
- const page = await context.newPage();
141
-
142
- this.contexts.push(context);
143
- this.pages.push(page);
144
- }
145
-
146
- // Backward compatibility
147
- this.context = this.contexts[0] ?? null;
148
- this.page = this.pages[0] ?? null;
149
- }
150
-
151
- /**
152
- * Closes browser
153
- * If not closed, the process will not exit
154
- */
155
- async close() {
156
- for (const context of this.contexts) {
157
- await context.close();
158
- }
159
- if (this.browser) {
160
- await this.browser.close();
161
- }
162
- }
163
-
164
- /**
165
- * Navigates to a URL with "domcontentloaded" waitUntil
166
- */
167
- async goTo(page: Page, url: string) {
168
- if (!this.context) {
169
- throw new Error("Browser not initialized");
170
- }
171
- await page.goto(url, { waitUntil: "domcontentloaded" });
172
- }
173
-
174
- /**
175
- * Takes a screenshot of the page
176
- */
177
- async takeScreenshot(
178
- page: Page,
179
- filename: string,
180
- options: ScreenshotSettings,
181
- ) {
182
- if (!this.browser) {
183
- throw new Error("Browser not initialized");
184
- }
185
-
186
- if (options.skip) {
187
- return;
188
- }
189
-
190
- try {
191
- // Generate filename - save to actual directory
192
- const filepath = this.filesystem.getActualFilePath(filename);
193
-
194
- // Ensure parent directories exist before taking screenshot
195
- this.filesystem.ensureParentDir(filepath);
196
-
197
- // Take screenshot
198
- const screenshotOptions = {
199
- path: filepath,
200
- fullPage: options.fullPage,
201
- type: "png" as const,
202
- timeout: 60000,
203
- mask: options.mask,
204
- omitBackground: options.omitBackground,
205
- scale: "css" as const,
206
- animations: "disabled",
207
- caret: "hide",
208
- } satisfies PageScreenshotOptions;
209
-
210
- await this.withViewport(page, options.viewport, async () => {
211
- if (options.delay) {
212
- await page.waitForTimeout(options.delay);
213
- }
214
-
215
- await page.screenshot(screenshotOptions);
216
- });
217
-
218
- this.logger.success(`Screenshot saved: ${filepath}`);
219
-
220
- return filepath;
221
- } catch (error) {
222
- this.logger.error(
223
- `Error taking screenshot of ${page.url()}:`,
224
- (error as Error).message,
225
- );
226
- throw error;
227
- }
228
- }
229
-
230
- /**
231
- * Sets the viewport size and executes the action, ensuring the original viewport is restored
232
- * even if the action throws an error.
233
- */
234
- private async withViewport<T>(
235
- page: Page,
236
- viewport: ScreenshotSettings["viewport"],
237
- action: () => Promise<T>,
238
- ): Promise<T> {
239
- if (!viewport) {
240
- return action();
241
- }
242
-
243
- const previousViewport = page.viewportSize();
244
-
245
- // Check if the new viewport is the same as the current one
246
- if (
247
- previousViewport &&
248
- previousViewport.width === viewport.width &&
249
- previousViewport.height === viewport.height
250
- ) {
251
- return action();
252
- }
253
-
254
- await page.setViewportSize(viewport);
255
-
256
- try {
257
- return await action();
258
- } finally {
259
- // Always restore the original viewport, even if the action throws an error
260
- if (previousViewport) {
261
- await page.setViewportSize(previousViewport);
262
- }
263
- }
264
- }
265
-
266
- /**
267
- * Takes a screenshot and returns the buffer (for comparison purposes)
268
- */
269
- async takeScreenshotBuffer(
270
- page: Page,
271
- options: ScreenshotSettings,
272
- ): Promise<Buffer> {
273
- if (!this.browser) {
274
- throw new Error("Browser not initialized");
275
- }
276
-
277
- if (options.skip) {
278
- throw new Error("Screenshot skipped");
279
- }
280
-
281
- try {
282
- // Take screenshot without saving to file
283
- const screenshotOptions = {
284
- fullPage: options.fullPage,
285
- type: "png" as const,
286
- timeout: 60000,
287
- mask: options.mask,
288
- omitBackground: options.omitBackground,
289
- scale: "css" as const,
290
- animations: "disabled",
291
- caret: "hide",
292
- } satisfies PageScreenshotOptions;
293
-
294
- const buffer = await this.withViewport(
295
- page,
296
- options.viewport,
297
- async () => {
298
- if (options.delay) {
299
- await page.waitForTimeout(options.delay);
300
- }
301
-
302
- return page.screenshot(screenshotOptions);
303
- },
304
- );
305
-
306
- return buffer;
307
- } catch (error) {
308
- this.logger.error(
309
- `Error taking screenshot of ${page.url()}:`,
310
- (error as Error).message,
311
- );
312
- throw error;
313
- }
314
- }
315
-
316
- async takeScreenshotWithComparison(
317
- page: Page,
318
- filename: string,
319
- referenceImage: Buffer,
320
- options: ScreenshotSettings & {
321
- saveDiffImage?: boolean;
322
- diffImageFilename?: string;
323
- },
324
- ): Promise<{
325
- screenshotPath: string;
326
- comparisonResult: CompareResult;
327
- diffImagePath?: string;
328
- }> {
329
- if (!this.browser) {
330
- throw new Error("Browser not initialized");
331
- }
332
-
333
- try {
334
- // Generate filename and take screenshot - save to actual directory
335
- const filepath = this.filesystem.getActualFilePath(filename);
336
-
337
- const screenshotSettings: ScreenshotSettings = {
338
- fullPage: options.fullPage,
339
- mask: options.mask,
340
- omitBackground: options.omitBackground,
341
- delay: options.delay,
342
- viewport: options.viewport,
343
- };
344
-
345
- const retryScreenshot = await this.retryScreenshot(
346
- page,
347
- referenceImage,
348
- screenshotSettings,
349
- );
350
-
351
- if (!retryScreenshot.screenshotPath) {
352
- throw new Error("Screenshot buffer is undefined");
353
- }
354
-
355
- // Save screenshot to actual directory
356
- this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
357
- this.logger.debug(`Actual screenshot saved: ${filepath}`);
358
-
359
- if (retryScreenshot.passed) {
360
- this.logger.success(`Screenshot passed visual comparison`);
361
- } else {
362
- this.logger.error(`Screenshot failed visual comparison`);
363
- }
364
-
365
- let diffImagePath: string | undefined;
366
-
367
- // Save diff image if requested and there are differences
368
- if (
369
- options.saveDiffImage &&
370
- retryScreenshot.comparisonResult.diffBuffer &&
371
- !retryScreenshot.passed
372
- ) {
373
- const diffFilename = options.diffImageFilename || filename;
374
- // Save to diff directory
375
- diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
376
-
377
- this.filesystem.writeDiffFile(
378
- diffFilename,
379
- retryScreenshot.comparisonResult.diffBuffer,
380
- );
381
-
382
- this.logger.debug(`Diff image saved: ${diffImagePath}`);
383
- }
384
-
385
- // different sizes diff image
386
- if (retryScreenshot.comparisonResult.differentSizes) {
387
- this.logger.warn(`Screenshot has different sizes than reference image`);
388
-
389
- const diffFilename = options.diffImageFilename || filename;
390
- diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
391
- const diffBuffer = createDiffSizePngImage(200, 200);
392
-
393
- this.filesystem.writeDiffFile(diffFilename, diffBuffer);
394
-
395
- this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
396
- }
397
-
398
- return {
399
- screenshotPath: filepath,
400
- comparisonResult: retryScreenshot.comparisonResult,
401
- diffImagePath,
402
- };
403
- } catch (error) {
404
- this.logger.error(
405
- `Error taking screenshot with comparison of ${page.url()}:`,
406
- (error as Error).message,
407
- );
408
- throw error;
409
- }
410
- }
411
-
412
- async retryScreenshot(
413
- page: Page,
414
- referenceImage: Buffer,
415
- options: ScreenshotSettings,
416
- ) {
417
- for (let i = 0; i < this.retries; i++) {
418
- try {
419
- const screenshotBuffer = await this.takeScreenshotBuffer(page, {
420
- ...options,
421
- delay: this.getIncBackoffDelay(i, options.delay || 0),
422
- });
423
-
424
- if (!screenshotBuffer) {
425
- throw new Error("Screenshot buffer is undefined");
426
- }
427
-
428
- const comparisonResult = await compareImages(
429
- screenshotBuffer,
430
- referenceImage,
431
- true,
432
- this.diff,
433
- );
434
-
435
- // bail early if the images are different sizes
436
- if (comparisonResult.differentSizes) {
437
- return {
438
- screenshotPath: screenshotBuffer,
439
- comparisonResult,
440
- passed: false,
441
- };
442
- }
443
-
444
- // last retry
445
- if (i === this.retries - 1 && !comparisonResult.passed) {
446
- this.logger.error(
447
- `Failed to match screenshot after ${this.retries} retries`,
448
- );
449
- return {
450
- screenshotPath: screenshotBuffer,
451
- comparisonResult,
452
- passed: false,
453
- };
454
- }
455
-
456
- if (comparisonResult.passed) {
457
- return {
458
- screenshotPath: screenshotBuffer,
459
- comparisonResult,
460
- passed: true,
461
- };
462
- } else {
463
- this.logger.warn(
464
- `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,
465
- );
466
- }
467
- } catch (error) {
468
- this.logger.error(
469
- `Error taking screenshot after ${i + 1} retries:`,
470
- (error as Error).message,
471
- );
472
- }
473
- }
474
-
475
- return {
476
- screenshotPath: null,
477
- comparisonResult: null,
478
- passed: false,
479
- };
480
- }
481
-
482
- getVariantFilename(filename: string, variant: ScreenshotVariant): string {
483
- if (variant.filename) {
484
- return variant.filename;
485
- }
486
-
487
- const parsed = path.parse(filename);
488
- const sanitizedId = variant.id
489
- .trim()
490
- .replace(/[^a-zA-Z0-9_-]+/g, "-")
491
- .replace(/-+/g, "-")
492
- .replace(/^-|-$/g, "");
493
- const suffix = sanitizedId || "variant";
494
- const ext = parsed.ext || ".png";
495
- const variantName = `${parsed.name}--${suffix}${ext}`;
496
-
497
- return parsed.dir ? path.join(parsed.dir, variantName) : variantName;
498
- }
499
-
500
- /**
501
- * Captures a single screenshot with the given options
502
- */
503
- private async captureSingleScreenshot(
504
- page: Page,
505
- filename: string,
506
- options: ScreenshotSettings,
507
- extras: {
508
- saveDiffImage?: boolean;
509
- diffImageFilename?: string;
510
- } = {},
511
- ): Promise<ScreenshotCaptureDetails> {
512
- const result: ScreenshotCaptureDetails = { filename };
513
-
514
- if (options.skip) {
515
- result.skipped = true;
516
- return result;
517
- }
518
-
519
- const saveDiff = extras.saveDiffImage ?? false;
520
- const diffFilename = extras.diffImageFilename ?? filename;
521
-
522
- if (!this.filesystem.hasExpectedFile(filename)) {
523
- this.logger.debug(
524
- `Expected image not found for ${filename}, taking screenshot`,
525
- );
526
-
527
- result.filepath = await this.takeScreenshot(page, filename, options);
528
- } else {
529
- const { screenshotPath, comparisonResult, diffImagePath } =
530
- await this.takeScreenshotWithComparison(
531
- page,
532
- filename,
533
- this.filesystem.readExpectedFile(filename),
534
- {
535
- ...options,
536
- saveDiffImage: saveDiff,
537
- diffImageFilename: diffFilename,
538
- },
539
- );
540
-
541
- result.filepath = screenshotPath;
542
- result.comparisonResult = comparisonResult;
543
- result.diffImagePath = diffImagePath;
544
- }
545
-
546
- return result;
547
- }
548
-
549
- async capture(
550
- page: Page,
551
- filename: string,
552
- options: ScreenshotOptions,
553
- extras: ScreenshotCaptureExtras = {},
554
- ): Promise<ScreenshotCaptureResult> {
555
- if (!this.browser) {
556
- throw new Error("Browser not initialized");
557
- }
558
-
559
- const { variants = [], ...baseOptions } = options;
560
- const baseResult: ScreenshotCaptureDetails = { filename };
561
- const variantResults: ScreenshotVariantCaptureDetails[] = [];
562
-
563
- const baseSaveDiff = extras.saveDiffImage ?? false;
564
- const baseDiffFilename = extras.diffImageFilename ?? filename;
565
-
566
- if (baseOptions.skip) {
567
- return {
568
- base: { ...baseResult, skipped: true },
569
- variants: variants.map((variant) => ({
570
- id: variant.id,
571
- label: variant.label,
572
- filename: this.getVariantFilename(filename, variant),
573
- skipped: true,
574
- })),
575
- };
576
- }
577
-
578
- // Capture base screenshot
579
- const baseCaptureResult = await this.captureSingleScreenshot(
580
- page,
581
- filename,
582
- baseOptions,
583
- {
584
- saveDiffImage: baseSaveDiff,
585
- diffImageFilename: baseDiffFilename,
586
- },
587
- );
588
-
589
- baseResult.filepath = baseCaptureResult.filepath;
590
- baseResult.comparisonResult = baseCaptureResult.comparisonResult;
591
- baseResult.diffImagePath = baseCaptureResult.diffImagePath;
592
- baseResult.skipped = baseCaptureResult.skipped;
593
-
594
- for (const variant of variants) {
595
- const variantFilename = this.getVariantFilename(filename, variant);
596
- const variantOptions: ScreenshotSettings = {
597
- ...baseOptions,
598
- ...variant.options,
599
- };
600
-
601
- const variantResult: ScreenshotVariantCaptureDetails = {
602
- id: variant.id,
603
- label: variant.label,
604
- filename: variantFilename,
605
- };
606
-
607
- if (variantOptions.skip) {
608
- variantResult.skipped = true;
609
- variantResults.push(variantResult);
610
- continue;
611
- }
612
-
613
- const variantExtra = extras.variants?.[variant.id];
614
- const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
615
- const variantDiffFilename =
616
- variantExtra?.diffImageFilename ?? variantFilename;
617
-
618
- const variantCaptureResult = await this.captureSingleScreenshot(
619
- page,
620
- variantFilename,
621
- variantOptions,
622
- {
623
- saveDiffImage: variantSaveDiff,
624
- diffImageFilename: variantDiffFilename,
625
- },
626
- );
627
-
628
- variantResult.filepath = variantCaptureResult.filepath;
629
- variantResult.comparisonResult = variantCaptureResult.comparisonResult;
630
- variantResult.diffImagePath = variantCaptureResult.diffImagePath;
631
- variantResult.skipped = variantCaptureResult.skipped;
632
-
633
- variantResults.push(variantResult);
634
- }
635
-
636
- return {
637
- base: baseResult,
638
- variants: variantResults,
639
- };
640
- }
641
-
642
- /**
643
- * Applies SVG and UI optimizations for screenshots
644
- */
645
- private async applyScreenshotOptimizations(page: Page) {
646
- await page.addStyleTag({
647
- content: `
648
- *, *::before, *::after {
649
- -moz-animation: none !important;
650
- -moz-transition: none !important;
651
- transition: none !important;
652
- animation: none !important;
653
- }
654
- *, input, textarea { caret-color: transparent !important }
655
- *:focus { outline: none !important }
656
- *:focus-visible { outline: none !important }
657
- *:focus-within { outline: none !important }
658
- * { text-rendering: optimizeLegibility !important }
659
- ::-webkit-scrollbar { display: none !important }
660
- html { scroll-behavior: auto !important }
661
- svg, svg * {
662
- shape-rendering: crispEdges !important;
663
- text-rendering: geometricPrecision !important;
664
- vector-effect: non-scaling-stroke !important;
665
- }
666
- img { image-rendering: crisp-edges !important }
667
- `,
668
- });
669
- }
670
-
671
- /**
672
- * Captures screenshots for multiple variants, each with their own URL
673
- */
674
- async captureWithVariants(
675
- page: Page,
676
- baseFilename: string,
677
- baseUrl: string,
678
- baseOptions: ScreenshotSettings,
679
- variants: ScreenshotVariantWithUrl[],
680
- extras: ScreenshotCaptureExtras = {},
681
- ): Promise<ScreenshotCaptureResult> {
682
- if (!this.browser) {
683
- throw new Error("Browser not initialized");
684
- }
685
-
686
- const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };
687
- const variantResults: ScreenshotVariantCaptureDetails[] = [];
688
-
689
- const baseSaveDiff = extras.saveDiffImage ?? false;
690
- const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
691
-
692
- // Capture base screenshot
693
- getLogger().debug(`Going to base URL: ${baseUrl}`);
694
- await page.goto(baseUrl);
695
- await this.applyScreenshotOptimizations(page);
696
- const baseCaptureResult = await this.captureSingleScreenshot(
697
- page,
698
- baseFilename,
699
- baseOptions,
700
- {
701
- saveDiffImage: baseSaveDiff,
702
- diffImageFilename: baseDiffFilename,
703
- },
704
- );
705
-
706
- baseResult.filepath = baseCaptureResult.filepath;
707
- baseResult.comparisonResult = baseCaptureResult.comparisonResult;
708
- baseResult.diffImagePath = baseCaptureResult.diffImagePath;
709
- baseResult.skipped = baseCaptureResult.skipped;
710
-
711
- // Capture variant screenshots
712
- for (const variant of variants) {
713
- const variantFilename =
714
- variant.filename || this.getVariantFilename(baseFilename, variant);
715
- const variantOptions: ScreenshotSettings = {
716
- ...baseOptions,
717
- ...variant.options,
718
- };
719
-
720
- const variantResult: ScreenshotVariantCaptureDetails = {
721
- id: variant.id,
722
- label: variant.label,
723
- filename: variantFilename,
724
- };
725
-
726
- if (variantOptions.skip) {
727
- variantResult.skipped = true;
728
- variantResults.push(variantResult);
729
- continue;
730
- }
731
-
732
- // Navigate to variant URL and apply optimizations
733
- getLogger().debug(`Going to variant URL: ${variant.url}`);
734
- await page.goto(variant.url);
735
- await this.applyScreenshotOptimizations(page);
736
-
737
- const variantExtra = extras.variants?.[variant.id];
738
- const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
739
- const variantDiffFilename =
740
- variantExtra?.diffImageFilename ?? variantFilename;
741
-
742
- const variantCaptureResult = await this.captureSingleScreenshot(
743
- page,
744
- variantFilename,
745
- variantOptions,
746
- {
747
- saveDiffImage: variantSaveDiff,
748
- diffImageFilename: variantDiffFilename,
749
- },
750
- );
751
-
752
- variantResult.filepath = variantCaptureResult.filepath;
753
- variantResult.comparisonResult = variantCaptureResult.comparisonResult;
754
- variantResult.diffImagePath = variantCaptureResult.diffImagePath;
755
- variantResult.skipped = variantCaptureResult.skipped;
756
-
757
- variantResults.push(variantResult);
758
- }
759
-
760
- return {
761
- base: baseResult,
762
- variants: variantResults,
763
- };
764
- }
765
-
766
- /**
767
- * Gets the exponential backoff delay
768
- */
769
- getIncBackoffDelay(i: number, delay: number): number {
770
- return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
771
- }
772
-
773
- /**
774
- * Get a page from the pool by index
775
- */
776
- getPageFromPool(index: number): Page {
777
- if (index < 0) {
778
- throw new Error(`Page index ${index} must be non-negative`);
779
- }
780
-
781
- if (index >= this.pages.length) {
782
- throw new Error(
783
- `Page index ${index} exceeds pool size ${this.pages.length}`,
784
- );
785
- }
786
-
787
- if (!this.pages[index]) {
788
- throw new Error(`Page index ${index} is undefined`);
789
- }
790
-
791
- return this.pages[index];
792
- }
793
- }
794
-
795
- export default ScreenshotTool;