@ultimat3/cli 12.0.0 → 14.0.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.
@@ -0,0 +1,117 @@
1
+ // A document small enough to hold in a test and real enough to RUN the driver's own in-page
2
+ // expressions. Without it every claim about `getByRole` and `getByText` would be an assertion
3
+ // about a string, and a string that never executes cannot be wrong about a page.
4
+ //
5
+ // Its own file, the pattern `dev-roles-fixture.ts` and `policy-fixture.ts` already set here.
6
+
7
+ /** One element. `attrs` is data, so every read of it goes through `Object.hasOwn` below. */
8
+ export interface FakeE2eElement {
9
+ readonly tag: string;
10
+ readonly attrs: Readonly<Record<string, string>>;
11
+ readonly text?: string;
12
+ readonly children?: readonly FakeE2eElement[];
13
+ /** What `getComputedStyle` answers. Absent is the browser's own default — visible. */
14
+ readonly style?: { display?: string; visibility?: string; opacity?: string };
15
+ }
16
+
17
+ interface Node {
18
+ tagName: string;
19
+ textContent: string;
20
+ readonly attributes: Record<string, string>;
21
+ readonly descendants: Node[];
22
+ readonly style: { display: string; visibility: string; opacity: string };
23
+ getAttribute(name: string): string | null;
24
+ setAttribute(name: string, value: string): void;
25
+ removeAttribute(name: string): void;
26
+ contains(other: Node): boolean;
27
+ }
28
+
29
+ const textOf = (element: FakeE2eElement): string =>
30
+ [element.text ?? '', ...(element.children ?? []).map(textOf)]
31
+ .join(' ')
32
+ .replace(/\s+/g, ' ')
33
+ .trim();
34
+
35
+ function build(element: FakeE2eElement): Node {
36
+ const attributes: Record<string, string> = { ...element.attrs };
37
+ const children = (element.children ?? []).map(build);
38
+ const descendants = children.flatMap((child) => [child, ...child.descendants]);
39
+ const node: Node = {
40
+ tagName: element.tag.toUpperCase(),
41
+ textContent: textOf(element),
42
+ attributes,
43
+ descendants,
44
+ style: {
45
+ display: element.style?.display ?? 'block',
46
+ visibility: element.style?.visibility ?? 'visible',
47
+ opacity: element.style?.opacity ?? '1',
48
+ },
49
+ getAttribute: (name) => (Object.hasOwn(attributes, name) ? (attributes[name] as string) : null),
50
+ setAttribute: (name, value) => {
51
+ attributes[name] = value;
52
+ },
53
+ removeAttribute: (name) => {
54
+ delete attributes[name];
55
+ },
56
+ contains: (other) => descendants.includes(other),
57
+ };
58
+ return node;
59
+ }
60
+
61
+ /** `tag`, `*`, `[attr]`, `[attr="value"]` and any combination — every shape this driver emits. */
62
+ const SIMPLE = /^([a-zA-Z0-9*]*)((?:\[[^\]]*\])*)$/;
63
+
64
+ function matchesSimple(node: Node, selector: string): boolean {
65
+ const parsed = SIMPLE.exec(selector.trim());
66
+ if (parsed === null) return false;
67
+ const tag = parsed[1] ?? '';
68
+ if (tag !== '' && tag !== '*' && tag.toUpperCase() !== node.tagName) return false;
69
+ for (const clause of (parsed[2] ?? '').matchAll(/\[([^\]=]+)(?:=("[^"]*"|[^\]]*))?\]/g)) {
70
+ const name = (clause[1] ?? '').trim();
71
+ const held = node.getAttribute(name);
72
+ if (held === null) return false;
73
+ const raw = clause[2];
74
+ if (raw !== undefined && held !== raw.replace(/^"|"$/g, '')) return false;
75
+ }
76
+ return true;
77
+ }
78
+
79
+ const matches = (node: Node, selector: string): boolean =>
80
+ selector.split(',').some((part) => part.trim() !== '' && matchesSimple(node, part));
81
+
82
+ /**
83
+ * The globals a driver expression names, bound to one tree. `getComputedStyle` and `document` are
84
+ * handed in as arguments rather than assigned to `globalThis`: a test that installed a fake
85
+ * `document` on the process would leak it into every later file in the run.
86
+ */
87
+ export function fakeE2eDocument(root: FakeE2eElement): Readonly<Record<string, unknown>> {
88
+ const rootNode = build(root);
89
+ const all = [rootNode, ...rootNode.descendants];
90
+ return {
91
+ document: {
92
+ querySelectorAll: (selector: string): Node[] => all.filter((node) => matches(node, selector)),
93
+ querySelector: (selector: string): Node | null =>
94
+ all.find((node) => matches(node, selector)) ?? null,
95
+ getElementById: (id: string): Node | null =>
96
+ all.find((node) => node.getAttribute('id') === id) ?? null,
97
+ },
98
+ getComputedStyle: (node: Node) => node.style,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Run an expression the driver built, in THIS process, against a stubbed global scope.
104
+ *
105
+ * `new Function` and not `eval`: the body evaluates with no access to this module's scope, so a
106
+ * name the expression does not receive as a parameter is genuinely free — which is exactly the
107
+ * `ReferenceError` a captured closure produces in a real browser, and the thing the evaluate
108
+ * wrapper has to be proved against.
109
+ */
110
+ export async function runInFakePage(
111
+ expression: string,
112
+ globals: Readonly<Record<string, unknown>> = {},
113
+ ): Promise<unknown> {
114
+ const names = Object.keys(globals);
115
+ const body = new Function(...names, `return (${expression});`) as (...args: unknown[]) => unknown;
116
+ return await body(...names.map((name) => globals[name]));
117
+ }
@@ -0,0 +1,78 @@
1
+ // The registration. One call from an app's test preload turns the declared `page` fixture into a
2
+ // browser-backed one and gives `e2eTest` a driver — and nothing here runs unless that call is
3
+ // made, which is what keeps a CI box with no Chrome answering `hasE2eDriver() === false`.
4
+
5
+ import { test as bunTest } from 'bun:test';
6
+ import type { E2eBody, E2eFixtures, PageLike } from '@ultimat3/testing';
7
+ import {
8
+ defineFixtures,
9
+ FixtureUnavailableError,
10
+ resetE2eDriver,
11
+ unavailableFixture,
12
+ useE2eDriver,
13
+ } from '@ultimat3/testing';
14
+ import type { E2ePageOptions } from './e2e-page';
15
+ import { e2ePage } from './e2e-page';
16
+
17
+ export type E2eDriverOptions = E2ePageOptions;
18
+
19
+ /**
20
+ * The three `E2eFixtures` members this driver cannot build, and why each is a REFUSAL rather than
21
+ * a no-op. A fixture that silently did nothing would make the assertion after it read as proof:
22
+ * `offline()` followed by "the fallback rendered" is the app's ONLINE page passing an offline test.
23
+ *
24
+ * All three are genuinely out of reach of the shipped port, not merely unimplemented:
25
+ * `CdpPageLike` (`packages/scraping/src/cdp-port.ts`) declares twelve methods and none of them is
26
+ * `setOfflineMode`, and a new build id is a fact about the SERVER, which no page port has ever
27
+ * been able to speak for.
28
+ */
29
+ const refuse =
30
+ (name: string, needs: string): (() => Promise<void>) =>
31
+ () =>
32
+ Promise.reject(new FixtureUnavailableError({ name, needs }));
33
+
34
+ /** What `e2eTest` hands its body: a real page, and three members that say what they are missing. */
35
+ export const e2eFixtures = (page: PageLike): E2eFixtures => ({
36
+ page,
37
+ offline: refuse(
38
+ 'offline',
39
+ "a CDP method for the browser's own network state — the shipped CdpPageLike has no setOfflineMode",
40
+ ),
41
+ online: refuse('online', 'the same CDP method offline() needs, in order to undo it'),
42
+ update: refuse(
43
+ 'update',
44
+ 'a second build served under a new immutable build id, which is a server fact',
45
+ ),
46
+ });
47
+
48
+ /**
49
+ * Install the browser-backed driver for this process.
50
+ *
51
+ * Two seams, deliberately, because they are two questions. `defineFixtures({ page })` replaces the
52
+ * declaration `driverFixtures()` registered — the ordinary way a driver arrives, last registration
53
+ * wins — so every `test('…', async ({ page }) => …)` in the suite gets a browser. `useE2eDriver`
54
+ * is the other half: it is what makes `hasE2eDriver()` answer true and stops `e2eTest` becoming a
55
+ * `test.skip` a green gate reports over.
56
+ *
57
+ * `budget`, `signIn` and `deploy` are deliberately NOT registered here. Each needs something a
58
+ * page cannot supply — byte counts off a built `dist/`, an app's own sign-in route, a second build
59
+ * — so each keeps refusing with `X_TEST_FIXTURE_UNAVAILABLE` naming what it waits for.
60
+ *
61
+ * Returns the undo. `bun test` is one process, so a driver installed and never removed reaches
62
+ * every later file in the run.
63
+ */
64
+ export function installE2eDriver(options: E2eDriverOptions): () => void {
65
+ const page = e2ePage(options);
66
+ defineFixtures({ page: () => page });
67
+ useE2eDriver((name, body: E2eBody) => {
68
+ bunTest(name, () => body(e2eFixtures(page)));
69
+ });
70
+ return () => {
71
+ // Both halves, because both were installed. Putting the DECLARATION back — rather than
72
+ // deleting the key — is what keeps a later file's `{ page }` failing as
73
+ // `X_TEST_FIXTURE_UNAVAILABLE` (a driver is missing) instead of `X_TEST_FIXTURE_UNKNOWN`
74
+ // (register it), which is the wrong instruction for a name the framework declares.
75
+ defineFixtures({ page: unavailableFixture('page') });
76
+ resetE2eDriver();
77
+ };
78
+ }
@@ -0,0 +1,103 @@
1
+ // One constructor per way the browser-backed e2e page refuses. Every cause below quotes a value
2
+ // that came out of a BROWSER or out of a test's own `toString()`, so every one of them is
3
+ // rendered rather than interpolated.
4
+
5
+ import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
6
+ import type { E2eSelection } from './e2e-selection';
7
+ import { selectionCall } from './e2e-selection';
8
+
9
+ /** A page URL is uncontrolled text; a fix line has to parse after one lands inside it. */
10
+ const URL_PLACEHOLDER = '<the url the cause names>';
11
+
12
+ /**
13
+ * The closure never left the test process. `PageLike.evaluate` takes a function and CDP takes a
14
+ * string, so the only thing that can cross is `Function.prototype.toString()` — and a function
15
+ * with no readable source, or one expecting an argument nothing in the page will pass, has no
16
+ * honest string form at all.
17
+ */
18
+ export class E2eEvaluateUnsupportedError extends UltimateError {
19
+ constructor(input: { readonly reason: string; readonly source: string }) {
20
+ super({
21
+ code: 'X_E2E_EVALUATE_UNSUPPORTED',
22
+ cause: `page.evaluate() was given a function that ${input.reason}: ${renderCauseValue(input.source)}`,
23
+ fix: 'page.evaluate(() => document.title) # a zero-parameter arrow whose body names only page globals',
24
+ });
25
+ }
26
+ }
27
+
28
+ /**
29
+ * The closure crossed and then named something the page has never heard of. This is the failure
30
+ * the whole `evaluate` seam is built around: `const wanted = 3; page.evaluate(() => rows === wanted)`
31
+ * sends the source, so the page receives the NAME `wanted` and a `ReferenceError`. Reported with
32
+ * the binding's own name, because "it threw in the browser" sends the reader to the app.
33
+ */
34
+ export class E2eEvaluateCapturedError extends UltimateError {
35
+ constructor(input: { readonly binding: string; readonly source: string }) {
36
+ const binding = renderFixLiteral(input.binding, '<the binding the cause names>');
37
+ super({
38
+ code: 'X_E2E_EVALUATE_CAPTURED',
39
+ cause: `page.evaluate() ran ${renderCauseValue(input.source)} in the browser and ${renderCauseValue(input.binding)} is not defined there — a closure sends its source, never its scope`,
40
+ fix: `page.evaluate(() => document.querySelectorAll("script[src]").length) # write the value into the closure literally; the page has no binding named ${binding}`,
41
+ });
42
+ }
43
+ }
44
+
45
+ /**
46
+ * The expression ran and the PAGE threw — the app's own failure, not the driver's. Kept apart from
47
+ * the two above so the reader is sent to the app rather than to the test's closure.
48
+ */
49
+ export class E2eEvaluateThrewError extends UltimateError {
50
+ constructor(input: { readonly thrown: string; readonly url: string }) {
51
+ super({
52
+ code: 'X_E2E_EVALUATE_THREW',
53
+ cause: `the expression page.evaluate() ran threw inside the browser: ${renderCauseValue(input.thrown)}`,
54
+ fix: `x dev — then open ${renderFixLiteral(input.url, URL_PLACEHOLDER)} and run the same expression in the console; the throw is the page's`,
55
+ });
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Nothing matched. The fix is the retrying assertion and not a longer sleep: `toBeVisible()` looks
61
+ * again to a budget, while `click()` resolves the selection once — so a test that raced the render
62
+ * is asserting in the wrong order rather than waiting for the wrong length of time.
63
+ */
64
+ export class E2eLocatorEmptyError extends UltimateError {
65
+ constructor(input: { readonly selection: E2eSelection; readonly url: string }) {
66
+ const call = selectionCall(input.selection);
67
+ super({
68
+ code: 'X_E2E_LOCATOR_EMPTY',
69
+ cause: `${call} matched no element on ${renderCauseValue(input.url)}`,
70
+ fix: `await expect(${call}).toBeVisible() before acting on it — that assertion retries to a budget, click() resolves once`,
71
+ });
72
+ }
73
+ }
74
+
75
+ /**
76
+ * More than one matched and the caller asked to ACT. Never raised by `count()` or `isVisible()`:
77
+ * an assertion handed an ambiguous locator has an answer, and refusing there would turn a question
78
+ * into a crash. A click has no such answer — one of them is about to be pressed.
79
+ */
80
+ export class E2eLocatorAmbiguousError extends UltimateError {
81
+ constructor(input: { readonly selection: E2eSelection; readonly count: number }) {
82
+ const call = selectionCall(input.selection);
83
+ super({
84
+ code: 'X_E2E_LOCATOR_AMBIGUOUS',
85
+ cause: `${call} matched ${String(input.count)} elements and click() presses exactly one`,
86
+ fix: `${call}.first().click() # or narrow the selection until it matches one element`,
87
+ });
88
+ }
89
+ }
90
+
91
+ /**
92
+ * `waitForServiceWorker()` gave up. Bounded IN THE PAGE rather than here: an unbounded wait is a
93
+ * test that hangs, and CI then reports a runner timeout with no assertion anywhere in it.
94
+ */
95
+ export class E2eServiceWorkerAbsentError extends UltimateError {
96
+ constructor(input: { readonly url: string; readonly timeoutMs: number }) {
97
+ super({
98
+ code: 'X_E2E_SERVICE_WORKER_ABSENT',
99
+ cause: `no service worker took control of ${renderCauseValue(input.url)} within ${String(input.timeoutMs)}ms`,
100
+ fix: `x build --target static — the worker is generated by the pwa build; then confirm the route at ${renderFixLiteral(input.url, URL_PLACEHOLDER)} registers it`,
101
+ });
102
+ }
103
+ }
@@ -0,0 +1,156 @@
1
+ // The one crossing in this driver that cannot be lossless: `PageLike.evaluate` takes a CLOSURE and
2
+ // every browser port in the framework takes a STRING. What is supported is stated here, what is
3
+ // not is refused by name, and a page-side throw comes back as itself rather than as a driver fault.
4
+
5
+ import { renderCauseValue, stringField } from '@ultimat3/core';
6
+ import {
7
+ E2eEvaluateCapturedError,
8
+ E2eEvaluateThrewError,
9
+ E2eEvaluateUnsupportedError,
10
+ } from './e2e-errors';
11
+
12
+ /** Only what this driver needs from a page, so a test proves the crossing with two methods. */
13
+ export interface EvaluablePage {
14
+ evaluate(expression: string): Promise<unknown>;
15
+ url(): string;
16
+ }
17
+
18
+ /**
19
+ * A function with no source. `Function.prototype.toString` answers `[native code]` for a native
20
+ * function and for anything `.bind()` produced, so there is nothing to send and the page would be
21
+ * asked to evaluate a syntax error.
22
+ */
23
+ const NATIVE = /\{\s*\[native code\]\s*\}/;
24
+
25
+ /**
26
+ * The parameter list of an arrow or a function expression, as written. `PageLike.evaluate` declares
27
+ * `() => T`, so a declared parameter is a value the author meant to pass and cannot: nothing in
28
+ * the page will supply it, and it would silently arrive `undefined`.
29
+ */
30
+ const takesParameters = (source: string): boolean => {
31
+ const arrow = /^(?:async\s+)?\(([^)]*)\)\s*=>/.exec(source);
32
+ if (arrow !== null) return arrow[1]?.trim() !== '';
33
+ // `x => x * 2` — a single unparenthesised parameter, which is still a parameter.
34
+ if (/^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(source)) return true;
35
+ const fn = /^(?:async\s+)?function\s*\*?\s*[A-Za-z_$][\w$]*?\s*\(([^)]*)\)/.exec(source);
36
+ return fn !== null && fn[1]?.trim() !== '';
37
+ };
38
+
39
+ /**
40
+ * Is the source a standalone expression at all? A method shorthand — what `{ evaluate() {} }.evaluate`
41
+ * stringifies to — is `evaluate() { … }`, which is legal in an object literal and a syntax error
42
+ * anywhere else. `new Function` is the parser, and it PARSES only: nothing is called here, so no
43
+ * page code and no test code runs in this process.
44
+ */
45
+ const parses = (source: string): boolean => {
46
+ try {
47
+ new Function(`"use strict"; return (${source});`);
48
+ return true;
49
+ } catch {
50
+ return false;
51
+ }
52
+ };
53
+
54
+ /**
55
+ * The static half. Everything it refuses is refused before a byte reaches the browser, because the
56
+ * page's own answer for each of these would be a syntax error with the driver's wrapper in it.
57
+ */
58
+ export function closureSource(fn: (...args: never[]) => unknown): string {
59
+ const source = fn.toString();
60
+ if (NATIVE.test(source)) {
61
+ throw new E2eEvaluateUnsupportedError({
62
+ reason: 'is native or bound, so it has no source to send',
63
+ source,
64
+ });
65
+ }
66
+ if (takesParameters(source)) {
67
+ throw new E2eEvaluateUnsupportedError({
68
+ reason: 'declares a parameter, and nothing in the page will pass one',
69
+ source,
70
+ });
71
+ }
72
+ if (!parses(source)) {
73
+ throw new E2eEvaluateUnsupportedError({
74
+ reason: 'does not stringify to an expression the browser can parse',
75
+ source,
76
+ });
77
+ }
78
+ return source;
79
+ }
80
+
81
+ /**
82
+ * The wrapper. It CATCHES in the page and answers a value, rather than letting the throw cross the
83
+ * wire: `@ultimat3/scraping`'s `cdp-target.ts` wraps anything its `evaluate` rejects with as
84
+ * `X_SCRAPE_BROWSER_UNREACHABLE`, so an app error that travelled as a rejection would arrive
85
+ * labelled a dead socket.
86
+ *
87
+ * `Promise.resolve().then(…)` because the closure may be async and because a `ReferenceError` for
88
+ * a captured binding is raised when the body RUNS, not when the arrow is built.
89
+ */
90
+ export const evaluateExpression = (source: string): string =>
91
+ `(() => { const fn = (${source});
92
+ return Promise.resolve().then(() => fn()).then(
93
+ (value) => JSON.stringify({ ok: true, value: value }),
94
+ (error) => JSON.stringify({ ok: false, name: String(error && error.name || 'Error'), message: String(error && error.message || error) }),
95
+ );
96
+ })()`;
97
+
98
+ /**
99
+ * The envelope, read by hand rather than through a schema, and the reason is `value`: it is
100
+ * whatever the test's own closure returned, so no schema in this package can describe it and a
101
+ * `t.object` would strip the one field the caller came for. Everything the DRIVER reads — the
102
+ * discriminant, the error name, the message — is read defensively through core's `stringField`,
103
+ * which is total against a getter that throws.
104
+ *
105
+ * A malformed answer degrades into the failure branch instead of a branch of its own: the wrapper
106
+ * below is the only writer, so anything else is a page that shadowed `JSON.stringify`, and the
107
+ * reader needs to see what came back either way.
108
+ */
109
+ type Envelope =
110
+ | { readonly ok: true; readonly value: unknown }
111
+ | { readonly ok: false; readonly name: string; readonly message: string };
112
+
113
+ const decode = (raw: unknown): unknown => {
114
+ if (typeof raw !== 'string') return raw;
115
+ try {
116
+ return JSON.parse(raw) as unknown;
117
+ } catch {
118
+ return raw;
119
+ }
120
+ };
121
+
122
+ const readEnvelope = (raw: unknown): Envelope => {
123
+ const decoded = decode(raw);
124
+ if (typeof decoded === 'object' && decoded !== null) {
125
+ const held = decoded as { readonly ok?: unknown; readonly value?: unknown };
126
+ if (held.ok === true) return { ok: true, value: held.value };
127
+ return {
128
+ ok: false,
129
+ name: stringField(decoded, 'name') ?? 'Error',
130
+ message: stringField(decoded, 'message') ?? renderCauseValue(raw),
131
+ };
132
+ }
133
+ return { ok: false, name: 'Error', message: renderCauseValue(raw) };
134
+ };
135
+
136
+ /** V8's wording for a free identifier. The name is the whole value of the refusal it produces. */
137
+ const NOT_DEFINED = /^([A-Za-z_$][\w$]*) is not defined$/;
138
+
139
+ /**
140
+ * Run the closure in the page and hand back what it answered.
141
+ *
142
+ * The cast on the way out is the generic boundary and nothing more: `evaluate<T>` is the CALLER's
143
+ * claim about what its own closure returns, and no schema in this process can check a claim the
144
+ * browser was never told about. Everything the driver itself reads is read above.
145
+ */
146
+ export async function evaluateClosure<T>(page: EvaluablePage, fn: () => T): Promise<Awaited<T>> {
147
+ const source = closureSource(fn);
148
+ const envelope = readEnvelope(await page.evaluate(evaluateExpression(source)));
149
+ if (envelope.ok) return envelope.value as Awaited<T>;
150
+ const captured = envelope.name === 'ReferenceError' ? NOT_DEFINED.exec(envelope.message) : null;
151
+ if (captured !== null) throw new E2eEvaluateCapturedError({ binding: captured[1] ?? '', source });
152
+ throw new E2eEvaluateThrewError({
153
+ thrown: `${envelope.name}: ${envelope.message}`,
154
+ url: page.url(),
155
+ });
156
+ }
@@ -0,0 +1,86 @@
1
+ // `LocatorLike` over a browser page: a handle that holds a SELECTION and resolves nothing until
2
+ // something asks. One round trip per question, and no waiting of its own — `toBeVisible()` owns
3
+ // the only retry budget in the harness and drives this by looking again.
4
+
5
+ import type { LocatorLike } from '@ultimat3/testing';
6
+ import { E2eLocatorAmbiguousError, E2eLocatorEmptyError } from './e2e-errors';
7
+ import type { E2eResolution, E2eSelection } from './e2e-selection';
8
+ import { markSelector, selectionExpression, unmarkExpression } from './e2e-selection';
9
+
10
+ /**
11
+ * What a locator needs from the browser. Narrower than `ScrapePage` on purpose: three methods is
12
+ * what a test has to stand up to prove the mapping, and `click` is taken from the page rather than
13
+ * re-derived here so the actionability wait `@ultimat3/scraping` already performs is the one that
14
+ * runs.
15
+ */
16
+ export interface LocatablePage {
17
+ evaluate(expression: string): Promise<unknown>;
18
+ click(selector: string): Promise<void>;
19
+ url(): string;
20
+ }
21
+
22
+ const readResolution = (raw: unknown): E2eResolution => {
23
+ const decoded = typeof raw === 'string' ? (JSON.parse(raw) as unknown) : raw;
24
+ const held = decoded as { count?: unknown; visible?: unknown; marked?: unknown };
25
+ return {
26
+ count: typeof held?.count === 'number' ? held.count : 0,
27
+ visible: held?.visible === true,
28
+ marked: held?.marked === true,
29
+ };
30
+ };
31
+
32
+ /**
33
+ * One mark per click, never a constant: two locators marking the same page at once would each
34
+ * click whichever element the other had just tagged. Seeded from a counter and not from
35
+ * `Math.random()`, which `bun run flight-copies` refuses in shipped source and which would make
36
+ * two runs of one test address two different elements.
37
+ */
38
+ let marks = 0;
39
+ const nextMark = (): string => {
40
+ marks += 1;
41
+ return `m${String(marks)}`;
42
+ };
43
+
44
+ /** Test seam: the counter is process-global, so a test that asserts a mark resets it first. */
45
+ export const resetLocatorMarks = (): void => {
46
+ marks = 0;
47
+ };
48
+
49
+ /**
50
+ * Nothing is cached. A locator taken before a navigation must address the page that is there when
51
+ * it is USED — the same rule `ScrapeFrame` states for a frame handle — so every method below
52
+ * re-resolves, and a handle can never go stale behind the caller's back.
53
+ */
54
+ export function e2eLocator(page: LocatablePage, selection: E2eSelection): LocatorLike {
55
+ const resolve = async (mark?: string): Promise<E2eResolution> =>
56
+ readResolution(await page.evaluate(selectionExpression(selection, mark)));
57
+
58
+ return {
59
+ count: async () => (await resolve()).count,
60
+ /**
61
+ * A point-in-time look, and deliberately not an ambiguity check: an assertion handed a locator
62
+ * that matched three elements has an ANSWER — was the first one visible — and a refusal there
63
+ * would turn `expect(...).toBeVisible()` into a crash rather than a verdict. Only `click`
64
+ * refuses, because only `click` has to pick one.
65
+ */
66
+ isVisible: async () => (await resolve()).visible,
67
+ first: () => e2eLocator(page, { ...selection, first: true }),
68
+ click: async () => {
69
+ const mark = nextMark();
70
+ const resolution = await resolve(mark);
71
+ if (resolution.count === 0) {
72
+ throw new E2eLocatorEmptyError({ selection, url: page.url() });
73
+ }
74
+ if (resolution.count > 1 && !selection.first) {
75
+ throw new E2eLocatorAmbiguousError({ selection, count: resolution.count });
76
+ }
77
+ try {
78
+ await page.click(markSelector(mark));
79
+ } finally {
80
+ // Best effort, and never allowed to replace the click's own failure: a click that
81
+ // navigated took the whole document — attribute included — with it.
82
+ await page.evaluate(unmarkExpression(mark)).catch(() => undefined);
83
+ }
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,124 @@
1
+ // `PageLike` over a browser page. The adapter itself: `@ultimat3/testing` declares the surface an
2
+ // e2e test drives and `@ultimat3/scraping` owns the only driver that can drive one, and neither
3
+ // may import the other — so the join is here, in the one package allowed to know about both.
4
+
5
+ import type { LocatorLike, PageLike } from '@ultimat3/testing';
6
+ import { E2eServiceWorkerAbsentError } from './e2e-errors';
7
+ import { evaluateClosure } from './e2e-evaluate';
8
+ import { e2eLocator } from './e2e-locator';
9
+ import type { E2eSelection } from './e2e-selection';
10
+
11
+ /**
12
+ * What this adapter needs of a browser: four members, every one of them on `ScrapePage`. Declared
13
+ * structurally rather than as `ScrapePage` so a test can stand one up in six lines — the same
14
+ * bargain `cdp-port.ts` makes about puppeteer, one layer up.
15
+ */
16
+ export interface E2eBrowserPage {
17
+ url(): string;
18
+ goto(url: string, options?: { readonly timeout?: number | undefined }): Promise<unknown>;
19
+ evaluate(expression: string): Promise<unknown>;
20
+ click(selector: string): Promise<void>;
21
+ }
22
+
23
+ export interface E2ePageOptions {
24
+ readonly page: E2eBrowserPage;
25
+ /** Every `goto('/feed')` in an e2e suite is app-relative; this is what makes one absolute. */
26
+ readonly baseUrl: string;
27
+ /** Per-navigation deadline, handed to the driver rather than enforced here. */
28
+ readonly timeoutMs?: number | undefined;
29
+ /** How long `waitForServiceWorker()` waits before refusing. Bounded IN THE PAGE. */
30
+ readonly serviceWorkerTimeoutMs?: number | undefined;
31
+ }
32
+
33
+ export const DEFAULT_E2E_TIMEOUT_MS = 30_000;
34
+ export const DEFAULT_SERVICE_WORKER_TIMEOUT_MS = 10_000;
35
+
36
+ /** Every in-page expression here answers JSON text, for the reason `cdp-snapshot.ts` states. */
37
+ const readField = (raw: unknown, key: string): unknown => {
38
+ const decoded = typeof raw === 'string' ? (JSON.parse(raw) as unknown) : raw;
39
+ return typeof decoded === 'object' && decoded !== null
40
+ ? (decoded as Record<string, unknown>)[key]
41
+ : undefined;
42
+ };
43
+
44
+ const TITLE = '(() => JSON.stringify({ title: document.title }))()';
45
+
46
+ /**
47
+ * The first flush, read by a `fetch` INSIDE the page after the navigation, because neither
48
+ * `ScrapePage` nor `CdpPageLike` exposes a response body — puppeteer's `page.on('response')` is
49
+ * not on the port and adding it would be an edit to `@ultimat3/scraping`.
50
+ *
51
+ * The cost, stated rather than hidden: this is a SECOND request to the same route, so what it
52
+ * measures is that route's streaming behaviour and not the byte-for-byte first chunk the open
53
+ * document received. It runs in the page, so it carries the page's cookies and its origin — a
54
+ * `fetch` from the test process would carry neither.
55
+ */
56
+ const firstFlushExpression = (url: string): string =>
57
+ `(() => fetch(${JSON.stringify(url)}, { credentials: 'same-origin' })
58
+ .then((response) => response.body.getReader().read())
59
+ .then((chunk) => JSON.stringify({ html: new TextDecoder().decode(chunk.value || new Uint8Array()) })))()`;
60
+
61
+ /**
62
+ * `ready` alone is not control: a first load activates a worker that is not yet the page's
63
+ * controller, and an offline assertion made in that window tests nothing. So this waits for
64
+ * `controllerchange` too — an EVENT, not a poll, so the harness still has exactly one retry loop.
65
+ */
66
+ const serviceWorkerExpression = (timeoutMs: number): string =>
67
+ `(() => {
68
+ if (!navigator.serviceWorker) return JSON.stringify({ controlled: false });
69
+ const controlled = new Promise((resolve) => {
70
+ if (navigator.serviceWorker.controller) { resolve(true); return; }
71
+ navigator.serviceWorker.addEventListener('controllerchange', () => resolve(true), { once: true });
72
+ });
73
+ const deadline = new Promise((resolve) => setTimeout(() => resolve(false), ${String(timeoutMs)}));
74
+ return Promise.race([navigator.serviceWorker.ready.then(() => controlled), deadline])
75
+ .catch(() => false)
76
+ .then((ok) => JSON.stringify({ controlled: ok === true }));
77
+ })()`;
78
+
79
+ /**
80
+ * The adapter. Every member re-reads the live page: a `PageLike` handed to a test outlives every
81
+ * navigation the test makes, so nothing here may capture a URL, a document or an element.
82
+ */
83
+ export function e2ePage(options: E2ePageOptions): PageLike {
84
+ const page = options.page;
85
+ const timeout = options.timeoutMs ?? DEFAULT_E2E_TIMEOUT_MS;
86
+ const swTimeout = options.serviceWorkerTimeoutMs ?? DEFAULT_SERVICE_WORKER_TIMEOUT_MS;
87
+ const absolute = (url: string): string => new URL(url, options.baseUrl).toString();
88
+ const locate = (selection: E2eSelection): LocatorLike => e2eLocator(page, selection);
89
+
90
+ return {
91
+ url: () => page.url(),
92
+ goto: (url) => page.goto(absolute(url), { timeout }),
93
+ // The page's OWN url, re-read at call time: a reload of the url the adapter was built with
94
+ // would navigate away from wherever the test had got to.
95
+ reload: () => page.goto(page.url(), { timeout }),
96
+ title: async () => {
97
+ const title = readField(await page.evaluate(TITLE), 'title');
98
+ return typeof title === 'string' ? title : '';
99
+ },
100
+ gotoStreamed: async (url) => {
101
+ const target = absolute(url);
102
+ await page.goto(target, { timeout });
103
+ const html = readField(await page.evaluate(firstFlushExpression(target)), 'html');
104
+ return { html: typeof html === 'string' ? html : '' };
105
+ },
106
+ waitForServiceWorker: async () => {
107
+ const raw = await page.evaluate(serviceWorkerExpression(swTimeout));
108
+ if (readField(raw, 'controlled') !== true) {
109
+ throw new E2eServiceWorkerAbsentError({ url: page.url(), timeoutMs: swTimeout });
110
+ }
111
+ },
112
+ evaluate: <T>(fn: () => T): Promise<T> => evaluateClosure(page, fn) as unknown as Promise<T>,
113
+ locator: (selector) => locate({ kind: 'css', selector, first: false }),
114
+ getByRole: (role, roleOptions) =>
115
+ locate({
116
+ kind: 'role',
117
+ role,
118
+ first: false,
119
+ ...(roleOptions?.name === undefined ? {} : { name: roleOptions.name }),
120
+ ...(roleOptions?.level === undefined ? {} : { level: roleOptions.level }),
121
+ }),
122
+ getByText: (text) => locate({ kind: 'text', text, first: false }),
123
+ };
124
+ }