@jini-ai/diagnostics 0.5.1 → 0.5.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @jini-ai/diagnostics
2
2
 
3
+ ## 0.5.3 — 2026-10-15
4
+
5
+ - The public-page browser capture uses a fixed 1,000,000-char raw-HTML cap instead of `maxChars * 4` (0625844e), so a large style head no longer eats the readable-text budget; `maxChars` still caps the text.
6
+
3
7
  ## 0.5.1
4
8
 
5
9
  ### Patch Changes
@@ -140,6 +140,7 @@ export type ObservePageResult = {
140
140
  } | {
141
141
  readonly ok: false;
142
142
  readonly reason: string;
143
+ readonly offOriginUrl?: string;
143
144
  };
144
145
  /** A supplied consent selector triggers one click and a second observation; absence means no
145
146
  * interaction. This belongs to call options rather than the required page/limit contract. */
@@ -140,6 +140,9 @@ async function observeOnePage(browser, originBaseUrl, path, input, timeoutMs) {
140
140
  maxContrastSamples: SITE_EVIDENCE_LIMITS.maxContrastSamples,
141
141
  }, input.consentAcceptSelector === undefined ? {} : { consentAcceptSelector: input.consentAcceptSelector });
142
142
  if (!result.ok) {
143
+ if (result.offOriginUrl && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: result.offOriginUrl })) {
144
+ return { kind: "skipped", skipped: skip(path, "off-origin-redirect", `redirected off the inspected origin to '${redactToOrigin(result.offOriginUrl)}' — not inspected; this tool only observes ${originBaseUrl}`) };
145
+ }
143
146
  return { kind: "skipped", skipped: skip(path, "navigation-failed", result.reason) };
144
147
  }
145
148
  // Second same-origin layer (`same-origin.ts`'s header, layer 2): the path could not name
@@ -0,0 +1,52 @@
1
+ /** Shared lazy browser ownership, extracted from the host screenshot lifecycle. */
2
+ import type { RenderBrowser } from "./render-page.js";
3
+ /** Anything with an async `close` — a Playwright `Browser` satisfies it structurally. */
4
+ export interface ClosableBrowser {
5
+ close(): Promise<void>;
6
+ }
7
+ export interface LazyBrowser<B extends ClosableBrowser> {
8
+ /** The running browser, launching it on first use. A failed launch is retried on the next call. */
9
+ acquire(required?: {}, optional?: {}): Promise<B>;
10
+ /** Marks the end of one use; with `idleCloseMs` set, the browser closes once that long passes unused. */
11
+ release(required?: {}, optional?: {}): void;
12
+ /** Closes now. Safe to call repeatedly and when nothing was launched. */
13
+ close(required?: {}, optional?: {}): Promise<void>;
14
+ }
15
+ export interface LazyBrowserTimers {
16
+ setTimeout(work: () => void, ms: number): unknown;
17
+ clearTimeout(handle: unknown): void;
18
+ }
19
+ /**
20
+ * @param required.launch - Starts the browser; called at most once per launched lifetime.
21
+ * @param optional.idleCloseMs - Close this long after the last `release`; omitted, only `close` closes.
22
+ * @param optional.timers - Injected for tests.
23
+ * @complexity O(1) per call.
24
+ */
25
+ export declare function createLazyBrowser<B extends ClosableBrowser>({ launch }: {
26
+ launch: () => Promise<B>;
27
+ }, { idleCloseMs, timers }?: {
28
+ idleCloseMs?: number;
29
+ timers?: LazyBrowserTimers;
30
+ }): LazyBrowser<B>;
31
+ /** A lease retains a shared process while its isolated context is in use. */
32
+ export interface RenderBrowserLease {
33
+ browser: RenderBrowser;
34
+ release(): void;
35
+ }
36
+ export interface RenderBrowserPool {
37
+ acquire(required: Record<string, never>, optional?: {
38
+ signal?: AbortSignal;
39
+ }): Promise<RenderBrowserLease>;
40
+ close(required?: Record<string, never>, optional?: Record<string, never>): Promise<void>;
41
+ }
42
+ /** Reuse the lazy owner with a firm concurrent-context cap. Busy calls fail before launching.
43
+ * Late/cancelled acquisition releases its lease; idle timers never close an active sibling.
44
+ * @complexity O(1) per call; at most maxConcurrent contexts and one browser process. */
45
+ export declare function createRenderBrowserPool({ launch }: {
46
+ launch: () => Promise<RenderBrowser>;
47
+ }, { maxConcurrent, idleCloseMs, timers }?: {
48
+ maxConcurrent?: number;
49
+ idleCloseMs?: number;
50
+ timers?: LazyBrowserTimers;
51
+ }): RenderBrowserPool;
52
+ //# sourceMappingURL=lazy-browser.d.ts.map
@@ -0,0 +1,115 @@
1
+ const NODE_TIMERS = {
2
+ // `unref`: an idle-close timer must never keep a finishing process (or a test runner) alive.
3
+ setTimeout: (work, ms) => setTimeout(work, ms).unref(),
4
+ clearTimeout: (handle) => clearTimeout(handle),
5
+ };
6
+ /**
7
+ * @param required.launch - Starts the browser; called at most once per launched lifetime.
8
+ * @param optional.idleCloseMs - Close this long after the last `release`; omitted, only `close` closes.
9
+ * @param optional.timers - Injected for tests.
10
+ * @complexity O(1) per call.
11
+ */
12
+ export function createLazyBrowser({ launch }, { idleCloseMs, timers = NODE_TIMERS } = {}) {
13
+ let browser = null;
14
+ let active = 0;
15
+ let idleTimer = null;
16
+ function cancelIdleClose() {
17
+ if (idleTimer === null)
18
+ return;
19
+ timers.clearTimeout(idleTimer);
20
+ idleTimer = null;
21
+ }
22
+ async function close() {
23
+ cancelIdleClose();
24
+ const closing = browser;
25
+ browser = null;
26
+ if (closing === null)
27
+ return;
28
+ try {
29
+ await (await closing).close();
30
+ }
31
+ catch {
32
+ // A launch that failed has nothing to close; a close that failed leaves nothing to retry.
33
+ }
34
+ }
35
+ return {
36
+ acquire() {
37
+ cancelIdleClose();
38
+ active += 1;
39
+ const launching = browser ?? Promise.resolve().then(launch);
40
+ browser = launching;
41
+ // A failed launch must not be cached, or every later capture would replay the same rejection.
42
+ launching.catch(() => {
43
+ active = Math.max(0, active - 1);
44
+ if (browser === launching)
45
+ browser = null;
46
+ });
47
+ return launching;
48
+ },
49
+ release() {
50
+ active = Math.max(0, active - 1);
51
+ if (active > 0)
52
+ return;
53
+ if (idleCloseMs === undefined || browser === null)
54
+ return;
55
+ cancelIdleClose();
56
+ idleTimer = timers.setTimeout(() => { idleTimer = null; void close(); }, idleCloseMs);
57
+ },
58
+ close,
59
+ };
60
+ }
61
+ /** Reuse the lazy owner with a firm concurrent-context cap. Busy calls fail before launching.
62
+ * Late/cancelled acquisition releases its lease; idle timers never close an active sibling.
63
+ * @complexity O(1) per call; at most maxConcurrent contexts and one browser process. */
64
+ export function createRenderBrowserPool({ launch }, { maxConcurrent = 2, idleCloseMs = 60_000, timers } = {}) {
65
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1)
66
+ throw new Error("maxConcurrent must be a positive integer");
67
+ const lazy = createLazyBrowser({ launch }, { idleCloseMs, ...(timers ? { timers } : {}) });
68
+ let active = 0;
69
+ return {
70
+ async acquire(_required, { signal } = {}) {
71
+ signal?.throwIfAborted();
72
+ if (active >= maxConcurrent)
73
+ throw Object.assign(new Error("Render capacity is busy; retry shortly"), { code: "WEB_RENDER_BUSY" });
74
+ active += 1;
75
+ let released = false;
76
+ let acquired = false;
77
+ const release = () => { if (!released) {
78
+ released = true;
79
+ active -= 1;
80
+ if (acquired)
81
+ lazy.release();
82
+ } };
83
+ const acquisition = lazy.acquire();
84
+ // Cancellation frees render capacity immediately; a late successful launch still releases
85
+ // its lazy reference, without closing a browser another capture may already be using.
86
+ void acquisition.then(() => { acquired = true; if (released)
87
+ lazy.release(); }, () => { });
88
+ let onAbort;
89
+ try {
90
+ const browser = signal ? await Promise.race([
91
+ acquisition,
92
+ new Promise((_resolve, reject) => {
93
+ onAbort = () => reject(signal.reason);
94
+ signal.addEventListener("abort", onAbort, { once: true });
95
+ if (signal.aborted)
96
+ onAbort();
97
+ }),
98
+ ]) : await acquisition;
99
+ acquired = true;
100
+ signal?.throwIfAborted();
101
+ return { browser, release };
102
+ }
103
+ catch (error) {
104
+ release();
105
+ throw error;
106
+ }
107
+ finally {
108
+ if (onAbort)
109
+ signal?.removeEventListener("abort", onAbort);
110
+ }
111
+ },
112
+ close: () => lazy.close(),
113
+ };
114
+ }
115
+ //# sourceMappingURL=lazy-browser.js.map
@@ -8,8 +8,11 @@ export declare class PageWorkTimeout extends Error {
8
8
  export declare class PageWorkBudget {
9
9
  private readonly expiresAt;
10
10
  private readonly timeoutMs;
11
+ private readonly signal;
11
12
  constructor({ timeoutMs }: {
12
13
  timeoutMs: number;
14
+ }, { signal }?: {
15
+ signal?: AbortSignal;
13
16
  });
14
17
  remainingMs(): number;
15
18
  /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
@@ -2,13 +2,16 @@
2
2
  export class PageWorkTimeout extends Error {
3
3
  constructor({ timeoutMs }) {
4
4
  super(`page work timed out after ${timeoutMs}ms`);
5
+ this.name = "PageWorkTimeout";
5
6
  }
6
7
  }
7
8
  /** A timeout is a budget for the whole page, not a fresh allowance for each browser operation. */
8
9
  export class PageWorkBudget {
9
10
  expiresAt;
10
11
  timeoutMs;
11
- constructor({ timeoutMs }) {
12
+ signal;
13
+ constructor({ timeoutMs }, { signal } = {}) {
14
+ this.signal = signal;
12
15
  this.timeoutMs = timeoutMs;
13
16
  this.expiresAt = Date.now() + timeoutMs;
14
17
  }
@@ -16,13 +19,21 @@ export class PageWorkBudget {
16
19
  /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
17
20
  * @complexity O(1) time and space apart from the injected operation. */
18
21
  async run({ work }) {
22
+ this.signal?.throwIfAborted();
19
23
  const remaining = this.remainingMs();
20
24
  if (remaining <= 0)
21
25
  throw new PageWorkTimeout({ timeoutMs: this.timeoutMs });
22
26
  let timer;
27
+ let onAbort;
23
28
  try {
24
29
  return await Promise.race([
25
30
  work(),
31
+ ...(this.signal ? [new Promise((_resolve, reject) => {
32
+ onAbort = () => reject(this.signal.reason);
33
+ this.signal.addEventListener("abort", onAbort, { once: true });
34
+ if (this.signal.aborted)
35
+ onAbort();
36
+ })] : []),
26
37
  new Promise((_resolve, reject) => {
27
38
  timer = setTimeout(() => reject(new PageWorkTimeout({ timeoutMs: this.timeoutMs })), remaining);
28
39
  }),
@@ -30,6 +41,8 @@ export class PageWorkBudget {
30
41
  }
31
42
  finally {
32
43
  clearTimeout(timer);
44
+ if (onAbort)
45
+ this.signal?.removeEventListener("abort", onAbort);
33
46
  }
34
47
  }
35
48
  /** Always initiate resource release, but a stalled close must not extend an exhausted budget.
@@ -37,15 +50,15 @@ export class PageWorkBudget {
37
50
  * @complexity O(1) aside from resource release. */
38
51
  async release({ close }) {
39
52
  const closing = close();
40
- if (this.remainingMs() <= 0) {
53
+ if (this.remainingMs() <= 0 || this.signal?.aborted) {
41
54
  void closing.catch(() => { });
42
55
  return;
43
56
  }
44
57
  try {
45
- await this.run({ work: () => closing });
58
+ await new PageWorkBudget({ timeoutMs: this.remainingMs() }, this.signal ? { signal: this.signal } : {}).run({ work: () => closing });
46
59
  }
47
60
  catch (error) {
48
- if (!(error instanceof PageWorkTimeout))
61
+ if (!(error instanceof PageWorkTimeout) && !this.signal?.aborted)
49
62
  throw error;
50
63
  }
51
64
  }
@@ -1,131 +1,16 @@
1
- /**
2
- * @file The one and only module in this repository that touches a real headless browser.
3
- * Implements `SiteEvidenceBrowserPort` (`browser-port.ts`) on Playwright's Chromium.
4
- *
5
- * ---------------------------------------------------------------------------
6
- * Why the import is dynamic, and why the module's types are declared here
7
- * ---------------------------------------------------------------------------
8
- * The host may optionally install `playwright`; this package adds no browser dependency. The BROWSER
9
- * BINARY it drives needs a separate `playwright install chromium` step in the host deployment.
10
- * Installing the module alone does not supply that binary. So both halves can
11
- * legitimately be missing at runtime, independently:
12
- *
13
- * - the module itself, on a deployment that pruned it;
14
- * - the Chromium binary, on a deployment that installed the module but not the browser.
15
- *
16
- * Both are caught here and converted into `{ available: false, reason }`, never a thrown error and
17
- * never a boot failure. The tool then reports "no browser in this deployment" and the compliance
18
- * skill is required by its own output contract to downgrade every rendered-truth finding to
19
- * `cannot-determine`. That is the entire reason this adapter must not be a static import: a static
20
- * one would make an optional capability a hard boot dependency for every host install.
21
- *
22
- * {@link PlaywrightLike} declares, structurally, exactly the eight or so members this adapter uses.
23
- * That is deliberate rather than importing Playwright's own (very large) `.d.ts`: typechecking this
24
- * repository must not depend on a browser automation library's type surface being resolvable, and
25
- * naming the members used makes the actual coupling one short, reviewable block instead of an
26
- * open-ended import.
27
- *
28
- * ---------------------------------------------------------------------------
29
- * Privacy properties, enforced here rather than promised
30
- * ---------------------------------------------------------------------------
31
- * - **Ephemeral context.** `browser.newContext()` with no `storageState` and no user-data
32
- * directory. Cookies, storage, and cache exist only in memory and die with `close()`. Nothing is
33
- * written to disk by this module.
34
- * - **One context per page.** Each `observe()` call gets a fresh context, so a cookie set by page A
35
- * can never be reported as though page B set it — which would be an outright false citation in a
36
- * pre-consent cookie finding.
37
- * - **No non-GET request ever leaves the process.** Every request is intercepted; anything that is
38
- * not GET or HEAD is aborted and recorded as blocked. This is what makes "never submits forms" a
39
- * structural property instead of a policy: even if a page auto-submits, or a consent widget POSTs
40
- * preferences, the attempt is observed and the bytes do not go out.
41
- * - **Values are never read.** Cookie values, request bodies, and form-field values are not
42
- * extracted anywhere below, because `browser-port.ts`'s shapes have nowhere to put them.
43
- */
1
+ /** Evidence adapter over the shared render function. Optional-import, sandbox and privacy
2
+ * rationale moved with the browser opener to playwright-runtime.ts; context lifecycle is in
3
+ * render-page.ts. Keeping one opener avoids a second vendor/browser stack for public reads. */
44
4
  import type { SiteEvidenceBrowserAvailability } from "./browser-port.js";
45
- interface PwRoute {
46
- request(): PwRequest;
47
- abort(errorCode?: string): Promise<void>;
48
- continue(): Promise<void>;
49
- }
50
- interface PwRequest {
51
- url(): string;
52
- method(): string;
53
- resourceType(): string;
54
- }
55
- interface PwResponse {
56
- status(): number;
57
- url(): string;
58
- headers(): Record<string, string>;
59
- }
60
- interface PwCookie {
61
- name: string;
62
- value: string;
63
- domain: string;
64
- path: string;
65
- expires: number;
66
- httpOnly: boolean;
67
- secure: boolean;
68
- sameSite: string;
69
- }
70
- interface PwLocator {
71
- first(): PwLocator;
72
- count(): Promise<number>;
73
- click(options?: {
74
- timeout?: number;
75
- }): Promise<void>;
76
- }
77
- interface PwPage {
78
- goto(url: string, options?: {
79
- waitUntil?: string;
80
- timeout?: number;
81
- }): Promise<PwResponse | null>;
82
- /** Only the STRING form is used — see {@link buildPageStructureExpression} for why passing the
83
- * function reference directly is not safe here. */
84
- evaluate<T>(expression: string): Promise<T>;
85
- locator(selector: string): PwLocator;
86
- waitForTimeout(ms: number): Promise<void>;
87
- title(): Promise<string>;
88
- }
89
- interface PwContext {
90
- newPage(): Promise<PwPage>;
91
- route(pattern: string, handler: (route: PwRoute) => void | Promise<void>): Promise<void>;
92
- cookies(): Promise<PwCookie[]>;
93
- close(): Promise<void>;
94
- }
95
- interface PwBrowser {
96
- newContext(options?: Record<string, unknown>): Promise<PwContext>;
97
- close(): Promise<void>;
98
- }
99
- export interface PlaywrightLike {
100
- chromium: {
101
- launch(options?: {
102
- headless?: boolean;
103
- args?: readonly string[];
104
- }): Promise<PwBrowser>;
105
- };
106
- }
107
- /**
108
- * Opens a real Chromium and returns a `SiteEvidenceBrowserPort` over it, or explains why this
109
- * deployment cannot.
110
- *
111
- * @returns `{ available: true, browser }` on success; `{ available: false, reason }` when the
112
- * `playwright` module or its Chromium binary is not present. Never throws for either case — see
113
- * this file's header for why an absent browser must be a reportable state rather than an error.
114
- * @complexity One process launch. The caller is responsible for calling `close()`, which
115
- * `collectPageEvidence` does in a `finally`.
116
- */
117
- export interface PlaywrightAdapterOptions {
118
- readonly moduleLoader?: {
119
- load(required: {
120
- moduleName: string;
121
- }): Promise<PlaywrightLike>;
122
- };
123
- readonly launchOptions?: {
124
- headless?: boolean;
125
- args?: string[];
126
- };
127
- }
128
- /** Opens the optional browser capability; import and launch failures become availability results. */
129
- export declare function openPlaywrightSiteEvidenceBrowser(_required: Record<string, never>, options?: PlaywrightAdapterOptions): Promise<SiteEvidenceBrowserAvailability>;
130
- export {};
5
+ import { type PlaywrightAdapterOptions } from "./playwright-runtime.js";
6
+ export { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./playwright-runtime.js";
7
+ export type { PlaywrightLike, PlaywrightAdapterOptions } from "./playwright-runtime.js";
8
+ export * from "./render-page.js";
9
+ export { PageWorkTimeout } from "./page-work-budget.js";
10
+ export * from "./request-guard.js";
11
+ export * from "./lazy-browser.js";
12
+ /** Evidence facade over the same browser opener and render lifecycle used for public reading. */
13
+ export declare function openPlaywrightSiteEvidenceBrowser(required: Record<string, never>, options?: PlaywrightAdapterOptions): Promise<SiteEvidenceBrowserAvailability>;
14
+ export { renderPublicPage, createJsonCapture, publicPageExpression } from "./public-page.js";
15
+ export type { PublicPageInput, PublicPageCapture, CapturedJsonResponse } from "./public-page.js";
131
16
  //# sourceMappingURL=playwright-browser.d.ts.map
@@ -1,45 +1,31 @@
1
1
  import { collectPageStructure } from "./page-structure-script.js";
2
+ import { renderPage, OffOriginNavigationError } from "./render-page.js";
3
+ import { openPlaywrightRenderBrowser } from "./playwright-runtime.js";
4
+ export { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./playwright-runtime.js";
5
+ export * from "./render-page.js";
6
+ export { PageWorkTimeout } from "./page-work-budget.js";
7
+ export * from "./request-guard.js";
8
+ export * from "./lazy-browser.js";
2
9
  import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
3
- /** Methods allowed out of the browser. Everything else is aborted — see this file's header. */
4
- const SAFE_METHODS = new Set(["GET", "HEAD"]);
5
10
  /** How long to wait for the page to settle after the consent click before re-reading state. Short
6
11
  * on purpose: this is a debounce for the widget's own DOM/network reaction, not a crawl budget,
7
12
  * and it is charged against the same per-page timeout as everything else. */
8
13
  const CONSENT_SETTLE_MS = 1_500;
9
- /** Opens the optional browser capability; import and launch failures become availability results. */
10
- // A successful launch transfers process ownership to the caller; close the browser in a finally
11
- // block so an unreachable or unstable page cannot leak the browser process.
12
- export async function openPlaywrightSiteEvidenceBrowser(_required, options = {}) {
13
- let playwright;
14
- try {
15
- const moduleName = "playwright";
16
- playwright = options.moduleLoader
17
- ? await options.moduleLoader.load({ moduleName })
18
- : (await import(moduleName));
19
- }
20
- catch (error) {
21
- return {
22
- available: false,
23
- reason: "the 'playwright' package is not installed in this deployment, so rendered-page behaviour " +
24
- `cannot be observed here (${messageOf(error)})`,
25
- };
26
- }
27
- let browser;
28
- try {
29
- browser = await playwright.chromium.launch({ headless: true, ...options.launchOptions });
30
- }
31
- catch (error) {
32
- return {
33
- available: false,
34
- reason: "Chromium could not be launched in this deployment — the 'playwright' package is present but its " +
35
- `browser binary is not installed (run 'npx playwright install --with-deps chromium'). Underlying error: ${messageOf(error)}`,
36
- };
37
- }
38
- return { available: true, browser: new PlaywrightSiteEvidenceBrowser({ browser }) };
14
+ // ---------------------------------------------------------------------------
15
+ // The structural slice of Playwright this adapter uses. See the file header.
16
+ // ---------------------------------------------------------------------------
17
+ /** Evidence facade over the same browser opener and render lifecycle used for public reading. */
18
+ export async function openPlaywrightSiteEvidenceBrowser(required, options = {}) {
19
+ const opened = await openPlaywrightRenderBrowser(required, options);
20
+ return opened.available ? { available: true, browser: new PlaywrightSiteEvidenceBrowser({ browser: opened.browser }, options) } : opened;
39
21
  }
40
22
  class PlaywrightSiteEvidenceBrowser {
41
23
  browser;
42
- constructor({ browser }) { this.browser = browser; }
24
+ routerFactory;
25
+ constructor({ browser }, options = {}) {
26
+ this.browser = browser;
27
+ this.routerFactory = options.routerFactory;
28
+ }
43
29
  /**
44
30
  * Loads one page in a fresh ephemeral context and returns what was observed.
45
31
  *
@@ -51,110 +37,64 @@ class PlaywrightSiteEvidenceBrowser {
51
37
  */
52
38
  async observe(required, options = {}) {
53
39
  const request = { ...required, ...options };
54
- const budget = new PageWorkBudget({ timeoutMs: request.timeoutMs });
55
- // No `storageState`, no `recordVideo`, no `recordHar`, no user-data dir: nothing this context
56
- // observes can outlive `close()` below or reach the filesystem. See this file's header.
57
- let context;
58
- try {
59
- context = await budget.run({ work: async () => {
60
- const created = await this.browser.newContext({ ignoreHTTPSErrors: false });
61
- // A context can finish opening after our race timed out. It still belongs to this call.
62
- if (budget.remainingMs() <= 0) {
63
- void created.close().catch(() => { });
64
- throw new PageWorkTimeout({ timeoutMs: request.timeoutMs });
65
- }
66
- return created;
67
- } });
68
- }
69
- catch (error) {
70
- return { ok: false, reason: `page capture failed before load: ${messageOf(error)}` };
71
- }
40
+ const abort = new AbortController();
41
+ const router = this.routerFactory?.({ originBaseUrl: request.originBaseUrl, signal: abort.signal });
72
42
  const requests = [];
73
43
  const notes = [];
74
44
  let phase = "before";
75
45
  try {
76
- await budget.run({ work: () => context.route("**/*", async (route) => {
46
+ return await renderPage({
47
+ browser: this.browser, url: request.url,
48
+ consume: async ({ page, context, response, finalUrl, budget }) => {
49
+ if (!response)
50
+ return { ok: false, reason: "the browser produced no response for this navigation (no HTTP exchange to observe)" };
51
+ const structureLimits = {
52
+ maxTextExcerptChars: request.maxTextExcerptChars,
53
+ maxNodesPerCategory: request.maxAccessibilityNodesPerCategory,
54
+ maxContrastSamples: request.maxContrastSamples,
55
+ collectAccessibility: request.collectAccessibility,
56
+ };
57
+ // A page can navigate, close or crash after goto (Execution context was destroyed).
58
+ // Such gaps remain evidence, never an exception that ends the whole collection run.
59
+ const structure = await budget.run({ work: async () => await page.evaluate(buildPageStructureExpression(structureLimits)) });
60
+ if (request.consentAcceptSelector !== undefined) {
61
+ await this.performConsentClick(page, request, notes, () => { phase = "after"; }, budget);
62
+ }
63
+ if (!context.cookies)
64
+ throw new Error("Browser cannot observe cookies");
65
+ const cookies = await budget.run({ work: () => context.cookies() });
66
+ return { ok: true, observation: buildObservation({
67
+ request, finalUrl, httpStatus: response.status(), headers: response.headers?.() ?? {},
68
+ title: structure.title, structure, cookies, requests, notes, consentPhase: phase,
69
+ }) };
70
+ },
71
+ }, {
72
+ ...(router ? { router } : {}), signal: abort.signal,
73
+ timeoutMs: request.timeoutMs, originBaseUrl: request.originBaseUrl,
74
+ // Consent evidence must stay pre-consent until the operator's explicit selector is clicked.
75
+ dismissCookieBanners: false, loadWaitMs: 5_000,
76
+ onRequest: ({ route, blocked }) => {
77
77
  const pending = route.request();
78
- const method = pending.method().toUpperCase();
79
- const blocked = !SAFE_METHODS.has(method);
78
+ const requestIndex = requests.length;
80
79
  recordRequest(requests, request, {
81
- method,
82
- url: pending.url(),
83
- resourceType: pending.resourceType(),
84
- phase,
85
- ...(blocked
86
- ? {
87
- blockedReason: "aborted: this tool never sends a non-GET request, so no form, consent preference, or " +
88
- "analytics beacon it observes is ever actually submitted. The attempt itself is the evidence.",
89
- }
90
- : {}),
80
+ method: pending.method().toUpperCase(), url: pending.url(), resourceType: pending.resourceType(), phase,
81
+ ...(blocked ? { blockedReason: "aborted: this tool never sends a non-GET request, so no form, consent preference, or " +
82
+ "analytics beacon it observes is ever actually submitted. Off-origin navigation is also refused." } : {}),
91
83
  });
92
- if (blocked) {
93
- await route.abort("blockedbyclient");
94
- return;
95
- }
96
- await route.continue();
97
- }) });
98
- const page = await budget.run({ work: () => context.newPage() });
99
- let response;
100
- try {
101
- response = await budget.run({ work: () => page.goto(request.url, { waitUntil: "load", timeout: budget.remainingMs() }) });
102
- }
103
- catch (error) {
104
- return { ok: false, reason: `navigation failed or timed out after ${request.timeoutMs}ms: ${messageOf(error)}` };
105
- }
106
- if (response === null) {
107
- return { ok: false, reason: "the browser produced no response for this navigation (no HTTP exchange to observe)" };
108
- }
109
- const finalUrl = response.url();
110
- const structureLimits = {
111
- maxTextExcerptChars: request.maxTextExcerptChars,
112
- maxNodesPerCategory: request.maxAccessibilityNodesPerCategory,
113
- maxContrastSamples: request.maxContrastSamples,
114
- collectAccessibility: request.collectAccessibility,
115
- };
116
- let structure;
117
- let cookies;
118
- try {
119
- structure = await budget.run({ work: () => page.evaluate(buildPageStructureExpression(structureLimits)) });
120
- if (request.consentAcceptSelector !== undefined) {
121
- await this.performConsentClick(page, request, notes, () => {
122
- phase = "after";
123
- }, budget);
124
- }
125
- cookies = await budget.run({ work: () => context.cookies() });
126
- }
127
- catch (error) {
128
- // The page can navigate away, close, or crash between `goto` resolving above and either of
129
- // these reads — most commonly surfacing as Playwright's own "Execution context was
130
- // destroyed". That is exactly the class of failure this port's contract exists to report as
131
- // `{ ok: false, reason }` rather than let escape as a thrown error: one unreachable/unstable
132
- // page must not end the whole `site_collect_page_evidence` run (`collect-page-evidence.ts`'s
133
- // own per-page catch is the second, defense-in-depth layer for a port that does not honor
134
- // this).
135
- return { ok: false, reason: `page capture failed after load: ${messageOf(error)}` };
136
- }
137
- return {
138
- ok: true,
139
- observation: buildObservation({
140
- request,
141
- finalUrl,
142
- httpStatus: response.status(),
143
- headers: response.headers(),
144
- title: structure.title,
145
- structure,
146
- cookies,
147
- requests,
148
- notes,
149
- consentPhase: phase,
150
- }),
151
- };
84
+ // Preserve the phase of the attempt even if a DNS/transport refusal finishes after consent.
85
+ return ({ reason }) => {
86
+ const observed = requests[requestIndex];
87
+ if (observed)
88
+ requests[requestIndex] = { ...observed, blockedReason: reason };
89
+ };
90
+ },
91
+ });
152
92
  }
153
93
  catch (error) {
154
- return { ok: false, reason: `page capture failed: ${messageOf(error)}` };
94
+ return { ok: false, reason: `page capture failed after load or navigation: ${messageOf(error)}`, ...(error instanceof OffOriginNavigationError ? { offOriginUrl: error.origin } : {}) };
155
95
  }
156
96
  finally {
157
- await budget.release({ close: () => context.close() });
97
+ abort.abort();
158
98
  }
159
99
  }
160
100
  async close(_required) {
@@ -346,4 +286,5 @@ function normalizeUrlForComparison(url) {
346
286
  function messageOf(error) {
347
287
  return error instanceof Error ? error.message : String(error);
348
288
  }
289
+ export { renderPublicPage, createJsonCapture, publicPageExpression } from "./public-page.js";
349
290
  //# sourceMappingURL=playwright-browser.js.map