@a11y-pulse/browser-adaptor 0.9.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/README.md +19 -3
- package/dist/adaptor.d.ts +21 -2
- package/dist/adaptors/playwright.d.ts +26 -2
- package/dist/adaptors/playwright.js +85 -7
- package/dist/adaptors/playwright.js.map +1 -1
- package/dist/adaptors/puppeteer.d.ts +19 -2
- package/dist/adaptors/puppeteer.js +78 -2
- package/dist/adaptors/puppeteer.js.map +1 -1
- package/dist/chunk-GRS3X3VZ.js +198 -0
- package/dist/chunk-GRS3X3VZ.js.map +1 -0
- package/dist/{chunk-QUDMCLZ7.js → chunk-M2OOSZU3.js} +2 -1
- package/dist/chunk-M2OOSZU3.js.map +1 -0
- package/dist/dom.d.ts +1 -1
- package/dist/dom.js +76 -7
- package/dist/dom.js.map +1 -1
- package/dist/get-selector.d.ts +12 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/truncate-html.d.ts +4 -0
- package/package.json +5 -5
- package/dist/chunk-QUDMCLZ7.js.map +0 -1
- package/dist/chunk-WI4RV7YK.js +0 -143
- package/dist/chunk-WI4RV7YK.js.map +0 -1
package/README.md
CHANGED
|
@@ -23,7 +23,7 @@ npm install @a11y-pulse/browser-adaptor
|
|
|
23
23
|
| `@a11y-pulse/browser-adaptor` | `BrowserAdaptor`, `ElementRef`, `Rect`, `bufferedClip`, `captureElementScreenshot`, `contrastRatio`, `parseOpaqueRgb`, `relativeLuminance`, `stashedElementHandle`, `stashedElementSelectors`, `releaseStashedElements`, and the page scripts `captureElementScreenshot` is built on |
|
|
24
24
|
| `@a11y-pulse/browser-adaptor/puppeteer` | `PuppeteerAdaptor` |
|
|
25
25
|
| `@a11y-pulse/browser-adaptor/playwright` | `PlaywrightAdaptor` |
|
|
26
|
-
| `@a11y-pulse/browser-adaptor/dom` | `getSelector`, `truncateHtml` |
|
|
26
|
+
| `@a11y-pulse/browser-adaptor/dom` | `getSelector`, `resolveSelector`, `truncateHtml` |
|
|
27
27
|
|
|
28
28
|
## Quickstart
|
|
29
29
|
|
|
@@ -56,11 +56,25 @@ interface BrowserAdaptor {
|
|
|
56
56
|
screenshotClip(clip: Rect, scale?: number): Promise<Uint8Array>;
|
|
57
57
|
readonly screenshotClipScale?: number;
|
|
58
58
|
ensureFocusReporting(): Promise<void>; // must not throw
|
|
59
|
+
takeDismissedDialogs?(): number; // optional
|
|
60
|
+
startDismissingDialogs?(): () => void; // optional
|
|
59
61
|
}
|
|
60
62
|
```
|
|
61
63
|
|
|
62
64
|
Consumers may ignore methods they do not need. `ensureFocusReporting` is best-effort and must not throw.
|
|
63
65
|
|
|
66
|
+
**Native dialogs.** An `alert`, `confirm`, `prompt` or `beforeunload` dialog blocks the page's scripts until something answers it, so a page that raises one from a focus handler would hang every later call. An adaptor should dismiss the dialogs an audit raises, and can report how many it has dismissed since the last call through the optional `takeDismissedDialogs`.
|
|
67
|
+
|
|
68
|
+
Both bundled adaptors take a `dismissDialogs` option:
|
|
69
|
+
|
|
70
|
+
| Value | When dialogs are dismissed |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `true` (default) | Only while something holds `startDismissingDialogs()`, which returns the function that stops it. A tab session holds it for as long as it runs. The rest of the time the adaptor answers nothing, so your own handler works as it would without the adaptor. A dialog that was already open when dismissing starts is closed too, so one raised earlier cannot hang a session: the Puppeteer adaptor keeps a `dialog` listener that only remembers the last dialog for this, and Playwright dismisses a dialog nothing listens for by itself. |
|
|
73
|
+
| `"always"` | From construction, for the page's lifetime. Use it when you hand the whole page over and run audits that do not tab through it (the audit runner does). |
|
|
74
|
+
| `false` | Never. You handle `dialog` events yourself. |
|
|
75
|
+
|
|
76
|
+
While it is dismissing, the adaptor answers a dialog only after every other `dialog` listener has been called, so a listener of yours that accepts or dismisses the dialog as it is raised still gets to. One that answers later, after an `await`, will find the dialog already dismissed.
|
|
77
|
+
|
|
64
78
|
## Puppeteer adaptor
|
|
65
79
|
|
|
66
80
|
`PuppeteerAdaptor` wraps a Puppeteer `Page`. Its CDP session is cached per page, so reusing a page across audit runs does not open extra sessions.
|
|
@@ -92,7 +106,7 @@ await browser.close();
|
|
|
92
106
|
|
|
93
107
|
Two differences from the Puppeteer adaptor are worth knowing about.
|
|
94
108
|
|
|
95
|
-
**`evaluate`
|
|
109
|
+
**`evaluate` and Content-Security-Policy.** Playwright's `evaluate` takes a single argument, so the adaptor packs the page function's source and its arguments into one tuple and rebuilds the function in the page with `new Function`. Where a page's Content-Security-Policy or Trusted Types policy refuses that, the adaptor falls back to having Playwright build the function through the protocol and calling it by handle, at the cost of two more round trips per call. Only if that is refused as well does it throw, with a message naming CSP as the cause rather than letting it read as a page failure. Puppeteer is unaffected, because CDP serialises the function itself.
|
|
96
110
|
|
|
97
111
|
**Screenshot scale depends on the engine.** On Chromium the adaptor screenshots over CDP, which honours `screenshotClipScale` per capture, so evidence images match Puppeteer's; it takes the same `captureBeyondViewport` option, off by default for the same reason. Firefox and WebKit expose no CDP, so the adaptor falls back to a full-page capture at the context's own `deviceScaleFactor`, which those engines take without resizing the viewport. There, create the context with a `deviceScaleFactor` matching `screenshotClipScale` (2 by default), or pass the scale you want:
|
|
98
112
|
|
|
@@ -106,7 +120,9 @@ new PlaywrightAdaptor(page, { screenshotClipScale: 1 });
|
|
|
106
120
|
import { getSelector, truncateHtml } from "@a11y-pulse/browser-adaptor/dom";
|
|
107
121
|
```
|
|
108
122
|
|
|
109
|
-
`getSelector` builds a compact selector for an element (intended to run in page context). `
|
|
123
|
+
`getSelector` builds a compact selector for an element (intended to run in page context). For an element inside an open shadow root it lists each host first, joined by ` >>> `, as in `site-footer >>> a.link`. That is deliberately not valid CSS: `document.querySelector` throws on it rather than resolving the inner part to a look-alike in the light DOM. `resolveSelector` (also a page-context function) turns any `getSelector` result back into its element, or `null`.
|
|
124
|
+
|
|
125
|
+
`truncateHtml` shortens an element's markup to its opening tag for display in results. It finds the end of the tag even when an attribute value contains a `>`, shortens long attribute values without cutting through a character reference or a surrogate pair, cuts `data:` URIs back to their media type, and replaces the `value` of a text-entry `<input>` with `[redacted]`, since that can hold whatever the page was pre-filled with for the person using it. Values that are labels or fixed choices (`submit`, `button`, `radio`, `checkbox` and the like) are kept.
|
|
110
126
|
|
|
111
127
|
A page script that collects many elements in one evaluate can leave them on `window` under a key of its own, then fetch selectors (or, with `stashedElementHandle`, a handle) for only the ones it reports:
|
|
112
128
|
|
package/dist/adaptor.d.ts
CHANGED
|
@@ -6,11 +6,16 @@ export type Rect = {
|
|
|
6
6
|
height: number;
|
|
7
7
|
};
|
|
8
8
|
/** A key, or a modifier and a key joined by `+`, as the adaptor's `pressKey` accepts it. */
|
|
9
|
-
export type KeyName = "Tab" | "Shift+Tab" | "Enter" | "Escape" | "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight";
|
|
9
|
+
export type KeyName = "Tab" | "Shift+Tab" | "Enter" | "Space" | "Escape" | "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight";
|
|
10
10
|
/**
|
|
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
|
*/
|
|
@@ -58,4 +63,18 @@ export interface BrowserAdaptor {
|
|
|
58
63
|
* This function must not throw.
|
|
59
64
|
*/
|
|
60
65
|
ensureFocusReporting(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* How many native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`) the adaptor has dismissed
|
|
68
|
+
* since this was last called. A dialog blocks the page's scripts until it is answered, so an
|
|
69
|
+
* adaptor has to dismiss them itself or a page that raises one hangs the audit. Optional: an
|
|
70
|
+
* adaptor without it is taken to report none.
|
|
71
|
+
*/
|
|
72
|
+
takeDismissedDialogs?(): number;
|
|
73
|
+
/**
|
|
74
|
+
* Dismiss native dialogs from now until the returned function is called. A tab session holds this
|
|
75
|
+
* for as long as it runs, so the adaptor need not interfere with the page's dialogs, or with a
|
|
76
|
+
* caller's own handling of them, the rest of the time. Optional: an adaptor without it is taken
|
|
77
|
+
* to deal with dialogs by itself.
|
|
78
|
+
*/
|
|
79
|
+
startDismissingDialogs?(): () => void;
|
|
61
80
|
}
|
|
@@ -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
|
|
@@ -17,14 +17,38 @@ export type PlaywrightAdaptorOptions = {
|
|
|
17
17
|
* page without resizing the viewport, so they ignore this.
|
|
18
18
|
*/
|
|
19
19
|
captureBeyondViewport?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count
|
|
22
|
+
* them. Playwright dismisses dialogs by itself only while nothing listens for them, and then
|
|
23
|
+
* nothing records that one appeared.
|
|
24
|
+
*
|
|
25
|
+
* - `true`, the default: only while something has asked for it through `startDismissingDialogs`,
|
|
26
|
+
* which a tab session does for as long as it runs. Outside that the page's dialogs are the
|
|
27
|
+
* caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog
|
|
28
|
+
* as it is raised still gets to.
|
|
29
|
+
* - `"always"`: from construction, for the page's lifetime. For a caller that hands the whole
|
|
30
|
+
* page over, such as the audit runner.
|
|
31
|
+
* - `false`: never. The caller handles `dialog` events itself.
|
|
32
|
+
*/
|
|
33
|
+
dismissDialogs?: boolean | "always";
|
|
20
34
|
};
|
|
21
35
|
/** A BrowserAdaptor backed by a Playwright Page. */
|
|
22
36
|
export declare class PlaywrightAdaptor implements BrowserAdaptor {
|
|
23
37
|
private readonly page;
|
|
24
38
|
readonly screenshotClipScale: number;
|
|
25
39
|
private readonly captureBeyondViewport;
|
|
40
|
+
private readonly dismissDialogs;
|
|
26
41
|
constructor(page: Page, options?: PlaywrightAdaptorOptions);
|
|
27
|
-
|
|
42
|
+
startDismissingDialogs(): () => void;
|
|
43
|
+
takeDismissedDialogs(): number;
|
|
44
|
+
evaluate<F extends PageFunction>(fn: F, ...args: EvaluateArgs<Parameters<F>>): Promise<Awaited<ReturnType<F>>>;
|
|
45
|
+
/**
|
|
46
|
+
* The route for pages whose Content-Security-Policy forbids `new Function()`: Playwright itself
|
|
47
|
+
* turns the source into a function, through the protocol rather than in page script, and the
|
|
48
|
+
* function is then called by handle. It costs two more round trips than the packed call, so it
|
|
49
|
+
* is only taken once that one has been refused.
|
|
50
|
+
*/
|
|
51
|
+
private evaluateWithoutEval;
|
|
28
52
|
evaluateHandle(fn: () => Element | null): Promise<ElementRef>;
|
|
29
53
|
disposeRef(ref: ElementRef): Promise<void>;
|
|
30
54
|
pressTab(): Promise<void>;
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
nextPaintScript
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-M2OOSZU3.js";
|
|
4
4
|
|
|
5
5
|
// src/adaptors/playwright.ts
|
|
6
6
|
var cdpSessions = /* @__PURE__ */ new WeakMap();
|
|
7
7
|
var focusEmulatedPages = /* @__PURE__ */ new WeakSet();
|
|
8
|
+
var dialogStates = /* @__PURE__ */ new WeakMap();
|
|
8
9
|
var DEFAULT_SCREENSHOT_CLIP_SCALE = 2;
|
|
9
|
-
var EVAL_BLOCKED = /EvalError|unsafe-eval|Content Security Policy/i;
|
|
10
|
+
var EVAL_BLOCKED = /EvalError|unsafe-eval|Content Security Policy|Trusted ?Type|TrustedScript/i;
|
|
10
11
|
function cdpSession(page) {
|
|
11
12
|
const existing = cdpSessions.get(page);
|
|
12
13
|
if (existing) {
|
|
@@ -23,15 +24,66 @@ function isChromium(page) {
|
|
|
23
24
|
return false;
|
|
24
25
|
}
|
|
25
26
|
}
|
|
27
|
+
function dismissDialogsOn(page) {
|
|
28
|
+
if (typeof page.on !== "function") {
|
|
29
|
+
return () => {
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
let state = dialogStates.get(page);
|
|
33
|
+
if (state === void 0) {
|
|
34
|
+
state = { count: 0, holds: 0, listener: null };
|
|
35
|
+
dialogStates.set(page, state);
|
|
36
|
+
}
|
|
37
|
+
const held = state;
|
|
38
|
+
if (held.holds++ === 0) {
|
|
39
|
+
const listener = (dialog) => {
|
|
40
|
+
held.count++;
|
|
41
|
+
setTimeout(() => {
|
|
42
|
+
dialog.dismiss().catch(() => {
|
|
43
|
+
});
|
|
44
|
+
}, 0);
|
|
45
|
+
};
|
|
46
|
+
held.listener = listener;
|
|
47
|
+
page.on("dialog", listener);
|
|
48
|
+
}
|
|
49
|
+
let released = false;
|
|
50
|
+
return () => {
|
|
51
|
+
if (released) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
released = true;
|
|
55
|
+
if (--held.holds === 0 && held.listener !== null) {
|
|
56
|
+
page.off("dialog", held.listener);
|
|
57
|
+
held.listener = null;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
26
61
|
var PlaywrightAdaptor = class {
|
|
27
62
|
constructor(page, options = {}) {
|
|
28
63
|
this.page = page;
|
|
29
64
|
this.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;
|
|
30
65
|
this.captureBeyondViewport = options.captureBeyondViewport ?? false;
|
|
66
|
+
this.dismissDialogs = options.dismissDialogs ?? true;
|
|
67
|
+
if (this.dismissDialogs === "always") {
|
|
68
|
+
dismissDialogsOn(page);
|
|
69
|
+
}
|
|
31
70
|
}
|
|
32
71
|
page;
|
|
33
72
|
screenshotClipScale;
|
|
34
73
|
captureBeyondViewport;
|
|
74
|
+
dismissDialogs;
|
|
75
|
+
startDismissingDialogs() {
|
|
76
|
+
return this.dismissDialogs === false ? () => {
|
|
77
|
+
} : dismissDialogsOn(this.page);
|
|
78
|
+
}
|
|
79
|
+
takeDismissedDialogs() {
|
|
80
|
+
const state = dialogStates.get(this.page);
|
|
81
|
+
const count = state?.count ?? 0;
|
|
82
|
+
if (state) {
|
|
83
|
+
state.count = 0;
|
|
84
|
+
}
|
|
85
|
+
return count;
|
|
86
|
+
}
|
|
35
87
|
async evaluate(fn, ...args) {
|
|
36
88
|
try {
|
|
37
89
|
return await this.page.evaluate(
|
|
@@ -40,13 +92,39 @@ var PlaywrightAdaptor = class {
|
|
|
40
92
|
);
|
|
41
93
|
} catch (error) {
|
|
42
94
|
const message = error instanceof Error ? error.message : String(error);
|
|
43
|
-
if (EVAL_BLOCKED.test(message)) {
|
|
95
|
+
if (!EVAL_BLOCKED.test(message)) {
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
return await this.evaluateWithoutEval(fn.toString(), args);
|
|
100
|
+
} catch (fallbackError) {
|
|
101
|
+
const fallbackMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
|
|
102
|
+
if (!EVAL_BLOCKED.test(fallbackMessage)) {
|
|
103
|
+
throw fallbackError;
|
|
104
|
+
}
|
|
44
105
|
throw new Error(
|
|
45
|
-
"
|
|
46
|
-
{ cause:
|
|
106
|
+
"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.",
|
|
107
|
+
{ cause: fallbackError }
|
|
47
108
|
);
|
|
48
109
|
}
|
|
49
|
-
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The route for pages whose Content-Security-Policy forbids `new Function()`: Playwright itself
|
|
114
|
+
* turns the source into a function, through the protocol rather than in page script, and the
|
|
115
|
+
* function is then called by handle. It costs two more round trips than the packed call, so it
|
|
116
|
+
* is only taken once that one has been refused.
|
|
117
|
+
*/
|
|
118
|
+
async evaluateWithoutEval(source, args) {
|
|
119
|
+
const handle = await this.page.evaluateHandle(`(${source})`);
|
|
120
|
+
try {
|
|
121
|
+
return await handle.evaluate(
|
|
122
|
+
(pageFn, packed) => pageFn(...packed),
|
|
123
|
+
args
|
|
124
|
+
);
|
|
125
|
+
} finally {
|
|
126
|
+
await handle.dispose().catch(() => {
|
|
127
|
+
});
|
|
50
128
|
}
|
|
51
129
|
}
|
|
52
130
|
evaluateHandle(fn) {
|
|
@@ -65,7 +143,6 @@ var PlaywrightAdaptor = class {
|
|
|
65
143
|
await this.page.keyboard.press(key);
|
|
66
144
|
}
|
|
67
145
|
async screenshotClip(clip, scale = 1) {
|
|
68
|
-
await this.page.evaluate(nextPaintScript);
|
|
69
146
|
const session = await cdpSession(this.page);
|
|
70
147
|
if (session) {
|
|
71
148
|
const { data } = await session.send("Page.captureScreenshot", {
|
|
@@ -75,6 +152,7 @@ var PlaywrightAdaptor = class {
|
|
|
75
152
|
});
|
|
76
153
|
return Buffer.from(data, "base64");
|
|
77
154
|
}
|
|
155
|
+
await this.page.evaluate(nextPaintScript);
|
|
78
156
|
return await this.page.screenshot({
|
|
79
157
|
type: "png",
|
|
80
158
|
fullPage: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adaptors/playwright.ts"],"sourcesContent":["import type { CDPSession, 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\nconst DEFAULT_SCREENSHOT_CLIP_SCALE = 2;\n\nconst EVAL_BLOCKED = /EvalError|unsafe-eval|Content Security Policy/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\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\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}\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 new Error(\n\t\t\t\t\t\"The Playwright adaptor rebuilds page functions with new Function(), which this page's Content-Security-Policy blocks. Allow 'unsafe-eval' in script-src, or use the Puppeteer adaptor.\",\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow error;\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\tawait this.page.evaluate(nextPaintScript);\n\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (session) {\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\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;AAE7C,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;AAuBO,IAAM,oBAAN,MAAkD;AAAA,EAKxD,YACkB,MACjB,UAAoC,CAAC,GACpC;AAFgB;AAGjB,SAAK,sBAAsB,QAAQ,uBAAuB;AAC1D,SAAK,wBAAwB,QAAQ,yBAAyB;AAAA,EAC/D;AAAA,EALkB;AAAA,EALT;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,MAAM,KAAK,KAAK,WAAW;AAAA,MAClC,MAAM;AAAA,MACN,UAAU;AAAA,MACV;AAAA,MACA,OAAO;AAAA,IACR,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,uBAAsC;AAK3C,UAAM,UAAU,MAAM,WAAW,KAAK,IAAI;AAE1C,QAAI,CAAC,SAAS;AAGb,UAAI,WAAW,KAAK,IAAI,GAAG;AAC1B,gBAAQ,KAAK,sDAAsD;AAAA,MACpE;AAEA;AAAA,IACD;AAEA,QAAI;AACH,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":[]}
|
|
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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;AAAA,MACN,UAAU;AAAA,MACV;AAAA,MACA,OAAO;AAAA,IACR,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,uBAAsC;AAK3C,UAAM,UAAU,MAAM,WAAW,KAAK,IAAI;AAE1C,QAAI,CAAC,SAAS;AAGb,UAAI,WAAW,KAAK,IAAI,GAAG;AAC1B,gBAAQ,KAAK,sDAAsD;AAAA,MACpE;AAEA;AAAA,IACD;AAEA,QAAI;AACH,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":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
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;
|
|
@@ -17,6 +17,20 @@ export type PuppeteerAdaptorOptions = {
|
|
|
17
17
|
* scroll into view, where the page's state does not matter.
|
|
18
18
|
*/
|
|
19
19
|
captureBeyondViewport?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Whether to dismiss native dialogs (`alert`, `confirm`, `prompt`, `beforeunload`), and count
|
|
22
|
+
* them. A dialog blocks the page until something answers it, so an unanswered one hangs every
|
|
23
|
+
* later call.
|
|
24
|
+
*
|
|
25
|
+
* - `true`, the default: only while something has asked for it through `startDismissingDialogs`,
|
|
26
|
+
* which a tab session does for as long as it runs. Outside that the page's dialogs are the
|
|
27
|
+
* caller's to handle, and inside it a `dialog` listener of the caller's that answers a dialog
|
|
28
|
+
* as it is raised still gets to.
|
|
29
|
+
* - `"always"`: from construction, for the page's lifetime. For a caller that hands the whole
|
|
30
|
+
* page over, such as the audit runner.
|
|
31
|
+
* - `false`: never. The caller handles `dialog` events itself.
|
|
32
|
+
*/
|
|
33
|
+
dismissDialogs?: boolean | "always";
|
|
20
34
|
};
|
|
21
35
|
/** A BrowserAdaptor backed by a Puppeteer Page. */
|
|
22
36
|
export declare class PuppeteerAdaptor implements BrowserAdaptor {
|
|
@@ -24,8 +38,11 @@ export declare class PuppeteerAdaptor implements BrowserAdaptor {
|
|
|
24
38
|
readonly screenshotClipScale: number;
|
|
25
39
|
private readonly optimizeForSpeed;
|
|
26
40
|
private readonly captureBeyondViewport;
|
|
41
|
+
private readonly dismissDialogs;
|
|
27
42
|
constructor(page: Page, options?: PuppeteerAdaptorOptions);
|
|
28
|
-
|
|
43
|
+
startDismissingDialogs(): () => void;
|
|
44
|
+
takeDismissedDialogs(): number;
|
|
45
|
+
evaluate<F extends PageFunction>(fn: F, ...args: EvaluateArgs<Parameters<F>>): Promise<Awaited<ReturnType<F>>>;
|
|
29
46
|
evaluateHandle(fn: () => Element | null): Promise<ElementRef>;
|
|
30
47
|
disposeRef(ref: ElementRef): Promise<void>;
|
|
31
48
|
pressTab(): Promise<void>;
|
|
@@ -1,10 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
nextPaintScript
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-M2OOSZU3.js";
|
|
4
4
|
|
|
5
5
|
// src/adaptors/puppeteer.ts
|
|
6
6
|
var cdpSessions = /* @__PURE__ */ new WeakMap();
|
|
7
7
|
var focusEmulatedPages = /* @__PURE__ */ new WeakSet();
|
|
8
|
+
function dialogStateOf(page) {
|
|
9
|
+
let state = dialogStates.get(page);
|
|
10
|
+
if (state === void 0) {
|
|
11
|
+
state = { count: 0, holds: 0, listener: null, watching: false, last: null };
|
|
12
|
+
dialogStates.set(page, state);
|
|
13
|
+
}
|
|
14
|
+
return state;
|
|
15
|
+
}
|
|
16
|
+
function watchDialogsOn(page) {
|
|
17
|
+
if (typeof page.on !== "function") {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const state = dialogStateOf(page);
|
|
21
|
+
if (state.watching) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
state.watching = true;
|
|
25
|
+
page.on("dialog", (dialog) => {
|
|
26
|
+
state.last = dialog;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
var dialogStates = /* @__PURE__ */ new WeakMap();
|
|
8
30
|
var DEFAULT_SCREENSHOT_CLIP_SCALE = 2;
|
|
9
31
|
function cdpSession(page) {
|
|
10
32
|
const existing = cdpSessions.get(page);
|
|
@@ -15,17 +37,71 @@ function cdpSession(page) {
|
|
|
15
37
|
cdpSessions.set(page, session);
|
|
16
38
|
return session;
|
|
17
39
|
}
|
|
40
|
+
function dismissDialogsOn(page) {
|
|
41
|
+
if (typeof page.on !== "function") {
|
|
42
|
+
return () => {
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const held = dialogStateOf(page);
|
|
46
|
+
if (held.holds++ === 0) {
|
|
47
|
+
const earlier = held.last;
|
|
48
|
+
held.last = null;
|
|
49
|
+
if (earlier !== null) {
|
|
50
|
+
Promise.resolve().then(() => earlier.dismiss()).catch(() => {
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
const listener = (dialog) => {
|
|
54
|
+
held.count++;
|
|
55
|
+
setTimeout(() => {
|
|
56
|
+
dialog.dismiss().catch(() => {
|
|
57
|
+
});
|
|
58
|
+
}, 0);
|
|
59
|
+
};
|
|
60
|
+
held.listener = listener;
|
|
61
|
+
page.on("dialog", listener);
|
|
62
|
+
}
|
|
63
|
+
let released = false;
|
|
64
|
+
return () => {
|
|
65
|
+
if (released) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
released = true;
|
|
69
|
+
if (--held.holds === 0 && held.listener !== null) {
|
|
70
|
+
page.off("dialog", held.listener);
|
|
71
|
+
held.listener = null;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
18
75
|
var PuppeteerAdaptor = class {
|
|
19
76
|
constructor(page, options = {}) {
|
|
20
77
|
this.page = page;
|
|
21
78
|
this.screenshotClipScale = options.screenshotClipScale ?? DEFAULT_SCREENSHOT_CLIP_SCALE;
|
|
22
79
|
this.optimizeForSpeed = options.optimizeForSpeed ?? true;
|
|
23
80
|
this.captureBeyondViewport = options.captureBeyondViewport ?? false;
|
|
81
|
+
this.dismissDialogs = options.dismissDialogs ?? true;
|
|
82
|
+
if (this.dismissDialogs === "always") {
|
|
83
|
+
dismissDialogsOn(page);
|
|
84
|
+
} else if (this.dismissDialogs) {
|
|
85
|
+
watchDialogsOn(page);
|
|
86
|
+
}
|
|
24
87
|
}
|
|
25
88
|
page;
|
|
26
89
|
screenshotClipScale;
|
|
27
90
|
optimizeForSpeed;
|
|
28
91
|
captureBeyondViewport;
|
|
92
|
+
dismissDialogs;
|
|
93
|
+
startDismissingDialogs() {
|
|
94
|
+
return this.dismissDialogs === false ? () => {
|
|
95
|
+
} : dismissDialogsOn(this.page);
|
|
96
|
+
}
|
|
97
|
+
takeDismissedDialogs() {
|
|
98
|
+
const state = dialogStates.get(this.page);
|
|
99
|
+
const count = state?.count ?? 0;
|
|
100
|
+
if (state) {
|
|
101
|
+
state.count = 0;
|
|
102
|
+
}
|
|
103
|
+
return count;
|
|
104
|
+
}
|
|
29
105
|
evaluate(fn, ...args) {
|
|
30
106
|
return this.page.evaluate(fn, ...args);
|
|
31
107
|
}
|
|
@@ -57,9 +133,9 @@ var PuppeteerAdaptor = class {
|
|
|
57
133
|
}
|
|
58
134
|
}
|
|
59
135
|
async screenshotClip(clip, scale = 1) {
|
|
60
|
-
await this.page.evaluate(nextPaintScript);
|
|
61
136
|
const session = await cdpSession(this.page);
|
|
62
137
|
if (!session) {
|
|
138
|
+
await this.page.evaluate(nextPaintScript);
|
|
63
139
|
return await this.page.screenshot({
|
|
64
140
|
type: "png",
|
|
65
141
|
optimizeForSpeed: this.optimizeForSpeed,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adaptors/puppeteer.ts"],"sourcesContent":["import type { CDPSession, 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\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\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\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}\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\tawait this.page.evaluate(nextPaintScript);\n\n\t\tconst session = await cdpSession(this.page);\n\n\t\tif (!session) {\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// 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;AAE7C,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;AAwBO,IAAM,mBAAN,MAAiD;AAAA,EAOvD,YACkB,MACjB,UAAmC,CAAC,GACnC;AAFgB;AAGjB,SAAK,sBAAsB,QAAQ,uBAAuB;AAC1D,SAAK,mBAAmB,QAAQ,oBAAoB;AACpD,SAAK,wBAAwB,QAAQ,yBAAyB;AAAA,EAC/D;AAAA,EANkB;AAAA,EAPT;AAAA,EAEQ;AAAA,EAEA;AAAA,EAWjB,SAEC,OACG,MACU;AAEb,WAAO,KAAK,KAAK,SAAS,IAAa,GAAI,IAAgB;AAAA,EAC5D;AAAA,EAEA,eAAe,IAA+C;AAC7D,WAAO,KAAK,KAAK,eAAe,EAAE;AAAA,EACnC;AAAA,EAEA,MAAM,WAAW,KAAgC;AAChD,UAAO,IAAiB,QAAQ;AAAA,EACjC;AAAA,EAEA,MAAM,WAA0B;AAC/B,UAAM,KAAK,KAAK,SAAS,MAAM,KAAK;AAAA,EACrC;AAAA,EAEA,MAAM,aAA4B;AACjC,UAAM,KAAK,KAAK,SAAS,MAAM,OAAO;AAAA,EAC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AsC;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":[]}
|
|
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;AACj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,MAAM,EAAE,GAAG,MAAM,MAAM;AAAA,MACxB,CAAC;AAAA,IACF;AAUA,UAAM,EAAE,KAAK,IAAI,MAAM,QAAQ,KAAK,0BAA0B;AAAA,MAC7D,QAAQ;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":[]}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// src/get-selector.ts
|
|
2
|
+
function getSelector(root) {
|
|
3
|
+
const MAX_LENGTH = 128;
|
|
4
|
+
const esc = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value;
|
|
5
|
+
const tagName = (node) => node.nodeType === 1 ? node.nodeName.toLowerCase() : node.nodeName.toUpperCase().replace(/^#/, "");
|
|
6
|
+
const rootOf = (element) => {
|
|
7
|
+
const node = element.getRootNode?.();
|
|
8
|
+
return node && typeof node.querySelectorAll === "function" ? node : null;
|
|
9
|
+
};
|
|
10
|
+
const countsByRoot = /* @__PURE__ */ new Map();
|
|
11
|
+
const matchCount = (queryRoot, selector) => {
|
|
12
|
+
let counts = countsByRoot.get(queryRoot);
|
|
13
|
+
if (counts === void 0) {
|
|
14
|
+
counts = /* @__PURE__ */ new Map();
|
|
15
|
+
countsByRoot.set(queryRoot, counts);
|
|
16
|
+
}
|
|
17
|
+
let count = counts.get(selector);
|
|
18
|
+
if (count === void 0) {
|
|
19
|
+
try {
|
|
20
|
+
count = queryRoot.querySelectorAll(selector).length;
|
|
21
|
+
} catch {
|
|
22
|
+
count = Number.POSITIVE_INFINITY;
|
|
23
|
+
}
|
|
24
|
+
counts.set(selector, count);
|
|
25
|
+
}
|
|
26
|
+
return count;
|
|
27
|
+
};
|
|
28
|
+
const classCount = (queryRoot, cls, selector) => {
|
|
29
|
+
const byClassName = queryRoot.getElementsByClassName;
|
|
30
|
+
if (typeof byClassName === "function" && typeof CSS !== "undefined" && typeof CSS.escape === "function") {
|
|
31
|
+
try {
|
|
32
|
+
return byClassName.call(queryRoot, cls).length;
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return matchCount(queryRoot, selector);
|
|
37
|
+
};
|
|
38
|
+
const safeMatches = (element, selector) => {
|
|
39
|
+
try {
|
|
40
|
+
return typeof element.matches === "function" && element.matches(selector);
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const idIsUnique = (element, id) => {
|
|
46
|
+
const queryRoot = rootOf(element);
|
|
47
|
+
return queryRoot === null || matchCount(queryRoot, `#${esc(id)}`) === 1;
|
|
48
|
+
};
|
|
49
|
+
const classFeature = (cls) => ({
|
|
50
|
+
feature: `.${esc(cls)}`,
|
|
51
|
+
sharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls)
|
|
52
|
+
});
|
|
53
|
+
const rarestFeature = (element, queryRoot) => {
|
|
54
|
+
const classes = Array.from(element.classList).slice(0, 8);
|
|
55
|
+
if (!queryRoot) {
|
|
56
|
+
const cls = classes[0];
|
|
57
|
+
return cls === void 0 ? null : classFeature(cls);
|
|
58
|
+
}
|
|
59
|
+
let best = null;
|
|
60
|
+
let bestCount = Number.POSITIVE_INFINITY;
|
|
61
|
+
for (const cls of classes) {
|
|
62
|
+
const candidate = classFeature(cls);
|
|
63
|
+
if (!safeMatches(element, candidate.feature)) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const count = classCount(queryRoot, cls, candidate.feature);
|
|
67
|
+
if (count < bestCount) {
|
|
68
|
+
best = candidate;
|
|
69
|
+
bestCount = count;
|
|
70
|
+
}
|
|
71
|
+
if (count === 1) {
|
|
72
|
+
return best;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const href = typeof element.getAttribute === "function" ? element.getAttribute("href") : null;
|
|
76
|
+
if (href && href.length <= 100 && !/["\\?]/.test(href)) {
|
|
77
|
+
const feature = `[href="${href}"]`;
|
|
78
|
+
if (safeMatches(element, feature) && matchCount(queryRoot, feature) < bestCount) {
|
|
79
|
+
return {
|
|
80
|
+
feature,
|
|
81
|
+
sharedBy: (sibling) => typeof sibling.getAttribute === "function" && sibling.getAttribute("href") === href
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return best;
|
|
86
|
+
};
|
|
87
|
+
const positionAmongSiblings = (element, sharedBy) => {
|
|
88
|
+
const siblings = element.parentNode?.children;
|
|
89
|
+
if (!siblings) {
|
|
90
|
+
return { nth: 0, ambiguous: false };
|
|
91
|
+
}
|
|
92
|
+
let nth = 0;
|
|
93
|
+
let count = 0;
|
|
94
|
+
let shared = 0;
|
|
95
|
+
for (const sibling of Array.from(siblings)) {
|
|
96
|
+
if (sibling.nodeName !== element.nodeName) {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
count++;
|
|
100
|
+
if (sibling === element) {
|
|
101
|
+
nth = count;
|
|
102
|
+
}
|
|
103
|
+
if (sharedBy(sibling)) {
|
|
104
|
+
shared++;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return { nth, ambiguous: shared > 1 };
|
|
108
|
+
};
|
|
109
|
+
const segmentFor = (element, queryRoot) => {
|
|
110
|
+
if (element.id && idIsUnique(element, element.id)) {
|
|
111
|
+
return { segment: `#${esc(element.id)}`, anchored: true };
|
|
112
|
+
}
|
|
113
|
+
const feature = rarestFeature(element, queryRoot);
|
|
114
|
+
let segment = tagName(element) + (feature === null ? "" : feature.feature);
|
|
115
|
+
const { nth, ambiguous } = positionAmongSiblings(
|
|
116
|
+
element,
|
|
117
|
+
feature === null ? () => true : feature.sharedBy
|
|
118
|
+
);
|
|
119
|
+
if (ambiguous && nth > 0) {
|
|
120
|
+
segment += `:nth-of-type(${nth})`;
|
|
121
|
+
}
|
|
122
|
+
return { segment, anchored: false };
|
|
123
|
+
};
|
|
124
|
+
const degradedSegmentFor = (element) => {
|
|
125
|
+
let segment = tagName(element);
|
|
126
|
+
const { nth, ambiguous } = positionAmongSiblings(element, () => true);
|
|
127
|
+
if (ambiguous && nth > 0) {
|
|
128
|
+
segment += `:nth-of-type(${nth})`;
|
|
129
|
+
}
|
|
130
|
+
return segment;
|
|
131
|
+
};
|
|
132
|
+
const selectorWithin = (start) => {
|
|
133
|
+
const segments = [];
|
|
134
|
+
let node = start;
|
|
135
|
+
const queryRoot = start && start.nodeType === 1 ? rootOf(start) : null;
|
|
136
|
+
try {
|
|
137
|
+
while (node && node.nodeType === 1) {
|
|
138
|
+
const element = node;
|
|
139
|
+
let { segment, anchored } = segmentFor(element, queryRoot);
|
|
140
|
+
const joinedWith = (candidate) => segments.length ? candidate.length + 1 + segments.join(">").length : candidate.length;
|
|
141
|
+
if (joinedWith(segment) > MAX_LENGTH - 1) {
|
|
142
|
+
segment = degradedSegmentFor(element);
|
|
143
|
+
anchored = false;
|
|
144
|
+
if (joinedWith(segment) > MAX_LENGTH - 1) {
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
segments.unshift(segment);
|
|
149
|
+
if (anchored) {
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
if (queryRoot && matchCount(queryRoot, segments.join(">")) === 1) {
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
node = element.parentNode;
|
|
156
|
+
}
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
return segments.join(">");
|
|
160
|
+
};
|
|
161
|
+
const parts = [selectorWithin(root)];
|
|
162
|
+
try {
|
|
163
|
+
let inner = root;
|
|
164
|
+
while (inner && inner.nodeType === 1) {
|
|
165
|
+
const tree = inner.getRootNode?.();
|
|
166
|
+
const host = tree && tree.nodeType === 11 ? tree.host ?? null : null;
|
|
167
|
+
if (!host) {
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
parts.unshift(selectorWithin(host));
|
|
171
|
+
inner = host;
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
}
|
|
175
|
+
return parts.join(" >>> ");
|
|
176
|
+
}
|
|
177
|
+
function resolveSelector(selector) {
|
|
178
|
+
let scope = document;
|
|
179
|
+
let element = null;
|
|
180
|
+
for (const part of selector.split(" >>> ")) {
|
|
181
|
+
try {
|
|
182
|
+
element = scope.querySelector(part);
|
|
183
|
+
} catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (!element) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
scope = element.shadowRoot ?? element;
|
|
190
|
+
}
|
|
191
|
+
return element;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export {
|
|
195
|
+
getSelector,
|
|
196
|
+
resolveSelector
|
|
197
|
+
};
|
|
198
|
+
//# sourceMappingURL=chunk-GRS3X3VZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/get-selector.ts"],"sourcesContent":["/**\n * Build a compact, hopefully-unique selector for any given element on the page. This function is\n * serialized and run in the page context, so it must not reference any symbols outside its own\n * scope.\n *\n * Mirrors axe-core's approach: each level contributes the fewest features that discriminate the\n * element (a unique id, the rarest single class, or an :nth-of-type position), and the walk stops\n * as soon as the joined selector matches exactly one element. Selectors stay short because of that\n * early stop, not because of truncation; the length budget is only a backstop.\n *\n * A selector is only unique within the tree the element lives in. For an element inside an open\n * shadow root, each host on the way out contributes its own selector, joined outermost first with\n * ` >>> `: `my-footer >>> a.link`. That is deliberately not valid CSS, so `document.querySelector`\n * throws on it rather than quietly resolving the inner part to some other element in the light DOM.\n * Use `resolveSelector` to turn one back into its element.\n */\nexport function getSelector(root: Node | null): string {\n\tconst MAX_LENGTH = 128;\n\n\tconst esc = (value: string): string =>\n\t\ttypeof CSS !== \"undefined\" && typeof CSS.escape === \"function\" ? CSS.escape(value) : value;\n\n\tconst tagName = (node: Node): string =>\n\t\tnode.nodeType === 1\n\t\t\t? node.nodeName.toLowerCase()\n\t\t\t: node.nodeName.toUpperCase().replace(/^#/, \"\");\n\n\t// A querySelectorAll-capable root (Document or ShadowRoot) for the element, used to confirm\n\t// uniqueness and class rarity. Absent on the plain objects used in the serialisation unit tests,\n\t// where we trust ids and walk to the top instead of stopping early.\n\tconst rootOf = (element: Element): ParentNode | null => {\n\t\tconst node = (element as Element & { getRootNode?: () => Node }).getRootNode?.();\n\n\t\treturn node && typeof (node as ParentNode).querySelectorAll === \"function\"\n\t\t\t? (node as ParentNode)\n\t\t\t: null;\n\t};\n\n\t// Counting matches walks the whole tree, and the same few selectors come up at every level of\n\t// the walk, so each count is taken once per call. Nothing changes the page in between.\n\tconst countsByRoot = new Map<ParentNode, Map<string, number>>();\n\n\tconst matchCount = (queryRoot: ParentNode, selector: string): number => {\n\t\tlet counts = countsByRoot.get(queryRoot);\n\n\t\tif (counts === undefined) {\n\t\t\tcounts = new Map();\n\t\t\tcountsByRoot.set(queryRoot, counts);\n\t\t}\n\n\t\tlet count = counts.get(selector);\n\n\t\tif (count === undefined) {\n\t\t\ttry {\n\t\t\t\tcount = queryRoot.querySelectorAll(selector).length;\n\t\t\t} catch {\n\t\t\t\t// A selector that fails to parse can't be relied on.\n\t\t\t\tcount = Number.POSITIVE_INFINITY;\n\t\t\t}\n\n\t\t\tcounts.set(selector, count);\n\t\t}\n\n\t\treturn count;\n\t};\n\n\t// How many elements in the root carry the class. Where the root offers it, the live collection\n\t// answers this: the browser keeps its length until the document changes, so the count stays cheap\n\t// across the many calls an audit makes, where a selector query walks the tree every time.\n\tconst classCount = (queryRoot: ParentNode, cls: string, selector: string): number => {\n\t\tconst byClassName = (queryRoot as Partial<Document>).getElementsByClassName;\n\n\t\tif (\n\t\t\ttypeof byClassName === \"function\" &&\n\t\t\ttypeof CSS !== \"undefined\" &&\n\t\t\ttypeof CSS.escape === \"function\"\n\t\t) {\n\t\t\ttry {\n\t\t\t\treturn byClassName.call(queryRoot, cls).length;\n\t\t\t} catch {}\n\t\t}\n\n\t\treturn matchCount(queryRoot, selector);\n\t};\n\n\t// A candidate feature is only usable if it actually selects this element; an escaping or engine\n\t// mismatch (e.g. CSS string escapes in an attribute value) could otherwise produce a selector\n\t// that matches nothing. Or a different element entirely.\n\tconst safeMatches = (element: Element, selector: string): boolean => {\n\t\ttry {\n\t\t\treturn typeof element.matches === \"function\" && element.matches(selector);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst idIsUnique = (element: Element, id: string): boolean => {\n\t\tconst queryRoot = rootOf(element);\n\n\t\treturn queryRoot === null || matchCount(queryRoot, `#${esc(id)}`) === 1;\n\t};\n\n\t// A discriminating feature for one level of the selector: its CSS text plus a predicate telling\n\t// whether a sibling would match the same feature (used to decide if an :nth-of-type pin is still\n\t// needed).\n\ttype Feature = {\n\t\tfeature: string;\n\t\tsharedBy: (sibling: Element) => boolean;\n\t};\n\n\tconst classFeature = (cls: string): Feature => ({\n\t\tfeature: `.${esc(cls)}`,\n\t\tsharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls),\n\t});\n\n\t// The single feature that narrows the element down the most: the class or href attribute with the\n\t// fewest matches in the root. Hrefs break ties between structurally-identical content blocks,\n\t// where classes and :nth-of-type (which only pins position within one parent) cannot. Without a\n\t// queryable root there is no rarity information, so the first class stands in.\n\tconst rarestFeature = (element: Element, queryRoot: ParentNode | null): Feature | null => {\n\t\tconst classes = Array.from(element.classList).slice(0, 8);\n\n\t\tif (!queryRoot) {\n\t\t\tconst cls = classes[0];\n\n\t\t\treturn cls === undefined ? null : classFeature(cls);\n\t\t}\n\n\t\tlet best: Feature | null = null;\n\t\tlet bestCount = Number.POSITIVE_INFINITY;\n\n\t\tfor (const cls of classes) {\n\t\t\tconst candidate = classFeature(cls);\n\n\t\t\tif (!safeMatches(element, candidate.feature)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst count = classCount(queryRoot, cls, candidate.feature);\n\n\t\t\tif (count < bestCount) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestCount = count;\n\t\t\t}\n\n\t\t\tif (count === 1) {\n\t\t\t\treturn best;\n\t\t\t}\n\t\t}\n\n\t\tconst href = typeof element.getAttribute === \"function\" ? element.getAttribute(\"href\") : null;\n\n\t\t// Skip hrefs with characters that change meaning inside a CSS string (quotes, backslashes), and\n\t\t// query strings, which are too volatile across runs to pin a selector to. Fragments (#main)\n\t\t// stay eligible. Skip links make stable discriminators.\n\t\tif (href && href.length <= 100 && !/[\"\\\\?]/.test(href)) {\n\t\t\tconst feature = `[href=\"${href}\"]`;\n\n\t\t\tif (safeMatches(element, feature) && matchCount(queryRoot, feature) < bestCount) {\n\t\t\t\treturn {\n\t\t\t\t\tfeature,\n\t\t\t\t\tsharedBy: (sibling) =>\n\t\t\t\t\t\ttypeof sibling.getAttribute === \"function\" && sibling.getAttribute(\"href\") === href,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t};\n\n\t// The element's 1-based position among same-tag siblings, and whether the chosen feature fails to\n\t// discriminate it from them (so the segment needs an :nth-of-type pin). Siblings are absent on\n\t// the serialisation test nodes. There we skip the pin.\n\tconst positionAmongSiblings = (\n\t\telement: Element,\n\t\tsharedBy: (sibling: Element) => boolean,\n\t): { nth: number; ambiguous: boolean } => {\n\t\tconst siblings = (element.parentNode as ParentNode | null)?.children;\n\n\t\tif (!siblings) {\n\t\t\treturn { nth: 0, ambiguous: false };\n\t\t}\n\n\t\tlet nth = 0;\n\t\tlet count = 0;\n\t\tlet shared = 0;\n\n\t\tfor (const sibling of Array.from(siblings)) {\n\t\t\tif (sibling.nodeName !== element.nodeName) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcount++;\n\n\t\t\tif (sibling === element) {\n\t\t\t\tnth = count;\n\t\t\t}\n\n\t\t\tif (sharedBy(sibling)) {\n\t\t\t\tshared++;\n\t\t\t}\n\t\t}\n\n\t\treturn { nth, ambiguous: shared > 1 };\n\t};\n\n\tconst segmentFor = (\n\t\telement: Element,\n\t\tqueryRoot: ParentNode | null,\n\t): { segment: string; anchored: boolean } => {\n\t\t// Only treat an id as an absolute anchor when it actually resolves to a single element: pages\n\t\t// with duplicate ids would otherwise yield a selector (e.g. \"#dup>a\") that matches several\n\t\t// elements.\n\t\tif (element.id && idIsUnique(element, element.id)) {\n\t\t\treturn { segment: `#${esc(element.id)}`, anchored: true };\n\t\t}\n\n\t\tconst feature = rarestFeature(element, queryRoot);\n\t\tlet segment = tagName(element) + (feature === null ? \"\" : feature.feature);\n\n\t\t// When same-tag siblings share the chosen feature, pin the position so the segment selects\n\t\t// exactly this element rather than all of them.\n\t\tconst { nth, ambiguous } = positionAmongSiblings(\n\t\t\telement,\n\t\t\tfeature === null ? () => true : feature.sharedBy,\n\t\t);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn { segment, anchored: false };\n\t};\n\n\t// A minimal segment for when a level's full segment would blow the budget (e.g. an enormous class\n\t// name or a long href): just the tag, pinned by position when same-tag siblings would make the\n\t// bare tag ambiguous.\n\tconst degradedSegmentFor = (element: Element): string => {\n\t\tlet segment = tagName(element);\n\n\t\tconst { nth, ambiguous } = positionAmongSiblings(element, () => true);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn segment;\n\t};\n\n\t// The selector for `start` within its own tree (the document, or the shadow root it is in).\n\tconst selectorWithin = (start: Node | null): string => {\n\t\tconst segments: string[] = [];\n\t\tlet node: Node | null = start;\n\t\tconst queryRoot = start && start.nodeType === 1 ? rootOf(start as Element) : null;\n\n\t\ttry {\n\t\t\t// Walk only element nodes. Stopping at the first non-element parent (the document, or a\n\t\t\t// ShadowRoot when the target is inside an open shadow root) keeps the selector within its tree\n\t\t\t// and avoids reading `classList` off a node that has none.\n\t\t\twhile (node && node.nodeType === 1) {\n\t\t\t\tconst element = node as Element;\n\t\t\t\tlet { segment, anchored } = segmentFor(element, queryRoot);\n\n\t\t\t\t// Keep within the budget (the +1 accounts for the \">\" that would join this segment to the\n\t\t\t\t// rest). A level whose full segment doesn't fit is degraded to tag + position rather than\n\t\t\t\t// discarded, so ancestor context is never lost to one long feature.\n\t\t\t\tconst joinedWith = (candidate: string): number =>\n\t\t\t\t\tsegments.length ? candidate.length + 1 + segments.join(\">\").length : candidate.length;\n\n\t\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\t\tsegment = degradedSegmentFor(element);\n\t\t\t\t\tanchored = false;\n\n\t\t\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsegments.unshift(segment);\n\n\t\t\t\tif (anchored) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Stop as soon as the selector already identifies a single element. This, not truncation, is\n\t\t\t\t// what keeps selectors short.\n\t\t\t\tif (queryRoot && matchCount(queryRoot, segments.join(\">\")) === 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tnode = element.parentNode;\n\t\t\t}\n\t\t} catch {\n\t\t\t// A malformed node tree must never crash the audit; return what we have.\n\t\t}\n\n\t\treturn segments.join(\">\");\n\t};\n\n\tconst parts: string[] = [selectorWithin(root)];\n\n\ttry {\n\t\tlet inner: Node | null = root;\n\n\t\t// Step out through each enclosing shadow root to its host.\n\t\twhile (inner && inner.nodeType === 1) {\n\t\t\tconst tree = (inner as Element & { getRootNode?: () => Node }).getRootNode?.();\n\t\t\tconst host: Element | null =\n\t\t\t\ttree && tree.nodeType === 11 ? ((tree as ShadowRoot).host ?? null) : null;\n\n\t\t\tif (!host) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tparts.unshift(selectorWithin(host));\n\t\t\tinner = host;\n\t\t}\n\t} catch {\n\t\t// As above: return what we have.\n\t}\n\n\treturn parts.join(\" >>> \");\n}\n\n/**\n * Find the element a `getSelector` selector names, stepping into the shadow root of each host it\n * lists. Returns `null` when any part matches nothing. This function is serialized and run in the\n * page context, so it must not reference any symbols outside its own scope.\n */\nexport function resolveSelector(selector: string): Element | null {\n\tlet scope: ParentNode = document;\n\tlet element: Element | null = null;\n\n\tfor (const part of selector.split(\" >>> \")) {\n\t\ttry {\n\t\t\telement = scope.querySelector(part);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (!element) {\n\t\t\treturn null;\n\t\t}\n\n\t\tscope = element.shadowRoot ?? element;\n\t}\n\n\treturn element;\n}\n"],"mappings":";AAgBO,SAAS,YAAY,MAA2B;AACtD,QAAM,aAAa;AAEnB,QAAM,MAAM,CAAC,UACZ,OAAO,QAAQ,eAAe,OAAO,IAAI,WAAW,aAAa,IAAI,OAAO,KAAK,IAAI;AAEtF,QAAM,UAAU,CAAC,SAChB,KAAK,aAAa,IACf,KAAK,SAAS,YAAY,IAC1B,KAAK,SAAS,YAAY,EAAE,QAAQ,MAAM,EAAE;AAKhD,QAAM,SAAS,CAAC,YAAwC;AACvD,UAAM,OAAQ,QAAmD,cAAc;AAE/E,WAAO,QAAQ,OAAQ,KAAoB,qBAAqB,aAC5D,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|
|
7
|
+
setTimeout(() => resolve(), 200);
|
|
7
8
|
});
|
|
8
9
|
}
|
|
9
10
|
|
|
10
11
|
export {
|
|
11
12
|
nextPaintScript
|
|
12
13
|
};
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
14
|
+
//# sourceMappingURL=chunk-M2OOSZU3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/paint.ts"],"sourcesContent":["/**\n * A doubleRAF that aims to wait until the page has painted the next frame.\n */\nexport function nextPaintScript(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\trequestAnimationFrame(() => {\n\t\t\trequestAnimationFrame(() => resolve());\n\t\t});\n\t\t// A page that is not being rendered (a background tab) never gets its frames.\n\t\tsetTimeout(() => resolve(), 200);\n\t});\n}\n"],"mappings":";AAGO,SAAS,kBAAiC;AAChD,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC/B,0BAAsB,MAAM;AAC3B,4BAAsB,MAAM,QAAQ,CAAC;AAAA,IACtC,CAAC;AAED,eAAW,MAAM,QAAQ,GAAG,GAAG;AAAA,EAChC,CAAC;AACF;","names":[]}
|
package/dist/dom.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { getSelector } from "./get-selector";
|
|
1
|
+
export { getSelector, resolveSelector } from "./get-selector";
|
|
2
2
|
export { type TruncateHtmlOptions, truncateHtml } from "./truncate-html";
|
package/dist/dom.js
CHANGED
|
@@ -1,35 +1,104 @@
|
|
|
1
1
|
import {
|
|
2
|
-
getSelector
|
|
3
|
-
|
|
2
|
+
getSelector,
|
|
3
|
+
resolveSelector
|
|
4
|
+
} from "./chunk-GRS3X3VZ.js";
|
|
4
5
|
|
|
5
6
|
// src/truncate-html.ts
|
|
6
7
|
var DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;
|
|
7
8
|
var DEFAULT_MAX_LENGTH = 300;
|
|
8
9
|
var ELLIPSIS = "...";
|
|
10
|
+
var REDACTED = "[redacted]";
|
|
11
|
+
var INPUT_TYPES_WITH_AUTHORED_VALUE = /* @__PURE__ */ new Set([
|
|
12
|
+
"button",
|
|
13
|
+
"checkbox",
|
|
14
|
+
"color",
|
|
15
|
+
"image",
|
|
16
|
+
"radio",
|
|
17
|
+
"range",
|
|
18
|
+
"reset",
|
|
19
|
+
"submit"
|
|
20
|
+
]);
|
|
21
|
+
function openingTagEnd(html) {
|
|
22
|
+
let quote = null;
|
|
23
|
+
let lastSignificant = "";
|
|
24
|
+
for (let i = 0; i < html.length; i++) {
|
|
25
|
+
const char = html[i];
|
|
26
|
+
if (quote !== null) {
|
|
27
|
+
if (char === quote) {
|
|
28
|
+
quote = null;
|
|
29
|
+
}
|
|
30
|
+
} else if ((char === '"' || char === "'") && lastSignificant === "=") {
|
|
31
|
+
quote = char;
|
|
32
|
+
} else if (char === ">") {
|
|
33
|
+
return i;
|
|
34
|
+
}
|
|
35
|
+
if (!/\s/.test(char)) {
|
|
36
|
+
lastSignificant = char;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return -1;
|
|
40
|
+
}
|
|
41
|
+
function attributeValue(openingTag, name) {
|
|
42
|
+
const afterTagName = openingTag.replace(/^<\s*[^\s/>]+/, "");
|
|
43
|
+
const attribute = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
44
|
+
for (const match of afterTagName.matchAll(attribute)) {
|
|
45
|
+
if (match[1].toLowerCase() === name) {
|
|
46
|
+
return match[2] ?? match[3] ?? match[4] ?? "";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
function sliceWhole(text, length) {
|
|
52
|
+
if (text.length <= length) {
|
|
53
|
+
return text;
|
|
54
|
+
}
|
|
55
|
+
let end = Math.max(length, 0);
|
|
56
|
+
const before = text.charCodeAt(end - 1);
|
|
57
|
+
if (before >= 55296 && before <= 56319) {
|
|
58
|
+
end--;
|
|
59
|
+
}
|
|
60
|
+
const ampersand = text.lastIndexOf("&", end - 1);
|
|
61
|
+
if (ampersand !== -1 && !text.slice(ampersand, end).includes(";")) {
|
|
62
|
+
const reference = /^&#?[a-z0-9]{1,31};/i.exec(text.slice(ampersand, ampersand + 34));
|
|
63
|
+
if (reference && ampersand + reference[0].length > end) {
|
|
64
|
+
end = ampersand;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return text.slice(0, end);
|
|
68
|
+
}
|
|
9
69
|
function truncateHtml(html, options = {}) {
|
|
10
70
|
if (!html) {
|
|
11
71
|
return "";
|
|
12
72
|
}
|
|
13
73
|
const maxAttributeValueLength = options.maxAttributeValueLength ?? DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH;
|
|
14
74
|
const maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH;
|
|
15
|
-
const closingBracket = html
|
|
75
|
+
const closingBracket = openingTagEnd(html);
|
|
16
76
|
const openingTag = closingBracket === -1 ? html : html.slice(0, closingBracket + 1);
|
|
77
|
+
const tagName = /^<\s*([^\s/>]+)/.exec(openingTag)?.[1]?.toLowerCase();
|
|
78
|
+
const inputType = (attributeValue(openingTag, "type") ?? "").trim().toLowerCase() || "text";
|
|
79
|
+
const redactValue = tagName === "input" && !INPUT_TYPES_WITH_AUTHORED_VALUE.has(inputType);
|
|
17
80
|
const trimmed = openingTag.replace(
|
|
18
|
-
|
|
19
|
-
(match, quote, value) => {
|
|
81
|
+
/([^\s"'<>/=]+)(\s*=\s*)(["'])([\s\S]*?)\3/g,
|
|
82
|
+
(match, name, equals, quote, value) => {
|
|
83
|
+
if (redactValue && name.toLowerCase() === "value" && value !== "") {
|
|
84
|
+
return `${name}${equals}${quote}${REDACTED}${quote}`;
|
|
85
|
+
}
|
|
20
86
|
if (value.length <= maxAttributeValueLength) {
|
|
21
87
|
return match;
|
|
22
88
|
}
|
|
23
|
-
|
|
89
|
+
const dataUri = /^\s*data:[^,]{0,64},/i.exec(value);
|
|
90
|
+
const kept = dataUri ? dataUri[0] : sliceWhole(value, maxAttributeValueLength);
|
|
91
|
+
return `${name}${equals}${quote}${kept}${ELLIPSIS}${quote}`;
|
|
24
92
|
}
|
|
25
93
|
);
|
|
26
94
|
if (trimmed.length > maxLength) {
|
|
27
|
-
return `${trimmed
|
|
95
|
+
return `${sliceWhole(trimmed, maxLength)}${ELLIPSIS}`;
|
|
28
96
|
}
|
|
29
97
|
return trimmed;
|
|
30
98
|
}
|
|
31
99
|
export {
|
|
32
100
|
getSelector,
|
|
101
|
+
resolveSelector,
|
|
33
102
|
truncateHtml
|
|
34
103
|
};
|
|
35
104
|
//# sourceMappingURL=dom.js.map
|
package/dist/dom.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/truncate-html.ts"],"sourcesContent":["const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;\nconst DEFAULT_MAX_LENGTH = 300;\nconst ELLIPSIS = \"...\";\n\nexport type TruncateHtmlOptions = {\n\tmaxAttributeValueLength?: number;\n\tmaxLength?: number;\n};\n\n/**\n * Given an element's outerHTML, produce a truncated version suitable for display in results. For\n * memory efficiency, pass a shallow outerHTML i.e. `Node.cloneNode(false).outerHTML`.\n */\nexport function truncateHtml(html: string, options: TruncateHtmlOptions = {}): string {\n\tif (!html) {\n\t\treturn \"\";\n\t}\n\n\tconst maxAttributeValueLength =\n\t\toptions.maxAttributeValueLength ?? DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH;\n\tconst maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH;\n\n\t// Keep only the opening tag\n\tconst closingBracket = html
|
|
1
|
+
{"version":3,"sources":["../src/truncate-html.ts"],"sourcesContent":["const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;\nconst DEFAULT_MAX_LENGTH = 300;\nconst ELLIPSIS = \"...\";\nconst REDACTED = \"[redacted]\";\n\n// Input types whose `value` is a label or a fixed choice the page author wrote, rather than text\n// that may have been filled in for the person using the page.\nconst INPUT_TYPES_WITH_AUTHORED_VALUE = new Set([\n\t\"button\",\n\t\"checkbox\",\n\t\"color\",\n\t\"image\",\n\t\"radio\",\n\t\"range\",\n\t\"reset\",\n\t\"submit\",\n]);\n\nexport type TruncateHtmlOptions = {\n\tmaxAttributeValueLength?: number;\n\tmaxLength?: number;\n};\n\n/**\n * Where the opening tag ends: the first `>` that is not inside a quoted attribute value. Serialised\n * HTML leaves `>` unescaped in attribute values, so the first one in the string is not always it.\n */\nfunction openingTagEnd(html: string): number {\n\tlet quote: string | null = null;\n\tlet lastSignificant = \"\";\n\n\tfor (let i = 0; i < html.length; i++) {\n\t\tconst char = html[i]!;\n\n\t\tif (quote !== null) {\n\t\t\tif (char === quote) {\n\t\t\t\tquote = null;\n\t\t\t}\n\t\t} else if ((char === '\"' || char === \"'\") && lastSignificant === \"=\") {\n\t\t\tquote = char;\n\t\t} else if (char === \">\") {\n\t\t\treturn i;\n\t\t}\n\n\t\tif (!/\\s/.test(char)) {\n\t\t\tlastSignificant = char;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\n/**\n * The value of the opening tag's own `name` attribute, or null without one. The tag is walked one\n * attribute at a time, so text inside another attribute's value is never mistaken for an attribute.\n */\nfunction attributeValue(openingTag: string, name: string): string | null {\n\tconst afterTagName = openingTag.replace(/^<\\s*[^\\s/>]+/, \"\");\n\tconst attribute = /([^\\s\"'<>/=]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+)))?/g;\n\n\tfor (const match of afterTagName.matchAll(attribute)) {\n\t\t// As in HTML, the first attribute of a name is the one that counts.\n\t\tif (match[1]!.toLowerCase() === name) {\n\t\t\treturn match[2] ?? match[3] ?? match[4] ?? \"\";\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * The first `length` characters of `text`, shortened further where the cut would otherwise split a\n * surrogate pair or a character reference such as `&`.\n */\nfunction sliceWhole(text: string, length: number): string {\n\tif (text.length <= length) {\n\t\treturn text;\n\t}\n\n\tlet end = Math.max(length, 0);\n\tconst before = text.charCodeAt(end - 1);\n\n\tif (before >= 0xd800 && before <= 0xdbff) {\n\t\tend--;\n\t}\n\n\tconst ampersand = text.lastIndexOf(\"&\", end - 1);\n\n\tif (ampersand !== -1 && !text.slice(ampersand, end).includes(\";\")) {\n\t\tconst reference = /^&#?[a-z0-9]{1,31};/i.exec(text.slice(ampersand, ampersand + 34));\n\n\t\tif (reference && ampersand + reference[0].length > end) {\n\t\t\tend = ampersand;\n\t\t}\n\t}\n\n\treturn text.slice(0, end);\n}\n\n/**\n * Given an element's outerHTML, produce a truncated version suitable for display in results. For\n * memory efficiency, pass a shallow outerHTML i.e. `Node.cloneNode(false).outerHTML`.\n *\n * Only the opening tag is kept. Long attribute values are shortened, `data:` URIs are cut back to\n * their media type, and the `value` of a text-entry `<input>` is redacted, since it can hold\n * whatever the page was pre-filled with for the person using it.\n */\nexport function truncateHtml(html: string, options: TruncateHtmlOptions = {}): string {\n\tif (!html) {\n\t\treturn \"\";\n\t}\n\n\tconst maxAttributeValueLength =\n\t\toptions.maxAttributeValueLength ?? DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH;\n\tconst maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH;\n\n\t// Keep only the opening tag\n\tconst closingBracket = openingTagEnd(html);\n\tconst openingTag = closingBracket === -1 ? html : html.slice(0, closingBracket + 1);\n\n\tconst tagName = /^<\\s*([^\\s/>]+)/.exec(openingTag)?.[1]?.toLowerCase();\n\tconst inputType = (attributeValue(openingTag, \"type\") ?? \"\").trim().toLowerCase() || \"text\";\n\tconst redactValue = tagName === \"input\" && !INPUT_TYPES_WITH_AUTHORED_VALUE.has(inputType);\n\n\t// Shorten long quoted attribute values, preserving the quote style.\n\tconst trimmed = openingTag.replace(\n\t\t/([^\\s\"'<>/=]+)(\\s*=\\s*)([\"'])([\\s\\S]*?)\\3/g,\n\t\t(match, name: string, equals: string, quote: string, value: string) => {\n\t\t\tif (redactValue && name.toLowerCase() === \"value\" && value !== \"\") {\n\t\t\t\treturn `${name}${equals}${quote}${REDACTED}${quote}`;\n\t\t\t}\n\n\t\t\tif (value.length <= maxAttributeValueLength) {\n\t\t\t\treturn match;\n\t\t\t}\n\n\t\t\tconst dataUri = /^\\s*data:[^,]{0,64},/i.exec(value);\n\t\t\tconst kept = dataUri ? dataUri[0] : sliceWhole(value, maxAttributeValueLength);\n\n\t\t\treturn `${name}${equals}${quote}${kept}${ELLIPSIS}${quote}`;\n\t\t},\n\t);\n\n\tif (trimmed.length > maxLength) {\n\t\treturn `${sliceWhole(trimmed, maxLength)}${ELLIPSIS}`;\n\t}\n\n\treturn trimmed;\n}\n"],"mappings":";;;;;;AAAA,IAAM,qCAAqC;AAC3C,IAAM,qBAAqB;AAC3B,IAAM,WAAW;AACjB,IAAM,WAAW;AAIjB,IAAM,kCAAkC,oBAAI,IAAI;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAWD,SAAS,cAAc,MAAsB;AAC5C,MAAI,QAAuB;AAC3B,MAAI,kBAAkB;AAEtB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACrC,UAAM,OAAO,KAAK,CAAC;AAEnB,QAAI,UAAU,MAAM;AACnB,UAAI,SAAS,OAAO;AACnB,gBAAQ;AAAA,MACT;AAAA,IACD,YAAY,SAAS,OAAO,SAAS,QAAQ,oBAAoB,KAAK;AACrE,cAAQ;AAAA,IACT,WAAW,SAAS,KAAK;AACxB,aAAO;AAAA,IACR;AAEA,QAAI,CAAC,KAAK,KAAK,IAAI,GAAG;AACrB,wBAAkB;AAAA,IACnB;AAAA,EACD;AAEA,SAAO;AACR;AAMA,SAAS,eAAe,YAAoB,MAA6B;AACxE,QAAM,eAAe,WAAW,QAAQ,iBAAiB,EAAE;AAC3D,QAAM,YAAY;AAElB,aAAW,SAAS,aAAa,SAAS,SAAS,GAAG;A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B,OAAe,UAAkB;AACtE,UAAI,eAAe,KAAK,YAAY,MAAM,WAAW,UAAU,IAAI;AAClE,eAAO,GAAG,IAAI,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,KAAK;AAAA,MACnD;AAEA,UAAI,MAAM,UAAU,yBAAyB;AAC5C,eAAO;AAAA,MACR;AAEA,YAAM,UAAU,wBAAwB,KAAK,KAAK;AAClD,YAAM,OAAO,UAAU,QAAQ,CAAC,IAAI,WAAW,OAAO,uBAAuB;AAE7E,aAAO,GAAG,IAAI,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,GAAG,QAAQ,GAAG,KAAK;AAAA,IAC1D;AAAA,EACD;AAEA,MAAI,QAAQ,SAAS,WAAW;AAC/B,WAAO,GAAG,WAAW,SAAS,SAAS,CAAC,GAAG,QAAQ;AAAA,EACpD;AAEA,SAAO;AACR;","names":[]}
|
package/dist/get-selector.d.ts
CHANGED
|
@@ -7,5 +7,17 @@
|
|
|
7
7
|
* element (a unique id, the rarest single class, or an :nth-of-type position), and the walk stops
|
|
8
8
|
* as soon as the joined selector matches exactly one element. Selectors stay short because of that
|
|
9
9
|
* early stop, not because of truncation; the length budget is only a backstop.
|
|
10
|
+
*
|
|
11
|
+
* A selector is only unique within the tree the element lives in. For an element inside an open
|
|
12
|
+
* shadow root, each host on the way out contributes its own selector, joined outermost first with
|
|
13
|
+
* ` >>> `: `my-footer >>> a.link`. That is deliberately not valid CSS, so `document.querySelector`
|
|
14
|
+
* throws on it rather than quietly resolving the inner part to some other element in the light DOM.
|
|
15
|
+
* Use `resolveSelector` to turn one back into its element.
|
|
10
16
|
*/
|
|
11
17
|
export declare function getSelector(root: Node | null): string;
|
|
18
|
+
/**
|
|
19
|
+
* Find the element a `getSelector` selector names, stepping into the shadow root of each host it
|
|
20
|
+
* lists. Returns `null` when any part matches nothing. This function is serialized and run in the
|
|
21
|
+
* page context, so it must not reference any symbols outside its own scope.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resolveSelector(selector: string): Element | null;
|
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";
|
package/dist/index.js
CHANGED
package/dist/truncate-html.d.ts
CHANGED
|
@@ -5,5 +5,9 @@ export type TruncateHtmlOptions = {
|
|
|
5
5
|
/**
|
|
6
6
|
* Given an element's outerHTML, produce a truncated version suitable for display in results. For
|
|
7
7
|
* memory efficiency, pass a shallow outerHTML i.e. `Node.cloneNode(false).outerHTML`.
|
|
8
|
+
*
|
|
9
|
+
* Only the opening tag is kept. Long attribute values are shortened, `data:` URIs are cut back to
|
|
10
|
+
* their media type, and the `value` of a text-entry `<input>` is redacted, since it can hold
|
|
11
|
+
* whatever the page was pre-filled with for the person using it.
|
|
8
12
|
*/
|
|
9
13
|
export declare function truncateHtml(html: string, options?: TruncateHtmlOptions): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@a11y-pulse/browser-adaptor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Shared browser adaptor primitives and DOM helpers for A11y Pulse accessibility audits.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
68
|
"playwright-core": ">=1.40",
|
|
69
|
-
"puppeteer": "^25.
|
|
69
|
+
"puppeteer": "^25.16.0"
|
|
70
70
|
},
|
|
71
71
|
"peerDependenciesMeta": {
|
|
72
72
|
"playwright-core": {
|
|
@@ -77,8 +77,8 @@
|
|
|
77
77
|
}
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
|
-
"happy-dom": "^21.0.
|
|
81
|
-
"playwright-core": "^1.
|
|
82
|
-
"puppeteer": "^25.
|
|
80
|
+
"happy-dom": "^21.0.4",
|
|
81
|
+
"playwright-core": "^1.65.0",
|
|
82
|
+
"puppeteer": "^25.16.0"
|
|
83
83
|
}
|
|
84
84
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/paint.ts"],"sourcesContent":["/**\n * A doubleRAF that aims to wait until the page has painted the next frame.\n */\nexport function nextPaintScript(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\trequestAnimationFrame(() => {\n\t\t\trequestAnimationFrame(() => resolve());\n\t\t});\n\t});\n}\n"],"mappings":";AAGO,SAAS,kBAAiC;AAChD,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC/B,0BAAsB,MAAM;AAC3B,4BAAsB,MAAM,QAAQ,CAAC;AAAA,IACtC,CAAC;AAAA,EACF,CAAC;AACF;","names":[]}
|
package/dist/chunk-WI4RV7YK.js
DELETED
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
// src/get-selector.ts
|
|
2
|
-
function getSelector(root) {
|
|
3
|
-
const MAX_LENGTH = 128;
|
|
4
|
-
const esc = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value;
|
|
5
|
-
const tagName = (node2) => node2.nodeType === 1 ? node2.nodeName.toLowerCase() : node2.nodeName.toUpperCase().replace(/^#/, "");
|
|
6
|
-
const rootOf = (element) => {
|
|
7
|
-
const node2 = element.getRootNode?.();
|
|
8
|
-
return node2 && typeof node2.querySelectorAll === "function" ? node2 : null;
|
|
9
|
-
};
|
|
10
|
-
const matchCount = (queryRoot2, selector) => {
|
|
11
|
-
try {
|
|
12
|
-
return queryRoot2.querySelectorAll(selector).length;
|
|
13
|
-
} catch {
|
|
14
|
-
return Number.POSITIVE_INFINITY;
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
const safeMatches = (element, selector) => {
|
|
18
|
-
try {
|
|
19
|
-
return typeof element.matches === "function" && element.matches(selector);
|
|
20
|
-
} catch {
|
|
21
|
-
return false;
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
const idIsUnique = (element, id) => {
|
|
25
|
-
const queryRoot2 = rootOf(element);
|
|
26
|
-
return queryRoot2 === null || matchCount(queryRoot2, `#${esc(id)}`) === 1;
|
|
27
|
-
};
|
|
28
|
-
const classFeature = (cls) => ({
|
|
29
|
-
feature: `.${esc(cls)}`,
|
|
30
|
-
sharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls)
|
|
31
|
-
});
|
|
32
|
-
const rarestFeature = (element, queryRoot2) => {
|
|
33
|
-
const classes = Array.from(element.classList).slice(0, 8);
|
|
34
|
-
if (!queryRoot2) {
|
|
35
|
-
const cls = classes[0];
|
|
36
|
-
return cls === void 0 ? null : classFeature(cls);
|
|
37
|
-
}
|
|
38
|
-
let best = null;
|
|
39
|
-
let bestCount = Number.POSITIVE_INFINITY;
|
|
40
|
-
for (const cls of classes) {
|
|
41
|
-
const candidate = classFeature(cls);
|
|
42
|
-
if (!safeMatches(element, candidate.feature)) {
|
|
43
|
-
continue;
|
|
44
|
-
}
|
|
45
|
-
const count = matchCount(queryRoot2, candidate.feature);
|
|
46
|
-
if (count < bestCount) {
|
|
47
|
-
best = candidate;
|
|
48
|
-
bestCount = count;
|
|
49
|
-
}
|
|
50
|
-
if (count === 1) {
|
|
51
|
-
return best;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
const href = typeof element.getAttribute === "function" ? element.getAttribute("href") : null;
|
|
55
|
-
if (href && href.length <= 100 && !/["\\?]/.test(href)) {
|
|
56
|
-
const feature = `[href="${href}"]`;
|
|
57
|
-
if (safeMatches(element, feature) && matchCount(queryRoot2, feature) < bestCount) {
|
|
58
|
-
return {
|
|
59
|
-
feature,
|
|
60
|
-
sharedBy: (sibling) => typeof sibling.getAttribute === "function" && sibling.getAttribute("href") === href
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
return best;
|
|
65
|
-
};
|
|
66
|
-
const positionAmongSiblings = (element, sharedBy) => {
|
|
67
|
-
const siblings = element.parentNode?.children;
|
|
68
|
-
if (!siblings) {
|
|
69
|
-
return { nth: 0, ambiguous: false };
|
|
70
|
-
}
|
|
71
|
-
let nth = 0;
|
|
72
|
-
let count = 0;
|
|
73
|
-
let shared = 0;
|
|
74
|
-
for (const sibling of Array.from(siblings)) {
|
|
75
|
-
if (sibling.nodeName !== element.nodeName) {
|
|
76
|
-
continue;
|
|
77
|
-
}
|
|
78
|
-
count++;
|
|
79
|
-
if (sibling === element) {
|
|
80
|
-
nth = count;
|
|
81
|
-
}
|
|
82
|
-
if (sharedBy(sibling)) {
|
|
83
|
-
shared++;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return { nth, ambiguous: shared > 1 };
|
|
87
|
-
};
|
|
88
|
-
const segmentFor = (element, queryRoot2) => {
|
|
89
|
-
if (element.id && idIsUnique(element, element.id)) {
|
|
90
|
-
return { segment: `#${esc(element.id)}`, anchored: true };
|
|
91
|
-
}
|
|
92
|
-
const feature = rarestFeature(element, queryRoot2);
|
|
93
|
-
let segment = tagName(element) + (feature === null ? "" : feature.feature);
|
|
94
|
-
const { nth, ambiguous } = positionAmongSiblings(
|
|
95
|
-
element,
|
|
96
|
-
feature === null ? () => true : feature.sharedBy
|
|
97
|
-
);
|
|
98
|
-
if (ambiguous && nth > 0) {
|
|
99
|
-
segment += `:nth-of-type(${nth})`;
|
|
100
|
-
}
|
|
101
|
-
return { segment, anchored: false };
|
|
102
|
-
};
|
|
103
|
-
const degradedSegmentFor = (element) => {
|
|
104
|
-
let segment = tagName(element);
|
|
105
|
-
const { nth, ambiguous } = positionAmongSiblings(element, () => true);
|
|
106
|
-
if (ambiguous && nth > 0) {
|
|
107
|
-
segment += `:nth-of-type(${nth})`;
|
|
108
|
-
}
|
|
109
|
-
return segment;
|
|
110
|
-
};
|
|
111
|
-
const segments = [];
|
|
112
|
-
let node = root;
|
|
113
|
-
const queryRoot = root && root.nodeType === 1 ? rootOf(root) : null;
|
|
114
|
-
try {
|
|
115
|
-
while (node && node.nodeType === 1) {
|
|
116
|
-
const element = node;
|
|
117
|
-
let { segment, anchored } = segmentFor(element, queryRoot);
|
|
118
|
-
const joinedWith = (candidate) => segments.length ? candidate.length + 1 + segments.join(">").length : candidate.length;
|
|
119
|
-
if (joinedWith(segment) > MAX_LENGTH - 1) {
|
|
120
|
-
segment = degradedSegmentFor(element);
|
|
121
|
-
anchored = false;
|
|
122
|
-
if (joinedWith(segment) > MAX_LENGTH - 1) {
|
|
123
|
-
break;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
segments.unshift(segment);
|
|
127
|
-
if (anchored) {
|
|
128
|
-
break;
|
|
129
|
-
}
|
|
130
|
-
if (queryRoot && matchCount(queryRoot, segments.join(">")) === 1) {
|
|
131
|
-
break;
|
|
132
|
-
}
|
|
133
|
-
node = element.parentNode;
|
|
134
|
-
}
|
|
135
|
-
} catch {
|
|
136
|
-
}
|
|
137
|
-
return segments.join(">");
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export {
|
|
141
|
-
getSelector
|
|
142
|
-
};
|
|
143
|
-
//# sourceMappingURL=chunk-WI4RV7YK.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/get-selector.ts"],"sourcesContent":["/**\n * Build a compact, hopefully-unique selector for any given element on the page. This function is\n * serialized and run in the page context, so it must not reference any symbols outside its own\n * scope.\n *\n * Mirrors axe-core's approach: each level contributes the fewest features that discriminate the\n * element (a unique id, the rarest single class, or an :nth-of-type position), and the walk stops\n * as soon as the joined selector matches exactly one element. Selectors stay short because of that\n * early stop, not because of truncation; the length budget is only a backstop.\n */\nexport function getSelector(root: Node | null): string {\n\tconst MAX_LENGTH = 128;\n\n\tconst esc = (value: string): string =>\n\t\ttypeof CSS !== \"undefined\" && typeof CSS.escape === \"function\" ? CSS.escape(value) : value;\n\n\tconst tagName = (node: Node): string =>\n\t\tnode.nodeType === 1\n\t\t\t? node.nodeName.toLowerCase()\n\t\t\t: node.nodeName.toUpperCase().replace(/^#/, \"\");\n\n\t// A querySelectorAll-capable root (Document or ShadowRoot) for the element, used to confirm\n\t// uniqueness and class rarity. Absent on the plain objects used in the serialisation unit tests,\n\t// where we trust ids and walk to the top instead of stopping early.\n\tconst rootOf = (element: Element): ParentNode | null => {\n\t\tconst node = (element as Element & { getRootNode?: () => Node }).getRootNode?.();\n\n\t\treturn node && typeof (node as ParentNode).querySelectorAll === \"function\"\n\t\t\t? (node as ParentNode)\n\t\t\t: null;\n\t};\n\n\tconst matchCount = (queryRoot: ParentNode, selector: string): number => {\n\t\ttry {\n\t\t\treturn queryRoot.querySelectorAll(selector).length;\n\t\t} catch {\n\t\t\t// A selector that fails to parse can't be relied on.\n\t\t\treturn Number.POSITIVE_INFINITY;\n\t\t}\n\t};\n\n\t// A candidate feature is only usable if it actually selects this element; an escaping or engine\n\t// mismatch (e.g. CSS string escapes in an attribute value) could otherwise produce a selector\n\t// that matches nothing. Or a different element entirely.\n\tconst safeMatches = (element: Element, selector: string): boolean => {\n\t\ttry {\n\t\t\treturn typeof element.matches === \"function\" && element.matches(selector);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst idIsUnique = (element: Element, id: string): boolean => {\n\t\tconst queryRoot = rootOf(element);\n\n\t\treturn queryRoot === null || matchCount(queryRoot, `#${esc(id)}`) === 1;\n\t};\n\n\t// A discriminating feature for one level of the selector: its CSS text plus a predicate telling\n\t// whether a sibling would match the same feature (used to decide if an :nth-of-type pin is still\n\t// needed).\n\ttype Feature = {\n\t\tfeature: string;\n\t\tsharedBy: (sibling: Element) => boolean;\n\t};\n\n\tconst classFeature = (cls: string): Feature => ({\n\t\tfeature: `.${esc(cls)}`,\n\t\tsharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls),\n\t});\n\n\t// The single feature that narrows the element down the most: the class or href attribute with the\n\t// fewest matches in the root. Hrefs break ties between structurally-identical content blocks,\n\t// where classes and :nth-of-type (which only pins position within one parent) cannot. Without a\n\t// queryable root there is no rarity information, so the first class stands in.\n\tconst rarestFeature = (element: Element, queryRoot: ParentNode | null): Feature | null => {\n\t\tconst classes = Array.from(element.classList).slice(0, 8);\n\n\t\tif (!queryRoot) {\n\t\t\tconst cls = classes[0];\n\n\t\t\treturn cls === undefined ? null : classFeature(cls);\n\t\t}\n\n\t\tlet best: Feature | null = null;\n\t\tlet bestCount = Number.POSITIVE_INFINITY;\n\n\t\tfor (const cls of classes) {\n\t\t\tconst candidate = classFeature(cls);\n\n\t\t\tif (!safeMatches(element, candidate.feature)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst count = matchCount(queryRoot, candidate.feature);\n\n\t\t\tif (count < bestCount) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestCount = count;\n\t\t\t}\n\n\t\t\tif (count === 1) {\n\t\t\t\treturn best;\n\t\t\t}\n\t\t}\n\n\t\tconst href = typeof element.getAttribute === \"function\" ? element.getAttribute(\"href\") : null;\n\n\t\t// Skip hrefs with characters that change meaning inside a CSS string (quotes, backslashes), and\n\t\t// query strings, which are too volatile across runs to pin a selector to. Fragments (#main)\n\t\t// stay eligible. Skip links make stable discriminators.\n\t\tif (href && href.length <= 100 && !/[\"\\\\?]/.test(href)) {\n\t\t\tconst feature = `[href=\"${href}\"]`;\n\n\t\t\tif (safeMatches(element, feature) && matchCount(queryRoot, feature) < bestCount) {\n\t\t\t\treturn {\n\t\t\t\t\tfeature,\n\t\t\t\t\tsharedBy: (sibling) =>\n\t\t\t\t\t\ttypeof sibling.getAttribute === \"function\" && sibling.getAttribute(\"href\") === href,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t};\n\n\t// The element's 1-based position among same-tag siblings, and whether the chosen feature fails to\n\t// discriminate it from them (so the segment needs an :nth-of-type pin). Siblings are absent on\n\t// the serialisation test nodes. There we skip the pin.\n\tconst positionAmongSiblings = (\n\t\telement: Element,\n\t\tsharedBy: (sibling: Element) => boolean,\n\t): { nth: number; ambiguous: boolean } => {\n\t\tconst siblings = (element.parentNode as ParentNode | null)?.children;\n\n\t\tif (!siblings) {\n\t\t\treturn { nth: 0, ambiguous: false };\n\t\t}\n\n\t\tlet nth = 0;\n\t\tlet count = 0;\n\t\tlet shared = 0;\n\n\t\tfor (const sibling of Array.from(siblings)) {\n\t\t\tif (sibling.nodeName !== element.nodeName) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcount++;\n\n\t\t\tif (sibling === element) {\n\t\t\t\tnth = count;\n\t\t\t}\n\n\t\t\tif (sharedBy(sibling)) {\n\t\t\t\tshared++;\n\t\t\t}\n\t\t}\n\n\t\treturn { nth, ambiguous: shared > 1 };\n\t};\n\n\tconst segmentFor = (\n\t\telement: Element,\n\t\tqueryRoot: ParentNode | null,\n\t): { segment: string; anchored: boolean } => {\n\t\t// Only treat an id as an absolute anchor when it actually resolves to a single element: pages\n\t\t// with duplicate ids would otherwise yield a selector (e.g. \"#dup>a\") that matches several\n\t\t// elements.\n\t\tif (element.id && idIsUnique(element, element.id)) {\n\t\t\treturn { segment: `#${esc(element.id)}`, anchored: true };\n\t\t}\n\n\t\tconst feature = rarestFeature(element, queryRoot);\n\t\tlet segment = tagName(element) + (feature === null ? \"\" : feature.feature);\n\n\t\t// When same-tag siblings share the chosen feature, pin the position so the segment selects\n\t\t// exactly this element rather than all of them.\n\t\tconst { nth, ambiguous } = positionAmongSiblings(\n\t\t\telement,\n\t\t\tfeature === null ? () => true : feature.sharedBy,\n\t\t);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn { segment, anchored: false };\n\t};\n\n\t// A minimal segment for when a level's full segment would blow the budget (e.g. an enormous class\n\t// name or a long href): just the tag, pinned by position when same-tag siblings would make the\n\t// bare tag ambiguous.\n\tconst degradedSegmentFor = (element: Element): string => {\n\t\tlet segment = tagName(element);\n\n\t\tconst { nth, ambiguous } = positionAmongSiblings(element, () => true);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn segment;\n\t};\n\n\tconst segments: string[] = [];\n\tlet node: Node | null = root;\n\tconst queryRoot = root && root.nodeType === 1 ? rootOf(root as Element) : null;\n\n\ttry {\n\t\t// Walk only element nodes. Stopping at the first non-element parent (the document, or a\n\t\t// ShadowRoot when the target is inside an open shadow root) keeps the selector within its tree\n\t\t// and avoids reading `classList` off a node that has none.\n\t\twhile (node && node.nodeType === 1) {\n\t\t\tconst element = node as Element;\n\t\t\tlet { segment, anchored } = segmentFor(element, queryRoot);\n\n\t\t\t// Keep within the budget (the +1 accounts for the \">\" that would join this segment to the\n\t\t\t// rest). A level whose full segment doesn't fit is degraded to tag + position rather than\n\t\t\t// discarded, so ancestor context is never lost to one long feature.\n\t\t\tconst joinedWith = (candidate: string): number =>\n\t\t\t\tsegments.length ? candidate.length + 1 + segments.join(\">\").length : candidate.length;\n\n\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\tsegment = degradedSegmentFor(element);\n\t\t\t\tanchored = false;\n\n\t\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsegments.unshift(segment);\n\n\t\t\tif (anchored) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Stop as soon as the selector already identifies a single element. This, not truncation, is\n\t\t\t// what keeps selectors short.\n\t\t\tif (queryRoot && matchCount(queryRoot, segments.join(\">\")) === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnode = element.parentNode;\n\t\t}\n\t} catch {\n\t\t// A malformed node tree must never crash the audit; return what we have.\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