@jini-ai/diagnostics 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,14 @@ function matchesCaptureUrl({ url, pattern }, _options = {}) {
23
23
  }
24
24
  return offset <= end;
25
25
  }
26
+ /** Only script-issued data answers are captured or counted; documents, images and scripts are not. */
27
+ function isDataResource(resourceType) {
28
+ return resourceType === "xhr" || resourceType === "fetch";
29
+ }
30
+ function isJsonResponse(headers) {
31
+ const contentType = Object.entries(headers).find(([key]) => key.toLowerCase() === "content-type")?.[1]?.split(";")[0]?.trim() ?? "";
32
+ return /^(?:application|text)\/(?:json|[\w.+-]+\+json)$/i.test(contentType);
33
+ }
26
34
  /** Bounded synchronous collector over responses already read by the pinned request router.
27
35
  * No response.body() listener: it would read whole untrusted bodies before applying the cap.
28
36
  * Filters affect output only: unmatched data still reaches the page so hydration can complete.
@@ -35,44 +43,42 @@ export function createJsonCapture(_required, { maxResponses = 20, perBodyChars =
35
43
  const patterns = typeof captureDataMatch === "string" ? [captureDataMatch] : captureDataMatch;
36
44
  let used = 0;
37
45
  let truncated = false;
46
+ function recordUnmatched({ url, capturedUrl, resource }) {
47
+ if (dataUnmatched.length >= maxResponses || used + capturedUrl.length > totalChars) {
48
+ truncated = true;
49
+ return;
50
+ }
51
+ // Do not decode or charge omitted bodies: noisy providers must not consume the useful body window.
52
+ dataUnmatched.push({ url: capturedUrl, status: resource.status, size: resource.body.length });
53
+ used += capturedUrl.length;
54
+ truncated ||= resource.truncated || url.length > 2048;
55
+ }
56
+ function recordMatched({ url, capturedUrl, resource }) {
57
+ if (data.length >= maxResponses || used + capturedUrl.length >= totalChars) {
58
+ truncated = true;
59
+ return;
60
+ }
61
+ const limit = Math.min(perBodyChars, totalChars - used - capturedUrl.length);
62
+ // At most four UTF-8 bytes per output character; never decode a multi-megabyte body here.
63
+ const decoded = resource.body.subarray(0, limit * 4).toString("utf8");
64
+ const body = decoded.slice(0, limit);
65
+ const cut = resource.truncated || resource.body.length > limit * 4 || decoded.length > limit || url.length > 2048;
66
+ used += capturedUrl.length + body.length;
67
+ data.push({ url: capturedUrl, status: resource.status, body, truncated: cut });
68
+ truncated ||= cut;
69
+ }
38
70
  return {
39
71
  record({ url, resourceType, resource }, _options = {}) {
40
- if (resourceType !== "xhr" && resourceType !== "fetch")
41
- return;
42
- const contentType = Object.entries(resource.headers).find(([key]) => key.toLowerCase() === "content-type")?.[1]?.split(";")[0]?.trim() ?? "";
43
- if (!/^(?:application|text)\/(?:json|[\w.+-]+\+json)$/i.test(contentType))
72
+ if (!isDataResource(resourceType) || !isJsonResponse(resource.headers))
44
73
  return;
45
74
  const capturedUrl = url.slice(0, 2048);
46
- if (patterns && !patterns.some(pattern => matchesCaptureUrl({ url, pattern }))) {
47
- if (dataUnmatched.length >= maxResponses || used + capturedUrl.length > totalChars) {
48
- truncated = true;
49
- return;
50
- }
51
- // Do not decode or charge omitted bodies: noisy providers must not consume the useful body window.
52
- dataUnmatched.push({ url: capturedUrl, status: resource.status, size: resource.body.length });
53
- used += capturedUrl.length;
54
- truncated ||= resource.truncated || url.length > 2048;
55
- return;
56
- }
57
- if (data.length >= maxResponses || used >= totalChars) {
58
- truncated = true;
59
- return;
60
- }
61
- if (used + capturedUrl.length >= totalChars) {
62
- truncated = true;
63
- return;
64
- }
65
- const limit = Math.min(perBodyChars, totalChars - used - capturedUrl.length);
66
- // At most four UTF-8 bytes per output character; never decode a multi-megabyte body here.
67
- const decoded = resource.body.subarray(0, limit * 4).toString("utf8");
68
- const body = decoded.slice(0, limit);
69
- const cut = resource.truncated || resource.body.length > limit * 4 || decoded.length > limit || url.length > 2048;
70
- used += capturedUrl.length + body.length;
71
- data.push({ url: capturedUrl, status: resource.status, body, truncated: cut });
72
- truncated ||= cut;
75
+ if (patterns && !patterns.some(pattern => matchesCaptureUrl({ url, pattern })))
76
+ recordUnmatched({ url, capturedUrl, resource });
77
+ else
78
+ recordMatched({ url, capturedUrl, resource });
73
79
  },
74
80
  markTruncated({ resourceType }, _options = {}) {
75
- if (resourceType === "xhr" || resourceType === "fetch")
81
+ if (isDataResource(resourceType))
76
82
  truncated = true;
77
83
  },
78
84
  result: (_required = {}, _options = {}) => ({ data: [...data], dataTruncated: truncated, ...(patterns ? { dataUnmatched: [...dataUnmatched] } : {}) }),
@@ -80,10 +86,11 @@ export function createJsonCapture(_required, { maxResponses = 20, perBodyChars =
80
86
  }
81
87
  /** Self-contained browser script: DOM and computed styles are native browser capabilities.
82
88
  * Ships as a string to avoid esbuild's module-scoped __name helper leaking into evaluation.
89
+ * HTML has a fixed transport cap so a large style head cannot consume the readable-text budget.
83
90
  * Scans at most 5000 nodes, caps images and every emitted string before crossing the browser port. */
84
91
  export function publicPageExpression({ maxChars, textMode = "full" }, _options = {}) {
85
92
  return `(() => {
86
- const cap = ${maxChars}; const htmlCap = Math.max(4096, cap * 4);
93
+ const cap = ${maxChars}; const htmlCap = 1_000_000;
87
94
  const mode = ${JSON.stringify(textMode)}; const textCap = mode === 'summary' ? Math.min(1000, cap) : cap;
88
95
  const images = []; const seen = new Set(); let imagesTruncated = false;
89
96
  const add = (raw, alt) => {
@@ -121,47 +128,66 @@ export function publicPageExpression({ maxChars, textMode = "full" }, _options =
121
128
  truncated: scanTruncated || html.length > htmlCap || text.length > textCap};
122
129
  })()`;
123
130
  }
131
+ function browserUnavailable(options = {}) {
132
+ return Object.assign(new Error("Headless browser is unavailable in this deployment", options), { code: "WEB_RENDER_UNAVAILABLE" });
133
+ }
134
+ /** A lease that arrives after cancellation or the deadline is handed straight back. */
135
+ async function leaseFromPool({ browserPool, signal, budget, timeoutMs }) {
136
+ let acquired;
137
+ try {
138
+ acquired = await browserPool.acquire({}, { signal });
139
+ }
140
+ catch (error) {
141
+ if (signal.aborted || error?.code === "WEB_RENDER_BUSY")
142
+ throw error;
143
+ throw browserUnavailable({ cause: error });
144
+ }
145
+ if (signal.aborted || budget.remainingMs() <= 0) {
146
+ acquired.release();
147
+ signal.throwIfAborted();
148
+ throw new PageWorkTimeout({ timeoutMs });
149
+ }
150
+ return { browser: acquired.browser, lease: acquired };
151
+ }
152
+ /** An owned launch that completes after cancellation or the deadline is closed, never leaked. */
153
+ async function launchOwnBrowser({ signal, budget, timeoutMs }, launch) {
154
+ const result = await openPlaywrightRenderBrowser({}, { ...launch, launchOptions: PUBLIC_RENDER_LAUNCH_OPTIONS });
155
+ if (!result.available)
156
+ throw browserUnavailable();
157
+ if (budget.remainingMs() <= 0 || signal.aborted) {
158
+ void result.browser.close().catch(() => { });
159
+ signal.throwIfAborted();
160
+ throw new PageWorkTimeout({ timeoutMs });
161
+ }
162
+ return { browser: result.browser };
163
+ }
164
+ /** Evaluates the page script and takes the optional bounded screenshot inside the page budget. */
165
+ async function capturePage({ session: { page, finalUrl, response, budget }, input }) {
166
+ const snapshot = await budget.run({ work: async () => await page.evaluate(publicPageExpression({ maxChars: input.maxChars, ...(input.textMode ? { textMode: input.textMode } : {}) })) });
167
+ const jpeg = input.screenshot ? await takeScreenshot({ page, budget }) : undefined;
168
+ const screenshot = jpeg && jpeg.length <= 2 * 1024 * 1024 ? { mimeType: "image/jpeg", data: jpeg.toString("base64") } : undefined;
169
+ const truncated = snapshot.truncated || (jpeg !== undefined && !screenshot) || finalUrl.length > 2048;
170
+ return { ...snapshot, truncated, finalUrl: finalUrl.slice(0, 2048), status: response?.status() ?? 0, ...(screenshot ? { screenshot } : {}) };
171
+ }
172
+ async function takeScreenshot({ page, budget }) {
173
+ if (!page.screenshot)
174
+ throw new Error("Public render cannot take the requested screenshot: this browser port has no screenshot()");
175
+ return budget.run({ work: () => page.screenshot({ type: "jpeg", quality: 72, fullPage: false, timeout: budget.remainingMs(), animations: "disabled" }) });
176
+ }
124
177
  /** Anonymous public render using the shared lifecycle and the existing pinned HTTP transport.
125
178
  * Import/launch, navigation, selector, extraction and screenshot all share one hard deadline.
126
179
  * Owned processes close, shared leases release; late launches are handled without owner storage.
127
180
  * @throws Error for unavailable Chromium, refused navigation or deadline exhaustion.
128
181
  * @complexity Bounded requests/bytes plus at most 5000 DOM nodes and one viewport screenshot. */
129
- export async function renderPublicPage({ input, httpClient }, { signal, timeoutMs = 30_000, moduleLoader, browserPool } = {}) {
130
- timeoutMs = Math.min(timeoutMs, 30_000);
182
+ export async function renderPublicPage({ input, httpClient }, { signal, timeoutMs: requestedMs = 30_000, browserPool, ...launch } = {}) {
183
+ const timeoutMs = Math.min(requestedMs, 30_000);
131
184
  const abort = new AbortController();
132
185
  const deadline = AbortSignal.timeout(timeoutMs);
133
186
  const combined = AbortSignal.any([abort.signal, deadline, ...(signal ? [signal] : [])]);
134
187
  const budget = new PageWorkBudget({ timeoutMs }, { signal: combined });
135
- let lease;
136
- const opened = await budget.run({ work: async () => {
137
- if (browserPool) {
138
- let acquired;
139
- try {
140
- acquired = await browserPool.acquire({}, { signal: combined });
141
- }
142
- catch (error) {
143
- if (combined.aborted || error?.code === "WEB_RENDER_BUSY")
144
- throw error;
145
- throw Object.assign(new Error("Headless browser is unavailable in this deployment"), { code: "WEB_RENDER_UNAVAILABLE" });
146
- }
147
- if (combined.aborted || budget.remainingMs() <= 0) {
148
- acquired.release();
149
- combined.throwIfAborted();
150
- throw new PageWorkTimeout({ timeoutMs });
151
- }
152
- lease = acquired;
153
- return { available: true, browser: acquired.browser };
154
- }
155
- const result = await openPlaywrightRenderBrowser({}, { ...(moduleLoader ? { moduleLoader } : {}), launchOptions: PUBLIC_RENDER_LAUNCH_OPTIONS });
156
- if (result.available && (budget.remainingMs() <= 0 || combined.aborted)) {
157
- void result.browser.close().catch(() => { });
158
- combined.throwIfAborted();
159
- throw new PageWorkTimeout({ timeoutMs });
160
- }
161
- return result;
162
- } });
163
- if (!opened.available)
164
- throw Object.assign(new Error("Headless browser is unavailable in this deployment"), { code: "WEB_RENDER_UNAVAILABLE" });
188
+ const opened = await budget.run({ work: () => browserPool
189
+ ? leaseFromPool({ browserPool, signal: combined, budget, timeoutMs })
190
+ : launchOwnBrowser({ signal: combined, budget, timeoutMs }, launch) });
165
191
  // Small/batched reads keep their JSON window small too; a batch must not multiply 60k by default.
166
192
  const json = createJsonCapture({}, { perBodyChars: Math.min(8000, input.maxChars), totalChars: Math.min(60_000, input.maxChars),
167
193
  ...(input.captureDataMatch === undefined ? {} : { captureDataMatch: input.captureDataMatch }),
@@ -172,26 +198,16 @@ export async function renderPublicPage({ input, httpClient }, { signal, timeoutM
172
198
  allowDataRequests: true,
173
199
  ...(input.captureData === false ? {} : { onResponse: json.record }),
174
200
  onBlocked: ({ resourceType, reason }) => {
175
- if (resourceType !== "xhr" && resourceType !== "fetch")
201
+ if (!isDataResource(resourceType))
176
202
  return;
177
203
  blockedDataRequests[reason] = (blockedDataRequests[reason] ?? 0) + 1;
178
204
  json.markTruncated({ resourceType });
179
205
  },
180
206
  });
181
207
  try {
182
- return await renderPage({ browser: opened.browser, url: input.url, consume: async ({ page, finalUrl, response, budget: pageBudget }) => {
183
- const snapshot = await pageBudget.run({ work: async () => await page.evaluate(publicPageExpression({ maxChars: input.maxChars, ...(input.textMode ? { textMode: input.textMode } : {}) })) });
184
- let screenshot;
185
- if (input.screenshot) {
186
- if (!page.screenshot)
187
- throw new Error("Browser cannot take screenshots");
188
- const jpeg = await pageBudget.run({ work: () => page.screenshot({ type: "jpeg", quality: 72, fullPage: false, timeout: pageBudget.remainingMs(), animations: "disabled" }) });
189
- if (jpeg.length <= 2 * 1024 * 1024)
190
- screenshot = { mimeType: "image/jpeg", data: jpeg.toString("base64") };
191
- else
192
- snapshot.truncated = true;
193
- }
194
- return { ...snapshot, truncated: snapshot.truncated || finalUrl.length > 2048, finalUrl: finalUrl.slice(0, 2048), status: response?.status() ?? 0, ...json.result(), blockedDataRequests: { ...blockedDataRequests }, ...(screenshot ? { screenshot } : {}) };
208
+ return await renderPage({ browser: opened.browser, url: input.url, consume: async (session) => {
209
+ const { screenshot, ...captured } = await capturePage({ session, input });
210
+ return { ...captured, ...json.result(), blockedDataRequests: { ...blockedDataRequests }, ...(screenshot ? { screenshot } : {}) };
195
211
  } }, {
196
212
  originPolicy: "public", router, timeoutMs: budget.remainingMs(), signal: combined,
197
213
  ...(input.waitFor === undefined ? {} : { waitFor: input.waitFor }), dismissCookieBanners: input.dismissCookieBanners !== false,
@@ -200,8 +216,8 @@ export async function renderPublicPage({ input, httpClient }, { signal, timeoutM
200
216
  }
201
217
  finally {
202
218
  abort.abort();
203
- if (lease)
204
- lease.release();
219
+ if (opened.lease)
220
+ opened.lease.release();
205
221
  else
206
222
  await budget.release({ close: () => opened.browser.close().catch(() => { }) });
207
223
  }
@@ -10,8 +10,9 @@ export class RenderRequestRefused extends Error {
10
10
  export class OffOriginNavigationError extends Error {
11
11
  origin;
12
12
  constructor({ url }) {
13
- super("Off-origin navigation refused");
14
- this.origin = new URL(url).origin;
13
+ const origin = new URL(url).origin;
14
+ super(`Off-origin navigation refused: ${origin} is outside the rendered site's origin`);
15
+ this.origin = origin;
15
16
  }
16
17
  }
17
18
  /** Narrow known consent controls: never click a generic page-wide 'close' or 'accept' button. */
@@ -29,22 +30,28 @@ export async function dismissCookieBanners({ page, budget }, _options = {}) {
29
30
  if (!page.locator)
30
31
  return false;
31
32
  for (const selector of COOKIE_DISMISS_SELECTORS) {
32
- try {
33
- const locator = page.locator(selector).first();
34
- if (await budget.run({ work: () => locator.count() }) === 0)
35
- continue;
36
- if (locator.isVisible && !await budget.run({ work: () => locator.isVisible() }))
37
- continue;
38
- await budget.run({ work: () => locator.click({ timeout: Math.min(500, budget.remainingMs()) }) });
33
+ if (await clickIfShown({ page, selector, budget }))
39
34
  return true;
40
- }
41
- catch (error) {
42
- if (error instanceof PageWorkTimeout)
43
- throw error;
44
- }
45
35
  }
46
36
  return false;
47
37
  }
38
+ /** One known control: missing, hidden or failing lookups move on; only the page budget ends the search. */
39
+ async function clickIfShown({ page, selector, budget }) {
40
+ try {
41
+ const locator = page.locator(selector).first();
42
+ if (await budget.run({ work: () => locator.count() }) === 0)
43
+ return false;
44
+ if (locator.isVisible && !await budget.run({ work: () => locator.isVisible() }))
45
+ return false;
46
+ await budget.run({ work: () => locator.click({ timeout: Math.min(500, budget.remainingMs()) }) });
47
+ return true;
48
+ }
49
+ catch (error) {
50
+ if (error instanceof PageWorkTimeout)
51
+ throw error;
52
+ return false;
53
+ }
54
+ }
48
55
  /** Syntax boundary; address/DNS decisions belong exclusively to the pinned request router. */
49
56
  function assertHttpUrl({ url }, _options = {}) {
50
57
  const parsed = new URL(url);
@@ -52,6 +59,135 @@ function assertHttpUrl({ url }, _options = {}) {
52
59
  throw new Error("Rendering requires an anonymous http(s) URL");
53
60
  }
54
61
  }
62
+ function isOffOrigin({ url, originPolicy, originBaseUrl }) {
63
+ return originPolicy === "same-origin" && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: url });
64
+ }
65
+ /** Every explicit target and the final URL pass the same syntax and origin boundary. */
66
+ function assertNavigable(required) {
67
+ assertHttpUrl(required);
68
+ if (isOffOrigin(required))
69
+ throw new OffOriginNavigationError(required);
70
+ }
71
+ /** Only viewport/device settings cross into the fresh context. */
72
+ const CONTEXT_OPTION_KEYS = ["viewport", "deviceScaleFactor", "isMobile", "hasTouch", "javaScriptEnabled"];
73
+ async function openContext({ browser, budget, signal, timeoutMs }, { contextOptions = {} }) {
74
+ return budget.run({ work: async () => {
75
+ const allowed = Object.fromEntries(CONTEXT_OPTION_KEYS.filter(key => contextOptions[key] !== undefined).map(key => [key, contextOptions[key]]));
76
+ // No storageState, recordVideo, recordHar or user-data dir: observed state never reaches disk.
77
+ const opened = await browser.newContext({ ...allowed, ignoreHTTPSErrors: false, serviceWorkers: "block", acceptDownloads: false });
78
+ // A context that opens after cancellation/deadline still belongs to this call.
79
+ if (budget.remainingMs() <= 0 || signal.aborted) {
80
+ void opened.close().catch(() => { });
81
+ signal.throwIfAborted();
82
+ throw new PageWorkTimeout({ timeoutMs });
83
+ }
84
+ return opened;
85
+ } });
86
+ }
87
+ /** Routes every context request; the returned reader names the origin of a refused main-frame navigation. */
88
+ async function guardRequests({ context, budget, originPolicy, originBaseUrl }, { router, onRequest }) {
89
+ let refusedOrigin;
90
+ await budget.run({ work: async () => { await context.routeWebSocket?.(/.*/, socket => socket.close().catch(() => { })); } });
91
+ await budget.run({ work: () => context.route("**/*", async (route) => {
92
+ const pending = route.request();
93
+ const offOrigin = isMainFrameNavigation({ request: pending }) && isOffOrigin({ url: pending.url(), originPolicy, originBaseUrl });
94
+ if (offOrigin)
95
+ refusedOrigin = new URL(pending.url()).origin;
96
+ // Public data methods belong to the router; evidence always refuses writes first.
97
+ // (Public mode always has a router: renderPage refuses public rendering without one.)
98
+ const blocked = offOrigin || (originPolicy !== "public" && !["GET", "HEAD"].includes(pending.method().toUpperCase()));
99
+ const markBlocked = onRequest?.({ route, blocked });
100
+ if (blocked)
101
+ return route.abort("blockedbyclient").catch(() => { });
102
+ if (router)
103
+ return routeThroughRouter({ router, route }, { markBlocked });
104
+ // Trusted own-origin evidence retains browser cookies, but never posts preferences or forms.
105
+ if (!route.continue)
106
+ throw new Error("Own-origin browser route cannot continue: the route port has no continue()");
107
+ await route.continue();
108
+ }) });
109
+ return () => refusedOrigin;
110
+ }
111
+ function routeThroughRouter({ router, route }, { markBlocked }) {
112
+ const pending = route.request();
113
+ return router.handle({
114
+ request: () => pending, fulfill: options => route.fulfill(options),
115
+ abort: async (code) => {
116
+ // Redirect aborts are navigation control, not a refused network observation.
117
+ if (code !== "aborted" && typeof markBlocked === "function")
118
+ markBlocked({ reason: "aborted by the guarded browser request router (unsafe target, unsupported request or resource cap)" });
119
+ await route.abort(code);
120
+ },
121
+ });
122
+ }
123
+ /** Explicit gotos only: a router-recorded main-frame redirect is vetted and navigated as a new hop. */
124
+ async function navigate({ page, budget, url, refusedOrigin, ...policy }, options) {
125
+ for (let hop = 0, target = url;; hop += 1) {
126
+ assertNavigable({ url: target, ...policy });
127
+ try {
128
+ return { target, response: await budget.run({ work: () => page.goto(target, { waitUntil: "domcontentloaded", timeout: budget.remainingMs() }) }) };
129
+ }
130
+ catch (error) {
131
+ target = nextHopAfterFailedGoto({ error, hop, target, refusedOrigin: refusedOrigin() }, options);
132
+ }
133
+ }
134
+ }
135
+ /** A failed goto is a refused origin, a recorded redirect to follow, a guard refusal, or the browser's own error. */
136
+ function nextHopAfterFailedGoto({ error, hop, target, refusedOrigin }, { router }) {
137
+ if (refusedOrigin)
138
+ throw new OffOriginNavigationError({ url: refusedOrigin });
139
+ const next = router?.takeNavigationRedirect();
140
+ if (next !== undefined && hop < MAX_REDIRECT_HOPS)
141
+ return next;
142
+ if (router?.report().navigationRefused)
143
+ throw new RenderRequestRefused({});
144
+ if (next !== undefined) {
145
+ throw new Error(`Rendering stopped: ${new URL(target).origin} kept redirecting past the ${MAX_REDIRECT_HOPS}-hop limit`, { cause: error });
146
+ }
147
+ throw error;
148
+ }
149
+ /** Cookie dismissal, the selector/settle strategy and the best-effort load wait, all within the page budget. */
150
+ async function settlePage({ page, budget, signal }, options) {
151
+ const { waitFor = 1.2, dismissCookieBanners: dismiss = false } = options;
152
+ const dismissed = dismiss && await dismissCookieBanners({ page, budget });
153
+ if (typeof waitFor === "string") {
154
+ if (!page.waitForSelector)
155
+ throw new Error(`Rendering cannot wait for selector "${waitFor}": this browser port has no waitForSelector`);
156
+ await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
157
+ }
158
+ else if (waitFor > 0) {
159
+ await budget.run({ work: () => page.waitForTimeout(waitFor * 1000) });
160
+ }
161
+ await waitForLoad({ page, budget, signal }, options);
162
+ // Hydrated consent widgets can arrive during the settle/selector wait.
163
+ if (dismiss && !dismissed && await dismissCookieBanners({ page, budget })) {
164
+ await budget.run({ work: () => page.waitForTimeout(200) });
165
+ }
166
+ }
167
+ async function waitForLoad({ page, budget, signal }, { loadWaitMs }) {
168
+ if (!loadWaitMs || !page.waitForLoadState)
169
+ return;
170
+ try {
171
+ await budget.run({ work: () => page.waitForLoadState("load", { timeout: Math.min(loadWaitMs, budget.remainingMs()) }) });
172
+ }
173
+ catch (error) {
174
+ if (error instanceof PageWorkTimeout || signal.aborted)
175
+ throw error;
176
+ // A polling or slow resource must not prevent bounded best-effort evidence/capture.
177
+ }
178
+ }
179
+ /** Guard, navigate and settle the page; the session's final URL passes the same origin boundary. */
180
+ async function openSession({ context, budget, signal, url }, options) {
181
+ const policy = { originPolicy: options.originPolicy ?? "same-origin", originBaseUrl: options.originBaseUrl ?? url };
182
+ const refusedOrigin = await guardRequests({ context, budget, ...policy }, options);
183
+ const page = await budget.run({ work: () => context.newPage() });
184
+ const { target, response } = await navigate({ page, budget, url, refusedOrigin, ...policy }, options);
185
+ await settlePage({ page, budget, signal }, options);
186
+ signal.throwIfAborted();
187
+ const finalUrl = page.url?.() ?? response?.url?.() ?? target;
188
+ assertNavigable({ url: finalUrl, ...policy });
189
+ return { page, context, response, finalUrl, budget };
190
+ }
55
191
  /** Open, guard, wait and consume ONE ephemeral page, always releasing the context.
56
192
  * No network-idle wait: SPAs and polling sites can stay busy forever. DNS decisions are not followed
57
193
  * by Chromium `continue()` in public mode: the router fetches on pinned vetted peers and fulfills
@@ -61,130 +197,36 @@ function assertHttpUrl({ url }, _options = {}) {
61
197
  * @throws Browser errors, cancellation, PageWorkTimeout, or a refused origin/transport boundary.
62
198
  * @complexity Bounded page I/O plus the consumer; at most six explicit navigation hops. */
63
199
  export async function renderPage({ browser, url, consume }, options = {}) {
64
- const { timeoutMs = 30_000, signal: callerSignal, waitFor = 1.2, originPolicy = "same-origin", originBaseUrl = url, router } = options;
200
+ const { timeoutMs = 30_000, signal: callerSignal } = options;
65
201
  assertHttpUrl({ url });
66
- if (originPolicy === "public" && !router)
202
+ if (options.originPolicy === "public" && !options.router)
67
203
  throw new Error("Public rendering requires a guarded request router");
68
204
  // A native total timer remains firm even if the wall clock moves between budgeted steps.
69
205
  const deadline = AbortSignal.timeout(timeoutMs);
70
206
  const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
71
- const budget = new PageWorkBudget({ timeoutMs }, { signal });
72
- let context;
73
- const onAbort = () => { void context?.close().catch(() => { }); };
74
- signal?.throwIfAborted();
75
- signal?.addEventListener("abort", onAbort, { once: true });
76
207
  try {
77
- context = await budget.run({ work: async () => {
78
- const supplied = options.contextOptions ?? {};
79
- const contextOptions = Object.fromEntries(["viewport", "deviceScaleFactor", "isMobile", "hasTouch", "javaScriptEnabled"].filter(key => supplied[key] !== undefined).map(key => [key, supplied[key]]));
80
- // No storageState, recordVideo, recordHar or user-data dir: observed state never reaches disk.
81
- const opened = await browser.newContext({ ...contextOptions, ignoreHTTPSErrors: false, serviceWorkers: "block", acceptDownloads: false });
82
- // A context that opens after cancellation/deadline still belongs to this call.
83
- if (budget.remainingMs() <= 0 || signal?.aborted) {
84
- void opened.close().catch(() => { });
85
- signal?.throwIfAborted();
86
- throw new PageWorkTimeout({ timeoutMs });
87
- }
88
- return opened;
89
- } });
90
- const active = context;
91
- await budget.run({ work: async () => { await active.routeWebSocket?.(/.*/, socket => socket.close().catch(() => { })); } });
92
- let refusedOrigin;
93
- await budget.run({ work: async () => {
94
- await active.route("**/*", async (route) => {
95
- const pending = route.request();
96
- const navigation = isMainFrameNavigation({ request: pending });
97
- const offOrigin = originPolicy === "same-origin" && navigation && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: pending.url() });
98
- if (offOrigin && navigation)
99
- refusedOrigin = new URL(pending.url()).origin;
100
- // Public data methods belong to the router; evidence always refuses writes first.
101
- const blocked = offOrigin || ((originPolicy !== "public" || !router) && !["GET", "HEAD"].includes(pending.method().toUpperCase()));
102
- const markBlocked = options.onRequest?.({ route, blocked });
103
- if (blocked) {
104
- await route.abort("blockedbyclient").catch(() => { });
105
- return;
106
- }
107
- if (router) {
108
- await router.handle({
109
- request: () => pending, fulfill: options => route.fulfill(options),
110
- abort: async (code) => {
111
- // Redirect aborts are navigation control, not a refused network observation.
112
- if (code !== "aborted" && typeof markBlocked === "function")
113
- markBlocked({ reason: "aborted by the guarded browser request router (unsafe target, unsupported request or resource cap)" });
114
- await route.abort(code);
115
- },
116
- });
117
- return;
118
- }
119
- // Trusted own-origin evidence retains browser cookies, but never posts preferences or forms.
120
- if (!route.continue)
121
- throw new Error("Own-origin browser route cannot continue");
122
- await route.continue();
123
- });
124
- } });
125
- const page = await budget.run({ work: () => active.newPage() });
126
- let target = url;
127
- let response = null;
128
- for (let hop = 0;; hop += 1) {
129
- assertHttpUrl({ url: target });
130
- if (originPolicy === "same-origin" && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: target }))
131
- throw new OffOriginNavigationError({ url: target });
132
- try {
133
- response = await budget.run({ work: () => page.goto(target, { waitUntil: "domcontentloaded", timeout: budget.remainingMs() }) });
134
- break;
135
- }
136
- catch (error) {
137
- if (refusedOrigin)
138
- throw new OffOriginNavigationError({ url: refusedOrigin });
139
- const next = router?.takeNavigationRedirect();
140
- if (next !== undefined && hop < MAX_REDIRECT_HOPS) {
141
- target = next;
142
- continue;
143
- }
144
- if (router?.report().navigationRefused)
145
- throw new RenderRequestRefused({});
146
- if (next !== undefined)
147
- throw new Error("too many redirects");
148
- throw error;
149
- }
150
- }
151
- const dismissed = options.dismissCookieBanners ? await dismissCookieBanners({ page, budget }) : false;
152
- if (typeof waitFor === "string") {
153
- if (!page.waitForSelector)
154
- throw new Error("Browser does not support selector waits");
155
- await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
156
- }
157
- else if (waitFor > 0) {
158
- await budget.run({ work: () => page.waitForTimeout(waitFor * 1000) });
159
- }
160
- if (options.loadWaitMs && page.waitForLoadState) {
161
- try {
162
- await budget.run({ work: () => page.waitForLoadState("load", { timeout: Math.min(options.loadWaitMs, budget.remainingMs()) }) });
163
- }
164
- catch (error) {
165
- if (error instanceof PageWorkTimeout || signal.aborted)
166
- throw error;
167
- // A polling or slow resource must not prevent bounded best-effort evidence/capture.
168
- }
169
- }
170
- // Hydrated consent widgets can arrive during the settle/selector wait.
171
- if (options.dismissCookieBanners && !dismissed && await dismissCookieBanners({ page, budget })) {
172
- await budget.run({ work: () => page.waitForTimeout(200) });
173
- }
174
- signal?.throwIfAborted();
175
- const finalUrl = page.url?.() ?? response?.url?.() ?? target;
176
- assertHttpUrl({ url: finalUrl });
177
- if (originPolicy === "same-origin" && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: finalUrl }))
178
- throw new OffOriginNavigationError({ url: finalUrl });
179
- return await budget.run({ work: () => consume({ page, context: active, response, finalUrl, budget }) });
208
+ return await consumeOnePage({ browser, url, consume, signal, timeoutMs }, options);
180
209
  }
181
210
  catch (error) {
182
211
  if (deadline.aborted && !callerSignal?.aborted)
183
212
  throw new PageWorkTimeout({ timeoutMs });
184
213
  throw error;
185
214
  }
215
+ }
216
+ /** The context opened here is closed at once on abort and always released when the call ends. */
217
+ async function consumeOnePage({ browser, url, consume, signal, timeoutMs }, options) {
218
+ const budget = new PageWorkBudget({ timeoutMs }, { signal });
219
+ let context;
220
+ const onAbort = () => { void context?.close().catch(() => { }); };
221
+ signal.throwIfAborted();
222
+ signal.addEventListener("abort", onAbort, { once: true });
223
+ try {
224
+ context = await openContext({ browser, budget, signal, timeoutMs }, options);
225
+ const session = await openSession({ context, budget, signal, url }, options);
226
+ return await budget.run({ work: () => consume(session) });
227
+ }
186
228
  finally {
187
- signal?.removeEventListener("abort", onAbort);
229
+ signal.removeEventListener("abort", onAbort);
188
230
  if (context)
189
231
  await budget.release({ close: () => context.close().catch(() => { }) });
190
232
  }
@@ -154,7 +154,7 @@ export declare function createRequestRouter({ httpClient, ownSiteFetch, allowedO
154
154
  ownSiteFetch: OwnSiteFetch;
155
155
  allowedOrigins: readonly string[];
156
156
  signal: AbortSignal;
157
- }, { maxRequests, maxTotalBytes, maxResourceBytes, maxConcurrent, perRequestTimeoutMs, preserveOwnSiteCookies, allowDataRequests, maxRequestBodyBytes, isEgressRefused, onResponse, onBlocked }?: RequestRouterOptions): RequestRouter;
157
+ }, options?: RequestRouterOptions): RequestRouter;
158
158
  /**
159
159
  * The default {@link OwnSiteFetch}: the global `fetch`, redirects returned rather than followed (so
160
160
  * the router re-decides the next hop), body read up to `maxBytes`. Overflow cancels the stream;