@a11y-pulse/browser-adaptor 0.10.0 → 0.11.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/adaptor.d.ts +6 -1
- package/dist/adaptors/playwright.d.ts +2 -2
- package/dist/adaptors/playwright.js +3 -3
- package/dist/adaptors/playwright.js.map +1 -1
- package/dist/adaptors/puppeteer.d.ts +2 -2
- package/dist/adaptors/puppeteer.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/adaptor.d.ts
CHANGED
|
@@ -11,6 +11,11 @@ export type KeyName = "Tab" | "Shift+Tab" | "Enter" | "Space" | "Escape" | "Arro
|
|
|
11
11
|
* An element handle in the page. This type is adaptor-specific and is opaque to the audit.
|
|
12
12
|
*/
|
|
13
13
|
export type ElementRef = unknown;
|
|
14
|
+
export type PageFunction = (...args: never[]) => unknown;
|
|
15
|
+
/** What the host passes for a page function's parameters: an `ElementRef` wherever it takes a node. */
|
|
16
|
+
export type EvaluateArgs<A extends unknown[]> = {
|
|
17
|
+
[K in keyof A]: A[K] extends Node | null | undefined ? ElementRef : A[K];
|
|
18
|
+
};
|
|
14
19
|
/**
|
|
15
20
|
* A framework-specific adaptor that provides the primitives needed by tab-loop audits. An adaptor
|
|
16
21
|
* wraps a single page in a web browser.
|
|
@@ -19,7 +24,7 @@ export interface BrowserAdaptor {
|
|
|
19
24
|
/**
|
|
20
25
|
* Run `fn` in the page context, passing in any serialisable `args`
|
|
21
26
|
*/
|
|
22
|
-
evaluate<
|
|
27
|
+
evaluate<F extends PageFunction>(fn: F, ...args: EvaluateArgs<Parameters<F>>): Promise<Awaited<ReturnType<F>>>;
|
|
23
28
|
/**
|
|
24
29
|
* Return an opaque handle to an element in the page
|
|
25
30
|
*/
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Page } from "playwright-core";
|
|
2
|
-
import type { BrowserAdaptor, ElementRef, KeyName, Rect } from "../adaptor";
|
|
2
|
+
import type { BrowserAdaptor, ElementRef, EvaluateArgs, KeyName, PageFunction, Rect } from "../adaptor";
|
|
3
3
|
export type PlaywrightAdaptorOptions = {
|
|
4
4
|
/**
|
|
5
5
|
* Device scale factor for evidence screenshots. Defaults to 2. On Chromium any value is honoured
|
|
@@ -41,7 +41,7 @@ export declare class PlaywrightAdaptor implements BrowserAdaptor {
|
|
|
41
41
|
constructor(page: Page, options?: PlaywrightAdaptorOptions);
|
|
42
42
|
startDismissingDialogs(): () => void;
|
|
43
43
|
takeDismissedDialogs(): number;
|
|
44
|
-
evaluate<
|
|
44
|
+
evaluate<F extends PageFunction>(fn: F, ...args: EvaluateArgs<Parameters<F>>): Promise<Awaited<ReturnType<F>>>;
|
|
45
45
|
/**
|
|
46
46
|
* The route for pages whose Content-Security-Policy forbids `new Function()`: Playwright itself
|
|
47
47
|
* turns the source into a function, through the protocol rather than in page script, and the
|
|
@@ -96,7 +96,7 @@ var PlaywrightAdaptor = class {
|
|
|
96
96
|
throw error;
|
|
97
97
|
}
|
|
98
98
|
try {
|
|
99
|
-
return await this.evaluateWithoutEval(fn, args);
|
|
99
|
+
return await this.evaluateWithoutEval(fn.toString(), args);
|
|
100
100
|
} catch (fallbackError) {
|
|
101
101
|
const fallbackMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
|
|
102
102
|
if (!EVAL_BLOCKED.test(fallbackMessage)) {
|
|
@@ -115,8 +115,8 @@ var PlaywrightAdaptor = class {
|
|
|
115
115
|
* function is then called by handle. It costs two more round trips than the packed call, so it
|
|
116
116
|
* is only taken once that one has been refused.
|
|
117
117
|
*/
|
|
118
|
-
async evaluateWithoutEval(
|
|
119
|
-
const handle = await this.page.evaluateHandle(`(${
|
|
118
|
+
async evaluateWithoutEval(source, args) {
|
|
119
|
+
const handle = await this.page.evaluateHandle(`(${source})`);
|
|
120
120
|
try {
|
|
121
121
|
return await handle.evaluate(
|
|
122
122
|
(pageFn, packed) => pageFn(...packed),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adaptors/playwright.ts"],"sourcesContent":["import type { CDPSession, Dialog, JSHandle, Page } from \"playwright-core\";\nimport type { BrowserAdaptor, ElementRef, KeyName, Rect } from \"../adaptor\";\nimport { nextPaintScript } from \"../paint\";\n\n// The CDP session for each page, shared by focus emulation and clipped screenshots. A fresh adaptor\n// is created per audit run, but a page often outlives one run, so without this each run would open\n// another session that is never detached. The session is kept attached for the page's lifetime:\n// Chrome clears focus emulation when the CDP client disconnects. Resolves to null on Firefox and\n// WebKit, where Playwright offers no CDP.\nconst cdpSessions = new WeakMap<Page, Promise<CDPSession | null>>();\n\n// Pages that have had focus emulation enabled at least once.\nconst focusEmulatedPages = new WeakSet<Page>();\n\n// Dialog dismissal per page, shared by every adaptor wrapping that page: how many dialogs were\n// dismissed and not yet reported, how many callers currently want dialogs dismissed, and the\n// listener doing it while any does.\ntype DialogState = {\n\tcount: number;\n\tholds: number;\n\tlistener: ((dialog: Dialog) => void) | null;\n};\n\nconst dialogStates = new WeakMap<Page, DialogState>();\n\nconst DEFAULT_SCREENSHOT_CLIP_SCALE = 2;\n\nconst EVAL_BLOCKED = /EvalError|unsafe-eval|Content Security Policy|Trusted ?Type|TrustedScript/i;\n\nfunction cdpSession(page: Page): Promise<CDPSession | null> {\n\tconst existing = cdpSessions.get(page);\n\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst session = page\n\t\t.context()\n\t\t.newCDPSession(page)\n\t\t.catch(() => null);\n\tcdpSessions.set(page, session);\n\n\treturn session;\n}\n\nfunction isChromium(page: Page): boolean {\n\ttry {\n\t\treturn page.context().browser()?.browserType().name() === \"chromium\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport type PlaywrightAdaptorOptions = {\n\t/**\n\t * Device scale factor for evidence screenshots. Defaults to 2. On Chromium any value is honoured\n\t * per capture. Elsewhere this must match the `deviceScaleFactor` the browser context was created\n\t * with, because Playwright's public screenshot API cannot rescale a single capture.\n\t */\n\tscreenshotClipScale?: number;\n\n\t/**\n\t * Let a Chromium clip capture content outside the current viewport. Defaults to false: to honour\n\t * it Chromium shrinks the emulated viewport to 1x1 and then resizes it for the clip before\n\t * restoring it, and the page observes each of those as a real resize (`resize` fires, media\n\t * queries flip to their narrowest breakpoint), which can collapse a responsive layout and blur\n\t * the focused element mid-capture. Only enable it for evidence of regions the caller cannot\n\t * scroll into view, where the page's state does not matter. Firefox and WebKit capture the full\n\t * page without resizing the viewport, so they ignore this.\n\t */\n\tcaptureBeyondViewport?: boolean;\n\n\t/**\n\t * Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count\n\t * them. Playwright dismisses dialogs by itself only while nothing listens for them, and then\n\t * nothing records that one appeared.\n\t *\n\t * - `true`, the default: only while something has asked for it through `startDismissingDialogs`,\n\t * which a tab session does for as long as it runs. Outside that the page's dialogs are the\n\t * caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog\n\t * as it is raised still gets to.\n\t * - `\"always\"`: from construction, for the page's lifetime. For a caller that hands the whole\n\t * page over, such as the audit runner.\n\t * - `false`: never. The caller handles `dialog` events itself.\n\t */\n\tdismissDialogs?: boolean | \"always\";\n};\n\n/**\n * Dismiss the dialogs `page` raises, counting them, until the returned function is called. The\n * listener is on the page only while at least one caller holds it, so a caller's own `dialog`\n * handler has the page to itself the rest of the time.\n */\nfunction dismissDialogsOn(page: Page): () => void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn () => {};\n\t}\n\n\tlet state = dialogStates.get(page);\n\n\tif (state === undefined) {\n\t\tstate = { count: 0, holds: 0, listener: null };\n\t\tdialogStates.set(page, state);\n\t}\n\n\tconst held = state;\n\n\tif (held.holds++ === 0) {\n\t\tconst listener = (dialog: Dialog): void => {\n\t\t\theld.count++;\n\n\t\t\t// Not answered until every other listener has had the dialog: one of the caller's own that\n\t\t\t// answers it as it is raised then gets to, instead of finding it already handled. The\n\t\t\t// dismissal rejects when that happened, which is as good as dismissed.\n\t\t\tsetTimeout(() => {\n\t\t\t\tdialog.dismiss().catch(() => {});\n\t\t\t}, 0);\n\t\t};\n\n\t\theld.listener = listener;\n\t\tpage.on(\"dialog\", listener);\n\t}\n\n\tlet released = false;\n\n\treturn () => {\n\t\tif (released) {\n\t\t\treturn;\n\t\t}\n\n\t\treleased = true;\n\n\t\tif (--held.holds === 0 && held.listener !== null) {\n\t\t\tpage.off(\"dialog\", held.listener);\n\t\t\theld.listener = null;\n\t\t}\n\t};\n}\n\n/** A BrowserAdaptor backed by a Playwright Page. */\nexport class PlaywrightAdaptor implements BrowserAdaptor {\n\treadonly screenshotClipScale: number;\n\n\tprivate readonly captureBeyondViewport: boolean;\n\n\tprivate readonly dismissDialogs: boolean | \"always\";\n\n\tconstructor(\n\t\tprivate readonly page: Page,\n\t\toptions: PlaywrightAdaptorOptions = {},\n\t) {\n\t\tthis.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;\n\t\tthis.captureBeyondViewport = options.captureBeyondViewport ?? false;\n\t\tthis.dismissDialogs = options.dismissDialogs ?? true;\n\n\t\tif (this.dismissDialogs === \"always\") {\n\t\t\tdismissDialogsOn(page);\n\t\t}\n\t}\n\n\tstartDismissingDialogs(): () => void {\n\t\treturn this.dismissDialogs === false ? () => {} : dismissDialogsOn(this.page);\n\t}\n\n\ttakeDismissedDialogs(): number {\n\t\tconst state = dialogStates.get(this.page);\n\t\tconst count = state?.count ?? 0;\n\n\t\tif (state) {\n\t\t\tstate.count = 0;\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tasync evaluate<T>(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: the page-evaluated fn accepts arbitrary serialised args and element handles.\n\t\tfn: (...args: any[]) => T | Promise<T>,\n\t\t...args: unknown[]\n\t): Promise<T> {\n\t\ttry {\n\t\t\t// Playwright takes a single argument, so the function source and its args travel packed\n\t\t\t// into one tuple. Handles nested in that tuple are still resolved to live elements.\n\t\t\treturn (await this.page.evaluate(\n\t\t\t\t([source, packed]) => new Function(`return (${source})`)()(...(packed as unknown[])),\n\t\t\t\t[fn.toString(), args] as [string, unknown[]],\n\t\t\t)) as T;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\n\t\t\tif (!EVAL_BLOCKED.test(message)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn await this.evaluateWithoutEval<T>(fn, args);\n\t\t\t} catch (fallbackError) {\n\t\t\t\tconst fallbackMessage =\n\t\t\t\t\tfallbackError instanceof Error ? fallbackError.message : String(fallbackError);\n\n\t\t\t\tif (!EVAL_BLOCKED.test(fallbackMessage)) {\n\t\t\t\t\tthrow fallbackError;\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This page's Content-Security-Policy blocks the Playwright adaptor from building page functions. Allow 'unsafe-eval' in script-src, or use the Puppeteer adaptor.\",\n\t\t\t\t\t{ cause: fallbackError },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The route for pages whose Content-Security-Policy forbids `new Function()`: Playwright itself\n\t * turns the source into a function, through the protocol rather than in page script, and the\n\t * function is then called by handle. It costs two more round trips than the packed call, so it\n\t * is only taken once that one has been refused.\n\t */\n\tprivate async evaluateWithoutEval<T>(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: the page-evaluated fn accepts arbitrary serialised args and element handles.\n\t\tfn: (...args: any[]) => T | Promise<T>,\n\t\targs: unknown[],\n\t): Promise<T> {\n\t\tconst handle = await this.page.evaluateHandle(`(${fn.toString()})`);\n\n\t\ttry {\n\t\t\treturn (await handle.evaluate(\n\t\t\t\t(pageFn, packed) => (pageFn as (...values: unknown[]) => unknown)(...(packed as unknown[])),\n\t\t\t\targs,\n\t\t\t)) as T;\n\t\t} finally {\n\t\t\tawait handle.dispose().catch(() => {});\n\t\t}\n\t}\n\n\tevaluateHandle(fn: () => Element | null): Promise<ElementRef> {\n\t\treturn this.page.evaluateHandle(fn);\n\t}\n\n\tasync disposeRef(ref: ElementRef): Promise<void> {\n\t\tawait (ref as JSHandle).dispose();\n\t}\n\n\tasync pressTab(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Tab\");\n\t}\n\n\tasync pressEnter(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Enter\");\n\t}\n\n\tasync pressKey(key: KeyName): Promise<void> {\n\t\tawait this.page.keyboard.press(key);\n\t}\n\n\tasync screenshotClip(clip: Rect, scale = 1): Promise<Uint8Array> {\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (session) {\n\t\t\t// No wait for a paint first: Chromium renders a frame of the page as it stands for every\n\t\t\t// capture it is asked for through CDP.\n\t\t\t//\n\t\t\t// The public API cannot scale one capture, and its `clip` is only honoured inside the\n\t\t\t// viewport. CDP is what Puppeteer drives too, so evidence images stay pixel-comparable.\n\t\t\t//\n\t\t\t// `captureBeyondViewport: false` ensures that Chromium does not resize the viewport before\n\t\t\t// capturing the screenshot, which can trigger media queries and hide the element we are\n\t\t\t// trying to capture.\n\t\t\tconst { data } = await session.send(\"Page.captureScreenshot\", {\n\t\t\t\tformat: \"png\",\n\t\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\t\tclip: { ...clip, scale },\n\t\t\t});\n\n\t\t\treturn Buffer.from(data, \"base64\");\n\t\t}\n\n\t\tawait this.page.evaluate(nextPaintScript);\n\n\t\t// Clips are document coordinates, and Playwright renders anything outside the viewport blank\n\t\t// unless the capture is full-page. Firefox and WebKit capture a full page without resizing\n\t\t// the viewport, so the page does not observe this.\n\t\treturn (await this.page.screenshot({\n\t\t\ttype: \"png\",\n\t\t\tfullPage: true,\n\t\t\tclip,\n\t\t\tscale: \"device\",\n\t\t})) as Uint8Array;\n\t}\n\n\tasync ensureFocusReporting(): Promise<void> {\n\t\t// Pages only report focus while they are the foreground tab. Since this browser instance is\n\t\t// likely running in the background, we need to enable focus emulation to get accurate results.\n\t\t//\n\t\t// Note this function does not throw if enabling emulation fails; it is a best-effort.\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (!session) {\n\t\t\t// Playwright emulates focus on Firefox and WebKit itself, so there is nothing to assert\n\t\t\t// and nothing worth warning about.\n\t\t\tif (isChromium(this.page)) {\n\t\t\t\tconsole.warn(\"Could not open a CDP session for the browser adaptor\");\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif (focusEmulatedPages.has(this.page)) {\n\t\t\t\t// Chromium ignores a redundant enable, so re-asserting has to toggle.\n\t\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\t\tenabled: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\tenabled: true,\n\t\t\t});\n\t\t\tfocusEmulatedPages.add(this.page);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Could not enable focus emulation for the browser adaptor\", {\n\t\t\t\terror,\n\t\t\t});\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AASA,IAAM,cAAc,oBAAI,QAA0C;AAGlE,IAAM,qBAAqB,oBAAI,QAAc;AAW7C,IAAM,eAAe,oBAAI,QAA2B;AAEpD,IAAM,gCAAgC;AAEtC,IAAM,eAAe;AAErB,SAAS,WAAW,MAAwC;AAC3D,QAAM,WAAW,YAAY,IAAI,IAAI;AAErC,MAAI,UAAU;AACb,WAAO;AAAA,EACR;AAEA,QAAM,UAAU,KACd,QAAQ,EACR,cAAc,IAAI,EAClB,MAAM,MAAM,IAAI;AAClB,cAAY,IAAI,MAAM,OAAO;AAE7B,SAAO;AACR;AAEA,SAAS,WAAW,MAAqB;AACxC,MAAI;AACH,WAAO,KAAK,QAAQ,EAAE,QAAQ,GAAG,YAAY,EAAE,KAAK,MAAM;AAAA,EAC3D,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AA0CA,SAAS,iBAAiB,MAAwB;AACjD,MAAI,OAAO,KAAK,OAAO,YAAY;AAClC,WAAO,MA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AAAA,EACD;AACD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adaptors/playwright.ts"],"sourcesContent":["import type { CDPSession, Dialog, JSHandle, Page } from \"playwright-core\";\nimport type {\n\tBrowserAdaptor,\n\tElementRef,\n\tEvaluateArgs,\n\tKeyName,\n\tPageFunction,\n\tRect,\n} from \"../adaptor\";\nimport { nextPaintScript } from \"../paint\";\n\n// The CDP session for each page, shared by focus emulation and clipped screenshots. A fresh adaptor\n// is created per audit run, but a page often outlives one run, so without this each run would open\n// another session that is never detached. The session is kept attached for the page's lifetime:\n// Chrome clears focus emulation when the CDP client disconnects. Resolves to null on Firefox and\n// WebKit, where Playwright offers no CDP.\nconst cdpSessions = new WeakMap<Page, Promise<CDPSession | null>>();\n\n// Pages that have had focus emulation enabled at least once.\nconst focusEmulatedPages = new WeakSet<Page>();\n\n// Dialog dismissal per page, shared by every adaptor wrapping that page: how many dialogs were\n// dismissed and not yet reported, how many callers currently want dialogs dismissed, and the\n// listener doing it while any does.\ntype DialogState = {\n\tcount: number;\n\tholds: number;\n\tlistener: ((dialog: Dialog) => void) | null;\n};\n\nconst dialogStates = new WeakMap<Page, DialogState>();\n\nconst DEFAULT_SCREENSHOT_CLIP_SCALE = 2;\n\nconst EVAL_BLOCKED = /EvalError|unsafe-eval|Content Security Policy|Trusted ?Type|TrustedScript/i;\n\nfunction cdpSession(page: Page): Promise<CDPSession | null> {\n\tconst existing = cdpSessions.get(page);\n\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst session = page\n\t\t.context()\n\t\t.newCDPSession(page)\n\t\t.catch(() => null);\n\tcdpSessions.set(page, session);\n\n\treturn session;\n}\n\nfunction isChromium(page: Page): boolean {\n\ttry {\n\t\treturn page.context().browser()?.browserType().name() === \"chromium\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport type PlaywrightAdaptorOptions = {\n\t/**\n\t * Device scale factor for evidence screenshots. Defaults to 2. On Chromium any value is honoured\n\t * per capture. Elsewhere this must match the `deviceScaleFactor` the browser context was created\n\t * with, because Playwright's public screenshot API cannot rescale a single capture.\n\t */\n\tscreenshotClipScale?: number;\n\n\t/**\n\t * Let a Chromium clip capture content outside the current viewport. Defaults to false: to honour\n\t * it Chromium shrinks the emulated viewport to 1x1 and then resizes it for the clip before\n\t * restoring it, and the page observes each of those as a real resize (`resize` fires, media\n\t * queries flip to their narrowest breakpoint), which can collapse a responsive layout and blur\n\t * the focused element mid-capture. Only enable it for evidence of regions the caller cannot\n\t * scroll into view, where the page's state does not matter. Firefox and WebKit capture the full\n\t * page without resizing the viewport, so they ignore this.\n\t */\n\tcaptureBeyondViewport?: boolean;\n\n\t/**\n\t * Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count\n\t * them. Playwright dismisses dialogs by itself only while nothing listens for them, and then\n\t * nothing records that one appeared.\n\t *\n\t * - `true`, the default: only while something has asked for it through `startDismissingDialogs`,\n\t * which a tab session does for as long as it runs. Outside that the page's dialogs are the\n\t * caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog\n\t * as it is raised still gets to.\n\t * - `\"always\"`: from construction, for the page's lifetime. For a caller that hands the whole\n\t * page over, such as the audit runner.\n\t * - `false`: never. The caller handles `dialog` events itself.\n\t */\n\tdismissDialogs?: boolean | \"always\";\n};\n\n/**\n * Dismiss the dialogs `page` raises, counting them, until the returned function is called. The\n * listener is on the page only while at least one caller holds it, so a caller's own `dialog`\n * handler has the page to itself the rest of the time.\n */\nfunction dismissDialogsOn(page: Page): () => void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn () => {};\n\t}\n\n\tlet state = dialogStates.get(page);\n\n\tif (state === undefined) {\n\t\tstate = { count: 0, holds: 0, listener: null };\n\t\tdialogStates.set(page, state);\n\t}\n\n\tconst held = state;\n\n\tif (held.holds++ === 0) {\n\t\tconst listener = (dialog: Dialog): void => {\n\t\t\theld.count++;\n\n\t\t\t// Not answered until every other listener has had the dialog: one of the caller's own that\n\t\t\t// answers it as it is raised then gets to, instead of finding it already handled. The\n\t\t\t// dismissal rejects when that happened, which is as good as dismissed.\n\t\t\tsetTimeout(() => {\n\t\t\t\tdialog.dismiss().catch(() => {});\n\t\t\t}, 0);\n\t\t};\n\n\t\theld.listener = listener;\n\t\tpage.on(\"dialog\", listener);\n\t}\n\n\tlet released = false;\n\n\treturn () => {\n\t\tif (released) {\n\t\t\treturn;\n\t\t}\n\n\t\treleased = true;\n\n\t\tif (--held.holds === 0 && held.listener !== null) {\n\t\t\tpage.off(\"dialog\", held.listener);\n\t\t\theld.listener = null;\n\t\t}\n\t};\n}\n\n/** A BrowserAdaptor backed by a Playwright Page. */\nexport class PlaywrightAdaptor implements BrowserAdaptor {\n\treadonly screenshotClipScale: number;\n\n\tprivate readonly captureBeyondViewport: boolean;\n\n\tprivate readonly dismissDialogs: boolean | \"always\";\n\n\tconstructor(\n\t\tprivate readonly page: Page,\n\t\toptions: PlaywrightAdaptorOptions = {},\n\t) {\n\t\tthis.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;\n\t\tthis.captureBeyondViewport = options.captureBeyondViewport ?? false;\n\t\tthis.dismissDialogs = options.dismissDialogs ?? true;\n\n\t\tif (this.dismissDialogs === \"always\") {\n\t\t\tdismissDialogsOn(page);\n\t\t}\n\t}\n\n\tstartDismissingDialogs(): () => void {\n\t\treturn this.dismissDialogs === false ? () => {} : dismissDialogsOn(this.page);\n\t}\n\n\ttakeDismissedDialogs(): number {\n\t\tconst state = dialogStates.get(this.page);\n\t\tconst count = state?.count ?? 0;\n\n\t\tif (state) {\n\t\t\tstate.count = 0;\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tasync evaluate<F extends PageFunction>(\n\t\tfn: F,\n\t\t...args: EvaluateArgs<Parameters<F>>\n\t): Promise<Awaited<ReturnType<F>>> {\n\t\ttry {\n\t\t\t// Playwright takes a single argument, so the function source and its args travel packed\n\t\t\t// into one tuple. Handles nested in that tuple are still resolved to live elements.\n\t\t\treturn (await this.page.evaluate(\n\t\t\t\t([source, packed]) => new Function(`return (${source})`)()(...(packed as unknown[])),\n\t\t\t\t[fn.toString(), args] as [string, unknown[]],\n\t\t\t)) as Awaited<ReturnType<F>>;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\n\t\t\tif (!EVAL_BLOCKED.test(message)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn (await this.evaluateWithoutEval(fn.toString(), args)) as Awaited<ReturnType<F>>;\n\t\t\t} catch (fallbackError) {\n\t\t\t\tconst fallbackMessage =\n\t\t\t\t\tfallbackError instanceof Error ? fallbackError.message : String(fallbackError);\n\n\t\t\t\tif (!EVAL_BLOCKED.test(fallbackMessage)) {\n\t\t\t\t\tthrow fallbackError;\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This page's Content-Security-Policy blocks the Playwright adaptor from building page functions. Allow 'unsafe-eval' in script-src, or use the Puppeteer adaptor.\",\n\t\t\t\t\t{ cause: fallbackError },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The route for pages whose Content-Security-Policy forbids `new Function()`: Playwright itself\n\t * turns the source into a function, through the protocol rather than in page script, and the\n\t * function is then called by handle. It costs two more round trips than the packed call, so it\n\t * is only taken once that one has been refused.\n\t */\n\tprivate async evaluateWithoutEval(source: string, args: unknown[]): Promise<unknown> {\n\t\tconst handle = await this.page.evaluateHandle(`(${source})`);\n\n\t\ttry {\n\t\t\treturn await handle.evaluate(\n\t\t\t\t(pageFn, packed) => (pageFn as (...values: unknown[]) => unknown)(...(packed as unknown[])),\n\t\t\t\targs,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait handle.dispose().catch(() => {});\n\t\t}\n\t}\n\n\tevaluateHandle(fn: () => Element | null): Promise<ElementRef> {\n\t\treturn this.page.evaluateHandle(fn);\n\t}\n\n\tasync disposeRef(ref: ElementRef): Promise<void> {\n\t\tawait (ref as JSHandle).dispose();\n\t}\n\n\tasync pressTab(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Tab\");\n\t}\n\n\tasync pressEnter(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Enter\");\n\t}\n\n\tasync pressKey(key: KeyName): Promise<void> {\n\t\tawait this.page.keyboard.press(key);\n\t}\n\n\tasync screenshotClip(clip: Rect, scale = 1): Promise<Uint8Array> {\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (session) {\n\t\t\t// No wait for a paint first: Chromium renders a frame of the page as it stands for every\n\t\t\t// capture it is asked for through CDP.\n\t\t\t//\n\t\t\t// The public API cannot scale one capture, and its `clip` is only honoured inside the\n\t\t\t// viewport. CDP is what Puppeteer drives too, so evidence images stay pixel-comparable.\n\t\t\t//\n\t\t\t// `captureBeyondViewport: false` ensures that Chromium does not resize the viewport before\n\t\t\t// capturing the screenshot, which can trigger media queries and hide the element we are\n\t\t\t// trying to capture.\n\t\t\tconst { data } = await session.send(\"Page.captureScreenshot\", {\n\t\t\t\tformat: \"png\",\n\t\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\t\tclip: { ...clip, scale },\n\t\t\t});\n\n\t\t\treturn Buffer.from(data, \"base64\");\n\t\t}\n\n\t\tawait this.page.evaluate(nextPaintScript);\n\n\t\t// Clips are document coordinates, and Playwright renders anything outside the viewport blank\n\t\t// unless the capture is full-page. Firefox and WebKit capture a full page without resizing\n\t\t// the viewport, so the page does not observe this.\n\t\treturn (await this.page.screenshot({\n\t\t\ttype: \"png\",\n\t\t\tfullPage: true,\n\t\t\tclip,\n\t\t\tscale: \"device\",\n\t\t})) as Uint8Array;\n\t}\n\n\tasync ensureFocusReporting(): Promise<void> {\n\t\t// Pages only report focus while they are the foreground tab. Since this browser instance is\n\t\t// likely running in the background, we need to enable focus emulation to get accurate results.\n\t\t//\n\t\t// Note this function does not throw if enabling emulation fails; it is a best-effort.\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (!session) {\n\t\t\t// Playwright emulates focus on Firefox and WebKit itself, so there is nothing to assert\n\t\t\t// and nothing worth warning about.\n\t\t\tif (isChromium(this.page)) {\n\t\t\t\tconsole.warn(\"Could not open a CDP session for the browser adaptor\");\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif (focusEmulatedPages.has(this.page)) {\n\t\t\t\t// Chromium ignores a redundant enable, so re-asserting has to toggle.\n\t\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\t\tenabled: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\tenabled: true,\n\t\t\t});\n\t\t\tfocusEmulatedPages.add(this.page);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Could not enable focus emulation for the browser adaptor\", {\n\t\t\t\terror,\n\t\t\t});\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAgBA,IAAM,cAAc,oBAAI,QAA0C;AAGlE,IAAM,qBAAqB,oBAAI,QAAc;AAW7C,IAAM,eAAe,oBAAI,QAA2B;AAEpD,IAAM,gCAAgC;AAEtC,IAAM,eAAe;AAErB,SAAS,WAAW,MAAwC;AAC3D,QAAM,WAAW,YAAY,IAAI,IAAI;AAErC,MAAI,UAAU;AACb,WAAO;AAAA,EACR;AAEA,QAAM,UAAU,KACd,QAAQ,EACR,cAAc,IAAI,EAClB,MAAM,MAAM,IAAI;AAClB,cAAY,IAAI,MAAM,OAAO;AAE7B,SAAO;AACR;AAEA,SAAS,WAAW,MAAqB;AACxC,MAAI;AACH,WAAO,KAAK,QAAQ,EAAE,QAAQ,GAAG,YAAY,EAAE,KAAK,MAAM;AAAA,EAC3D,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AA0CA,SAAS,iBAAiB,MAAwB;AACjD,MAAI,OAAO,KAAK,OAAO,YAAY;AAClC,WAAO,MAAM;AAAA,IAAC;AAAA,EACf;AAEA,MAAI,QAAQ,aAAa,IAA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 @@
|
|
|
1
1
|
import type { Page } from "puppeteer";
|
|
2
|
-
import type { BrowserAdaptor, ElementRef, KeyName, Rect } from "../adaptor";
|
|
2
|
+
import type { BrowserAdaptor, ElementRef, EvaluateArgs, KeyName, PageFunction, Rect } from "../adaptor";
|
|
3
3
|
export type PuppeteerAdaptorOptions = {
|
|
4
4
|
/** Device scale factor for evidence screenshots. Defaults to 2, applied per capture. */
|
|
5
5
|
screenshotClipScale?: number;
|
|
@@ -42,7 +42,7 @@ export declare class PuppeteerAdaptor implements BrowserAdaptor {
|
|
|
42
42
|
constructor(page: Page, options?: PuppeteerAdaptorOptions);
|
|
43
43
|
startDismissingDialogs(): () => void;
|
|
44
44
|
takeDismissedDialogs(): number;
|
|
45
|
-
evaluate<
|
|
45
|
+
evaluate<F extends PageFunction>(fn: F, ...args: EvaluateArgs<Parameters<F>>): Promise<Awaited<ReturnType<F>>>;
|
|
46
46
|
evaluateHandle(fn: () => Element | null): Promise<ElementRef>;
|
|
47
47
|
disposeRef(ref: ElementRef): Promise<void>;
|
|
48
48
|
pressTab(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adaptors/puppeteer.ts"],"sourcesContent":["import type { CDPSession, Dialog, JSHandle, KeyInput, Page } from \"puppeteer\";\nimport type { BrowserAdaptor, ElementRef, KeyName, Rect } from \"../adaptor\";\nimport { nextPaintScript } from \"../paint\";\n\n// Keep track of the CDP session for each page so that we can reuse it. The session is kept\n// attached for the page's lifetime: Chrome clears focus emulation when the CDP client disconnects.\n// Resolves to null when a session cannot be opened, so the failure is not retried on every call.\nconst cdpSessions = new WeakMap<Page, Promise<CDPSession | null>>();\n\n// Pages that have had focus emulation enabled at least once.\nconst focusEmulatedPages = new WeakSet<Page>();\n\n// Dialog dismissal per page, shared by every adaptor wrapping that page: how many dialogs were\n// dismissed and not yet reported, how many callers currently want dialogs dismissed, the listener\n// doing it while any does, and the last dialog the page raised, which may still be open.\ntype DialogState = {\n\tcount: number;\n\tholds: number;\n\tlistener: ((dialog: Dialog) => void) | null;\n\twatching: boolean;\n\tlast: Dialog | null;\n};\n\nfunction dialogStateOf(page: Page): DialogState {\n\tlet state = dialogStates.get(page);\n\n\tif (state === undefined) {\n\t\tstate = { count: 0, holds: 0, listener: null, watching: false, last: null };\n\t\tdialogStates.set(page, state);\n\t}\n\n\treturn state;\n}\n\n/**\n * Remember the last dialog `page` raised, without answering it. Puppeteer leaves a dialog nobody\n * answers open, and an open dialog blocks every call to the page, so whoever starts dismissing\n * dialogs later has to be able to close one that was raised before they started. Watching answers\n * nothing, so the caller's own `dialog` handler is unaffected.\n */\nfunction watchDialogsOn(page: Page): void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn;\n\t}\n\n\tconst state = dialogStateOf(page);\n\n\tif (state.watching) {\n\t\treturn;\n\t}\n\n\tstate.watching = true;\n\tpage.on(\"dialog\", (dialog: Dialog) => {\n\t\tstate.last = dialog;\n\t});\n}\n\nconst dialogStates = new WeakMap<Page, DialogState>();\n\nconst DEFAULT_SCREENSHOT_CLIP_SCALE = 2;\n\nfunction cdpSession(page: Page): Promise<CDPSession | null> {\n\tconst existing = cdpSessions.get(page);\n\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst session = page.createCDPSession().catch(() => null);\n\tcdpSessions.set(page, session);\n\n\treturn session;\n}\n\nexport type PuppeteerAdaptorOptions = {\n\t/** Device scale factor for evidence screenshots. Defaults to 2, applied per capture. */\n\tscreenshotClipScale?: number;\n\n\t/**\n\t * Trade PNG compression for capture speed. Defaults to true, which roughly doubles the encoded\n\t * size of each capture without changing a single pixel.\n\t */\n\toptimizeForSpeed?: boolean;\n\n\t/**\n\t * Let a clip capture content outside the current viewport. Defaults to false: to honour it\n\t * Chromium shrinks the emulated viewport to 1x1 and then resizes it for the clip before\n\t * restoring it, and the page observes each of those as a real resize (`resize` fires, media\n\t * queries flip to their narrowest breakpoint), which can collapse a responsive layout and blur\n\t * the focused element mid-capture. Only enable it for evidence of regions the caller cannot\n\t * scroll into view, where the page's state does not matter.\n\t */\n\tcaptureBeyondViewport?: boolean;\n\n\t/**\n\t * Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count\n\t * them. A dialog blocks the page until something answers it, so an unanswered one hangs every\n\t * later call.\n\t *\n\t * - `true`, the default: only while something has asked for it through `startDismissingDialogs`,\n\t * which a tab session does for as long as it runs. Outside that the page's dialogs are the\n\t * caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog\n\t * as it is raised still gets to.\n\t * - `\"always\"`: from construction, for the page's lifetime. For a caller that hands the whole\n\t * page over, such as the audit runner.\n\t * - `false`: never. The caller handles `dialog` events itself.\n\t */\n\tdismissDialogs?: boolean | \"always\";\n};\n\n/**\n * Dismiss the dialogs `page` raises, counting them, until the returned function is called. The\n * listener is on the page only while at least one caller holds it, so a caller's own `dialog`\n * handler has the page to itself the rest of the time.\n */\nfunction dismissDialogsOn(page: Page): () => void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn () => {};\n\t}\n\n\tconst held = dialogStateOf(page);\n\n\tif (held.holds++ === 0) {\n\t\t// A dialog raised before anyone was dismissing them may still be open, blocking the page.\n\t\t// Dismissing one that was answered since rejects, which is fine. It is not counted: it\n\t\t// predates whatever is starting now.\n\t\tconst earlier = held.last;\n\t\theld.last = null;\n\n\t\tif (earlier !== null) {\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => earlier.dismiss())\n\t\t\t\t.catch(() => {});\n\t\t}\n\n\t\tconst listener = (dialog: Dialog): void => {\n\t\t\theld.count++;\n\n\t\t\t// Not answered until every other listener has had the dialog: one of the caller's own that\n\t\t\t// answers it as it is raised then gets to, instead of finding it already handled. The\n\t\t\t// dismissal rejects when that happened, which is as good as dismissed.\n\t\t\tsetTimeout(() => {\n\t\t\t\tdialog.dismiss().catch(() => {});\n\t\t\t}, 0);\n\t\t};\n\n\t\theld.listener = listener;\n\t\tpage.on(\"dialog\", listener);\n\t}\n\n\tlet released = false;\n\n\treturn () => {\n\t\tif (released) {\n\t\t\treturn;\n\t\t}\n\n\t\treleased = true;\n\n\t\tif (--held.holds === 0 && held.listener !== null) {\n\t\t\tpage.off(\"dialog\", held.listener);\n\t\t\theld.listener = null;\n\t\t}\n\t};\n}\n\n/** A BrowserAdaptor backed by a Puppeteer Page. */\nexport class PuppeteerAdaptor implements BrowserAdaptor {\n\treadonly screenshotClipScale: number;\n\n\tprivate readonly optimizeForSpeed: boolean;\n\n\tprivate readonly captureBeyondViewport: boolean;\n\n\tprivate readonly dismissDialogs: boolean | \"always\";\n\n\tconstructor(\n\t\tprivate readonly page: Page,\n\t\toptions: PuppeteerAdaptorOptions = {},\n\t) {\n\t\tthis.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;\n\t\tthis.optimizeForSpeed = options.optimizeForSpeed ?? true;\n\t\tthis.captureBeyondViewport = options.captureBeyondViewport ?? false;\n\t\tthis.dismissDialogs = options.dismissDialogs ?? true;\n\n\t\tif (this.dismissDialogs === \"always\") {\n\t\t\tdismissDialogsOn(page);\n\t\t} else if (this.dismissDialogs) {\n\t\t\twatchDialogsOn(page);\n\t\t}\n\t}\n\n\tstartDismissingDialogs(): () => void {\n\t\treturn this.dismissDialogs === false ? () => {} : dismissDialogsOn(this.page);\n\t}\n\n\ttakeDismissedDialogs(): number {\n\t\tconst state = dialogStates.get(this.page);\n\t\tconst count = state?.count ?? 0;\n\n\t\tif (state) {\n\t\t\tstate.count = 0;\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tevaluate<T>(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: the page-evaluated fn accepts arbitrary serialised args and element handles.\n\t\tfn: (...args: any[]) => T | Promise<T>,\n\t\t...args: unknown[]\n\t): Promise<T> {\n\t\t// Puppeteer resolves any JSHandle passed as an arg to the live element.\n\t\treturn this.page.evaluate(fn as never, ...(args as never[])) as Promise<T>;\n\t}\n\n\tevaluateHandle(fn: () => Element | null): Promise<ElementRef> {\n\t\treturn this.page.evaluateHandle(fn);\n\t}\n\n\tasync disposeRef(ref: ElementRef): Promise<void> {\n\t\tawait (ref as JSHandle).dispose();\n\t}\n\n\tasync pressTab(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Tab\");\n\t}\n\n\tasync pressEnter(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Enter\");\n\t}\n\n\tasync pressKey(key: KeyName): Promise<void> {\n\t\tconst { keyboard } = this.page;\n\t\t// Puppeteer has no syntax for a combination, so modifiers are held down by hand.\n\t\tconst modifiers = key.split(\"+\") as KeyInput[];\n\t\tconst name = modifiers.pop()!;\n\n\t\tfor (const modifier of modifiers) {\n\t\t\tawait keyboard.down(modifier);\n\t\t}\n\n\t\ttry {\n\t\t\tawait keyboard.press(name);\n\t\t} finally {\n\t\t\tfor (const modifier of modifiers) {\n\t\t\t\tawait keyboard.up(modifier);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync screenshotClip(clip: Rect, scale = 1): Promise<Uint8Array> {\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (!session) {\n\t\t\tawait this.page.evaluate(nextPaintScript);\n\n\t\t\t// Without CDP the public API is all there is. With captureBeyondViewport off it intersects\n\t\t\t// the clip with the viewport, so a clip that does not fit comes back smaller than asked\n\t\t\t// for, with a shifted origin.\n\t\t\treturn (await this.page.screenshot({\n\t\t\t\ttype: \"png\",\n\t\t\t\toptimizeForSpeed: this.optimizeForSpeed,\n\t\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\t\tclip: { ...clip, scale },\n\t\t\t})) as Uint8Array;\n\t\t}\n\n\t\t// No wait for a paint first: Chromium renders a frame of the page as it stands for every\n\t\t// capture it is asked for through CDP.\n\t\t//\n\t\t// Straight to CDP rather than page.screenshot(): with captureBeyondViewport off, Puppeteer\n\t\t// intersects the clip with the visual viewport and silently moves the origin that callers\n\t\t// align element rects against. Keeping captureBeyondViewport off ensures that Chromium does\n\t\t// not resize the viewport, which can trigger media queries and hide the element we are\n\t\t// trying to capture.\n\t\tconst { data } = await session.send(\"Page.captureScreenshot\", {\n\t\t\tformat: \"png\",\n\t\t\toptimizeForSpeed: this.optimizeForSpeed,\n\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\tclip: { ...clip, scale },\n\t\t});\n\n\t\treturn Buffer.from(data, \"base64\");\n\t}\n\n\tasync ensureFocusReporting(): Promise<void> {\n\t\t// Pages only report focus while they are the foreground tab. Since this browser instance is\n\t\t// likely running in the background, we need to enable focus emulation to get accurate results.\n\t\t//\n\t\t// Note this function does not throw if enabling emulation fails; it is a best-effort.\n\t\ttry {\n\t\t\tconst session = await cdpSession(this.page);\n\n\t\t\tif (!session) {\n\t\t\t\tthrow new Error(\"Could not open a CDP session\");\n\t\t\t}\n\n\t\t\tif (focusEmulatedPages.has(this.page)) {\n\t\t\t\t// Chromium ignores a redundant enable, so re-asserting has to toggle.\n\t\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\t\tenabled: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\tenabled: true,\n\t\t\t});\n\t\t\tfocusEmulatedPages.add(this.page);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Could not enable focus emulation for the browser adaptor\", {\n\t\t\t\terror,\n\t\t\t});\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAOA,IAAM,cAAc,oBAAI,QAA0C;AAGlE,IAAM,qBAAqB,oBAAI,QAAc;AAa7C,SAAS,cAAc,MAAyB;AAC/C,MAAI,QAAQ,aAAa,IAAI,IAAI;AAEjC,MAAI,UAAU,QAAW;AACxB,YAAQ,EAAE,OAAO,GAAG,OAAO,GAAG,UAAU,MAAM,UAAU,OAAO,MAAM,KAAK;AAC1E,iBAAa,IAAI,MAAM,KAAK;AAAA,EAC7B;AAEA,SAAO;AACR;AAQA,SAAS,eAAe,MAAkB;AACzC,MAAI,OAAO,KAAK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AA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AACD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adaptors/puppeteer.ts"],"sourcesContent":["import type { CDPSession, Dialog, JSHandle, KeyInput, Page } from \"puppeteer\";\nimport type {\n\tBrowserAdaptor,\n\tElementRef,\n\tEvaluateArgs,\n\tKeyName,\n\tPageFunction,\n\tRect,\n} from \"../adaptor\";\nimport { nextPaintScript } from \"../paint\";\n\n// Keep track of the CDP session for each page so that we can reuse it. The session is kept\n// attached for the page's lifetime: Chrome clears focus emulation when the CDP client disconnects.\n// Resolves to null when a session cannot be opened, so the failure is not retried on every call.\nconst cdpSessions = new WeakMap<Page, Promise<CDPSession | null>>();\n\n// Pages that have had focus emulation enabled at least once.\nconst focusEmulatedPages = new WeakSet<Page>();\n\n// Dialog dismissal per page, shared by every adaptor wrapping that page: how many dialogs were\n// dismissed and not yet reported, how many callers currently want dialogs dismissed, the listener\n// doing it while any does, and the last dialog the page raised, which may still be open.\ntype DialogState = {\n\tcount: number;\n\tholds: number;\n\tlistener: ((dialog: Dialog) => void) | null;\n\twatching: boolean;\n\tlast: Dialog | null;\n};\n\nfunction dialogStateOf(page: Page): DialogState {\n\tlet state = dialogStates.get(page);\n\n\tif (state === undefined) {\n\t\tstate = { count: 0, holds: 0, listener: null, watching: false, last: null };\n\t\tdialogStates.set(page, state);\n\t}\n\n\treturn state;\n}\n\n/**\n * Remember the last dialog `page` raised, without answering it. Puppeteer leaves a dialog nobody\n * answers open, and an open dialog blocks every call to the page, so whoever starts dismissing\n * dialogs later has to be able to close one that was raised before they started. Watching answers\n * nothing, so the caller's own `dialog` handler is unaffected.\n */\nfunction watchDialogsOn(page: Page): void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn;\n\t}\n\n\tconst state = dialogStateOf(page);\n\n\tif (state.watching) {\n\t\treturn;\n\t}\n\n\tstate.watching = true;\n\tpage.on(\"dialog\", (dialog: Dialog) => {\n\t\tstate.last = dialog;\n\t});\n}\n\nconst dialogStates = new WeakMap<Page, DialogState>();\n\nconst DEFAULT_SCREENSHOT_CLIP_SCALE = 2;\n\nfunction cdpSession(page: Page): Promise<CDPSession | null> {\n\tconst existing = cdpSessions.get(page);\n\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst session = page.createCDPSession().catch(() => null);\n\tcdpSessions.set(page, session);\n\n\treturn session;\n}\n\nexport type PuppeteerAdaptorOptions = {\n\t/** Device scale factor for evidence screenshots. Defaults to 2, applied per capture. */\n\tscreenshotClipScale?: number;\n\n\t/**\n\t * Trade PNG compression for capture speed. Defaults to true, which roughly doubles the encoded\n\t * size of each capture without changing a single pixel.\n\t */\n\toptimizeForSpeed?: boolean;\n\n\t/**\n\t * Let a clip capture content outside the current viewport. Defaults to false: to honour it\n\t * Chromium shrinks the emulated viewport to 1x1 and then resizes it for the clip before\n\t * restoring it, and the page observes each of those as a real resize (`resize` fires, media\n\t * queries flip to their narrowest breakpoint), which can collapse a responsive layout and blur\n\t * the focused element mid-capture. Only enable it for evidence of regions the caller cannot\n\t * scroll into view, where the page's state does not matter.\n\t */\n\tcaptureBeyondViewport?: boolean;\n\n\t/**\n\t * Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count\n\t * them. A dialog blocks the page until something answers it, so an unanswered one hangs every\n\t * later call.\n\t *\n\t * - `true`, the default: only while something has asked for it through `startDismissingDialogs`,\n\t * which a tab session does for as long as it runs. Outside that the page's dialogs are the\n\t * caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog\n\t * as it is raised still gets to.\n\t * - `\"always\"`: from construction, for the page's lifetime. For a caller that hands the whole\n\t * page over, such as the audit runner.\n\t * - `false`: never. The caller handles `dialog` events itself.\n\t */\n\tdismissDialogs?: boolean | \"always\";\n};\n\n/**\n * Dismiss the dialogs `page` raises, counting them, until the returned function is called. The\n * listener is on the page only while at least one caller holds it, so a caller's own `dialog`\n * handler has the page to itself the rest of the time.\n */\nfunction dismissDialogsOn(page: Page): () => void {\n\tif (typeof page.on !== \"function\") {\n\t\treturn () => {};\n\t}\n\n\tconst held = dialogStateOf(page);\n\n\tif (held.holds++ === 0) {\n\t\t// A dialog raised before anyone was dismissing them may still be open, blocking the page.\n\t\t// Dismissing one that was answered since rejects, which is fine. It is not counted: it\n\t\t// predates whatever is starting now.\n\t\tconst earlier = held.last;\n\t\theld.last = null;\n\n\t\tif (earlier !== null) {\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => earlier.dismiss())\n\t\t\t\t.catch(() => {});\n\t\t}\n\n\t\tconst listener = (dialog: Dialog): void => {\n\t\t\theld.count++;\n\n\t\t\t// Not answered until every other listener has had the dialog: one of the caller's own that\n\t\t\t// answers it as it is raised then gets to, instead of finding it already handled. The\n\t\t\t// dismissal rejects when that happened, which is as good as dismissed.\n\t\t\tsetTimeout(() => {\n\t\t\t\tdialog.dismiss().catch(() => {});\n\t\t\t}, 0);\n\t\t};\n\n\t\theld.listener = listener;\n\t\tpage.on(\"dialog\", listener);\n\t}\n\n\tlet released = false;\n\n\treturn () => {\n\t\tif (released) {\n\t\t\treturn;\n\t\t}\n\n\t\treleased = true;\n\n\t\tif (--held.holds === 0 && held.listener !== null) {\n\t\t\tpage.off(\"dialog\", held.listener);\n\t\t\theld.listener = null;\n\t\t}\n\t};\n}\n\n/** A BrowserAdaptor backed by a Puppeteer Page. */\nexport class PuppeteerAdaptor implements BrowserAdaptor {\n\treadonly screenshotClipScale: number;\n\n\tprivate readonly optimizeForSpeed: boolean;\n\n\tprivate readonly captureBeyondViewport: boolean;\n\n\tprivate readonly dismissDialogs: boolean | \"always\";\n\n\tconstructor(\n\t\tprivate readonly page: Page,\n\t\toptions: PuppeteerAdaptorOptions = {},\n\t) {\n\t\tthis.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;\n\t\tthis.optimizeForSpeed = options.optimizeForSpeed ?? true;\n\t\tthis.captureBeyondViewport = options.captureBeyondViewport ?? false;\n\t\tthis.dismissDialogs = options.dismissDialogs ?? true;\n\n\t\tif (this.dismissDialogs === \"always\") {\n\t\t\tdismissDialogsOn(page);\n\t\t} else if (this.dismissDialogs) {\n\t\t\twatchDialogsOn(page);\n\t\t}\n\t}\n\n\tstartDismissingDialogs(): () => void {\n\t\treturn this.dismissDialogs === false ? () => {} : dismissDialogsOn(this.page);\n\t}\n\n\ttakeDismissedDialogs(): number {\n\t\tconst state = dialogStates.get(this.page);\n\t\tconst count = state?.count ?? 0;\n\n\t\tif (state) {\n\t\t\tstate.count = 0;\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tevaluate<F extends PageFunction>(\n\t\tfn: F,\n\t\t...args: EvaluateArgs<Parameters<F>>\n\t): Promise<Awaited<ReturnType<F>>> {\n\t\t// Puppeteer resolves any JSHandle passed as an arg to the live element.\n\t\treturn this.page.evaluate(fn as never, ...(args as never[])) as Promise<Awaited<ReturnType<F>>>;\n\t}\n\n\tevaluateHandle(fn: () => Element | null): Promise<ElementRef> {\n\t\treturn this.page.evaluateHandle(fn);\n\t}\n\n\tasync disposeRef(ref: ElementRef): Promise<void> {\n\t\tawait (ref as JSHandle).dispose();\n\t}\n\n\tasync pressTab(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Tab\");\n\t}\n\n\tasync pressEnter(): Promise<void> {\n\t\tawait this.page.keyboard.press(\"Enter\");\n\t}\n\n\tasync pressKey(key: KeyName): Promise<void> {\n\t\tconst { keyboard } = this.page;\n\t\t// Puppeteer has no syntax for a combination, so modifiers are held down by hand.\n\t\tconst modifiers = key.split(\"+\") as KeyInput[];\n\t\tconst name = modifiers.pop()!;\n\n\t\tfor (const modifier of modifiers) {\n\t\t\tawait keyboard.down(modifier);\n\t\t}\n\n\t\ttry {\n\t\t\tawait keyboard.press(name);\n\t\t} finally {\n\t\t\tfor (const modifier of modifiers) {\n\t\t\t\tawait keyboard.up(modifier);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync screenshotClip(clip: Rect, scale = 1): Promise<Uint8Array> {\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (!session) {\n\t\t\tawait this.page.evaluate(nextPaintScript);\n\n\t\t\t// Without CDP the public API is all there is. With captureBeyondViewport off it intersects\n\t\t\t// the clip with the viewport, so a clip that does not fit comes back smaller than asked\n\t\t\t// for, with a shifted origin.\n\t\t\treturn (await this.page.screenshot({\n\t\t\t\ttype: \"png\",\n\t\t\t\toptimizeForSpeed: this.optimizeForSpeed,\n\t\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\t\tclip: { ...clip, scale },\n\t\t\t})) as Uint8Array;\n\t\t}\n\n\t\t// No wait for a paint first: Chromium renders a frame of the page as it stands for every\n\t\t// capture it is asked for through CDP.\n\t\t//\n\t\t// Straight to CDP rather than page.screenshot(): with captureBeyondViewport off, Puppeteer\n\t\t// intersects the clip with the visual viewport and silently moves the origin that callers\n\t\t// align element rects against. Keeping captureBeyondViewport off ensures that Chromium does\n\t\t// not resize the viewport, which can trigger media queries and hide the element we are\n\t\t// trying to capture.\n\t\tconst { data } = await session.send(\"Page.captureScreenshot\", {\n\t\t\tformat: \"png\",\n\t\t\toptimizeForSpeed: this.optimizeForSpeed,\n\t\t\tcaptureBeyondViewport: this.captureBeyondViewport,\n\t\t\tclip: { ...clip, scale },\n\t\t});\n\n\t\treturn Buffer.from(data, \"base64\");\n\t}\n\n\tasync ensureFocusReporting(): Promise<void> {\n\t\t// Pages only report focus while they are the foreground tab. Since this browser instance is\n\t\t// likely running in the background, we need to enable focus emulation to get accurate results.\n\t\t//\n\t\t// Note this function does not throw if enabling emulation fails; it is a best-effort.\n\t\ttry {\n\t\t\tconst session = await cdpSession(this.page);\n\n\t\t\tif (!session) {\n\t\t\t\tthrow new Error(\"Could not open a CDP session\");\n\t\t\t}\n\n\t\t\tif (focusEmulatedPages.has(this.page)) {\n\t\t\t\t// Chromium ignores a redundant enable, so re-asserting has to toggle.\n\t\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\t\tenabled: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait session.send(\"Emulation.setFocusEmulationEnabled\", {\n\t\t\t\tenabled: true,\n\t\t\t});\n\t\t\tfocusEmulatedPages.add(this.page);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Could not enable focus emulation for the browser adaptor\", {\n\t\t\t\terror,\n\t\t\t});\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAcA,IAAM,cAAc,oBAAI,QAA0C;AAGlE,IAAM,qBAAqB,oBAAI,QAAc;AAa7C,SAAS,cAAc,MAAyB;AAC/C,MAAI,QAAQ,aAAa,IAAI,IAAI;AAEjC,MAAI,UAAU,QAAW;AACxB,YAAQ,EAAE,OAAO,GAAG,OAAO,GAAG,UAAU,MAAM,UAAU,OAAO,MAAM,KAAK;AAC1E,iBAAa,IAAI,MAAM,KAAK;AAAA,EAC7B;AAEA,SAAO;AACR;AAQA,SAAS,eAAe,MAAkB;AACzC,MAAI,OAAO,KAAK,OAAO,YAAY;AAClC;AAAA,EACD;AAEA,QAAM,QAAQ,cAAc,IAAI;AAEhC,MAAI,MAAM,UAAU;AACnB;AAAA,EACD;AAEA,QAAM,WAAW;AACjB,OAAK,GAAG,UAAU,CAAC,WAAmB;AACrC,UAAM,OAAO;AAAA,EACd,CAAC;AACF;AAEA,IAAM,eAAe,oBAAI,QAA2B;AAEpD,IAAM,gCAAgC;AAEtC,SAAS,WAAW,MAAwC;AAC3D,QAAM,WAAW,YAAY,IAAI,IAAI;AAErC,MAAI,UAAU;AACb,WAAO;AAAA,EACR;AAEA,QAAM,UAAU,KAAK,iBAAiB,EAAE,MAAM,MAAM,IAAI;AACxD,cAAY,IAAI,MAAM,OAAO;AAE7B,SAAO;AACR;AA2CA,SAAS,iBAAiB,MAAwB;AACjD,MAAI,OAAO,KAAK,OAAO,YAAY;AAClC,WAAO,MAAM;AAAA,IAAC;AAAA,EACf;AAEA,QAAM,OAAO,cAAc,IAAI;AAE/B,MAAI,KAAK,YAAY,GAAG;A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;AAAA,MACR,kBAAkB,KAAK;AAAA,MACvB,uBAAuB,KAAK;AAAA,MAC5B,MAAM,EAAE,GAAG,MAAM,MAAM;AAAA,IACxB,CAAC;AAED,WAAO,OAAO,KAAK,MAAM,QAAQ;AAAA,EAClC;AAAA,EAEA,MAAM,uBAAsC;AAK3C,QAAI;AACH,YAAM,UAAU,MAAM,WAAW,KAAK,IAAI;AAE1C,UAAI,CAAC,SAAS;AACb,cAAM,IAAI,MAAM,8BAA8B;AAAA,MAC/C;AAEA,UAAI,mBAAmB,IAAI,KAAK,IAAI,GAAG;AAEtC,cAAM,QAAQ,KAAK,sCAAsC;AAAA,UACxD,SAAS;AAAA,QACV,CAAC;AAAA,MACF;AAEA,YAAM,QAAQ,KAAK,sCAAsC;AAAA,QACxD,SAAS;AAAA,MACV,CAAC;AACD,yBAAmB,IAAI,KAAK,IAAI;AAAA,IACjC,SAAS,OAAO;AACf,cAAQ,KAAK,4DAA4D;AAAA,QACxE;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AACD;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { BrowserAdaptor, ElementRef, KeyName, Rect } from "./adaptor";
|
|
1
|
+
export type { BrowserAdaptor, ElementRef, EvaluateArgs, KeyName, PageFunction, Rect, } from "./adaptor";
|
|
2
2
|
export { bufferedClip } from "./clip";
|
|
3
3
|
export type { Rgb } from "./contrast";
|
|
4
4
|
export { contrastRatio, parseOpaqueRgb, relativeLuminance } from "./contrast";
|