@jini-ai/diagnostics 0.5.3 → 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.
@@ -1,4 +1,5 @@
1
1
  /** Evidence and browser ports. Cookie values, request bodies, and form values are never modelled. */
2
+ import type { PagePerformanceEvidence } from "./page-performance-script.js";
2
3
  /** Which side of the consent interaction an observation belongs to. `before` is everything seen
3
4
  * from navigation up to the consent click; `after` is everything seen following it. A run that was
4
5
  * not asked to perform a consent action reports everything as `before` — there was no transition,
@@ -109,6 +110,7 @@ export interface DocumentEvidence {
109
110
  * a section that was not collected is missing, and a report must treat missing as
110
111
  * "not observed", never as "observed to be empty". */
111
112
  export interface PageObservation {
113
+ readonly performance?: PagePerformanceEvidence;
112
114
  readonly document: DocumentEvidence;
113
115
  readonly cookies: readonly CookieEvidence[];
114
116
  readonly requests: readonly RequestEvidence[];
@@ -146,6 +148,7 @@ export type ObservePageResult = {
146
148
  * interaction. This belongs to call options rather than the required page/limit contract. */
147
149
  export interface ObservePageOptions {
148
150
  readonly consentAcceptSelector?: string;
151
+ readonly collectPerformance?: boolean;
149
152
  }
150
153
  export interface SiteEvidenceBrowserPort {
151
154
  /** Loads one page in a fresh, isolated, non-persistent context and returns what was observed.
@@ -1,4 +1,3 @@
1
- /** Evidence and browser ports. Cookie values, request bodies, and form values are never modelled. */
2
1
  export {};
3
2
  // Keep browser vendors behind this port so caps, same-origin refusals and privacy rules can be
4
3
  // checked with a lightweight fake. Omitting sensitive fields from the contract is stronger than
@@ -127,6 +127,8 @@ export interface ObservationPolicy {
127
127
  }): string;
128
128
  }
129
129
  export interface CollectPageEvidenceOptions {
130
+ /** Explicit opt-in only; never collected by background evidence calls. */
131
+ readonly collectPerformance?: boolean;
130
132
  readonly clock?: Clock;
131
133
  /** CSS selector for the site's own consent-accept control. Without it no interaction happens and
132
134
  * no `after`-phase evidence is produced — an omission the result states explicitly rather than
@@ -51,54 +51,36 @@ export async function collectPageEvidence(deps, input = {}) {
51
51
  const origin = await deps.originRegistry.canonicalOrigin({ workspaceId: deps.workspaceId });
52
52
  const originBaseUrl = verifiedOriginToBaseUrl({ origin });
53
53
  const { accepted, skipped } = partitionRequestedPaths(deps.paths);
54
+ const report = (rest) => ({
55
+ schemaVersion: "1",
56
+ collectedAt: new Date(startedAt).toISOString(),
57
+ origin: originBaseUrl,
58
+ browser: rest.browser,
59
+ consentTransition: consentTransitionReport(input.consentAcceptSelector),
60
+ limits: SITE_EVIDENCE_LIMITS,
61
+ pages: rest.pages,
62
+ skipped: rest.skipped,
63
+ disclaimer: SITE_EVIDENCE_DISCLAIMER,
64
+ });
54
65
  const availability = await deps.openBrowser({});
55
66
  if (!availability.available) {
56
67
  const reason = deps.observationPolicy.redactMessage({ message: availability.reason });
57
- return {
58
- schemaVersion: "1",
59
- collectedAt: new Date(startedAt).toISOString(),
60
- origin: originBaseUrl,
68
+ return report({
61
69
  browser: { status: "unavailable", reason },
62
- consentTransition: consentTransitionReport(input.consentAcceptSelector),
63
- limits: SITE_EVIDENCE_LIMITS,
64
70
  pages: [],
65
- skipped: [
66
- ...skipped,
67
- ...accepted.map((path) => skip(path, "browser-unavailable", reason)),
68
- ],
69
- disclaimer: SITE_EVIDENCE_DISCLAIMER,
70
- };
71
+ skipped: [...skipped, ...accepted.map((path) => skip(path, "browser-unavailable", reason))],
72
+ });
71
73
  }
72
74
  const pages = [];
73
75
  const runtimeSkipped = [];
74
76
  try {
75
77
  for (const path of accepted) {
76
78
  const remainingMs = SITE_EVIDENCE_LIMITS.maxTotalMs - (now() - startedAt);
77
- if (remainingMs <= 0) {
78
- runtimeSkipped.push(skip(path, "deadline", `the ${SITE_EVIDENCE_LIMITS.maxTotalMs}ms whole-call budget was exhausted before this page was loaded`));
79
- continue;
80
- }
81
- // A THROWING `observe()` (a port implementation that does not honor the `{ ok: false, reason }`
82
- // contract for every failure — e.g. the page navigating away between the load and the read
83
- // that follows it) must not end the whole run any more than an ordinary `ok: false` does. One
84
- // bad page is recorded as skipped; every OTHER requested page still gets its own attempt.
85
- try {
86
- // The port's timeout is advisory for custom adapters; bound our own await as well.
87
- const timeoutMs = Math.min(SITE_EVIDENCE_LIMITS.maxPageLoadMs, remainingMs);
88
- const outcome = await new PageWorkBudget({ timeoutMs }).run({
89
- work: () => observeOnePage(availability.browser, originBaseUrl, path, input, timeoutMs),
90
- });
91
- if (outcome.kind === "skipped") {
92
- runtimeSkipped.push({ ...outcome.skipped, message: deps.observationPolicy.redactMessage({ message: outcome.skipped.message }) });
93
- }
94
- else {
95
- pages.push({ ...outcome.page, observation: deps.observationPolicy.redactObservation({ observation: outcome.page.observation }) });
96
- }
97
- }
98
- catch (error) {
99
- const reason = error instanceof PageWorkTimeout && remainingMs <= SITE_EVIDENCE_LIMITS.maxPageLoadMs ? "deadline" : "navigation-failed";
100
- runtimeSkipped.push(skip(path, reason, deps.observationPolicy.redactMessage({ message: messageOf(error) })));
101
- }
79
+ const outcome = await attemptPage({ browser: availability.browser, originBaseUrl, path, remainingMs, policy: deps.observationPolicy }, input);
80
+ if (outcome.kind === "skipped")
81
+ runtimeSkipped.push(outcome.skipped);
82
+ else
83
+ pages.push(outcome.page);
102
84
  }
103
85
  }
104
86
  finally {
@@ -106,17 +88,35 @@ export async function collectPageEvidence(deps, input = {}) {
106
88
  await new PageWorkBudget({ timeoutMs: Math.max(0, SITE_EVIDENCE_LIMITS.maxTotalMs - (now() - startedAt)) })
107
89
  .release({ close: () => availability.browser.close({}) });
108
90
  }
109
- return {
110
- schemaVersion: "1",
111
- collectedAt: new Date(startedAt).toISOString(),
112
- origin: originBaseUrl,
113
- browser: { status: "available" },
114
- consentTransition: consentTransitionReport(input.consentAcceptSelector),
115
- limits: SITE_EVIDENCE_LIMITS,
116
- pages,
117
- skipped: [...skipped, ...runtimeSkipped],
118
- disclaimer: SITE_EVIDENCE_DISCLAIMER,
119
- };
91
+ return report({ browser: { status: "available" }, pages, skipped: [...skipped, ...runtimeSkipped] });
92
+ }
93
+ /**
94
+ * One accepted page inside the whole-call budget: its redacted evidence, or why it was skipped.
95
+ * @complexity O(1) plus one bounded browser page load.
96
+ */
97
+ async function attemptPage({ browser, originBaseUrl, path, remainingMs, policy }, input) {
98
+ if (remainingMs <= 0) {
99
+ return { kind: "skipped", skipped: skip(path, "deadline", `the ${SITE_EVIDENCE_LIMITS.maxTotalMs}ms whole-call budget was exhausted before this page was loaded`) };
100
+ }
101
+ // A THROWING `observe()` (a port implementation that does not honor the `{ ok: false, reason }`
102
+ // contract for every failure — e.g. the page navigating away between the load and the read
103
+ // that follows it) must not end the whole run any more than an ordinary `ok: false` does. One
104
+ // bad page is recorded as skipped; every OTHER requested page still gets its own attempt.
105
+ try {
106
+ // The port's timeout is advisory for custom adapters; bound our own await as well.
107
+ const timeoutMs = Math.min(SITE_EVIDENCE_LIMITS.maxPageLoadMs, remainingMs);
108
+ const outcome = await new PageWorkBudget({ timeoutMs }).run({
109
+ work: () => observeOnePage(browser, originBaseUrl, path, input, timeoutMs),
110
+ });
111
+ if (outcome.kind === "skipped") {
112
+ return { kind: "skipped", skipped: { ...outcome.skipped, message: policy.redactMessage({ message: outcome.skipped.message }) } };
113
+ }
114
+ return { kind: "observed", page: { ...outcome.page, observation: policy.redactObservation({ observation: outcome.page.observation }) } };
115
+ }
116
+ catch (error) {
117
+ const reason = error instanceof PageWorkTimeout && remainingMs <= SITE_EVIDENCE_LIMITS.maxPageLoadMs ? "deadline" : "navigation-failed";
118
+ return { kind: "skipped", skipped: skip(path, reason, policy.redactMessage({ message: messageOf(error) })) };
119
+ }
120
120
  }
121
121
  /**
122
122
  * Resolves, loads, and validates exactly one requested page. Split out of
@@ -138,10 +138,13 @@ async function observeOnePage(browser, originBaseUrl, path, input, timeoutMs) {
138
138
  maxRequests: SITE_EVIDENCE_LIMITS.maxRequests,
139
139
  maxAccessibilityNodesPerCategory: SITE_EVIDENCE_LIMITS.maxAccessibilityNodesPerCategory,
140
140
  maxContrastSamples: SITE_EVIDENCE_LIMITS.maxContrastSamples,
141
- }, input.consentAcceptSelector === undefined ? {} : { consentAcceptSelector: input.consentAcceptSelector });
141
+ }, {
142
+ ...(input.consentAcceptSelector === undefined ? {} : { consentAcceptSelector: input.consentAcceptSelector }),
143
+ ...(input.collectPerformance === undefined ? {} : { collectPerformance: input.collectPerformance }),
144
+ });
142
145
  if (!result.ok) {
143
146
  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}`) };
147
+ return offOriginSkip({ path, url: result.offOriginUrl, originBaseUrl });
145
148
  }
146
149
  return { kind: "skipped", skipped: skip(path, "navigation-failed", result.reason) };
147
150
  }
@@ -150,14 +153,13 @@ async function observeOnePage(browser, originBaseUrl, path, input, timeoutMs) {
150
153
  // as evidence of the redirect and its content is discarded — this tool does not inspect
151
154
  // anybody else's site, including one the inspected origin chose to point at.
152
155
  const finalUrl = result.observation.document.finalUrl;
153
- if (!isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: finalUrl })) {
154
- return {
155
- kind: "skipped",
156
- skipped: skip(path, "off-origin-redirect", `redirected off the inspected origin to '${redactToOrigin(finalUrl)}' — not inspected; this tool only observes ${originBaseUrl}`),
157
- };
158
- }
156
+ if (!isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: finalUrl }))
157
+ return offOriginSkip({ path, url: finalUrl, originBaseUrl });
159
158
  return { kind: "observed", page: { path, url, observation: result.observation } };
160
159
  }
160
+ function offOriginSkip({ path, url, originBaseUrl }) {
161
+ return { kind: "skipped", skipped: skip(path, "off-origin-redirect", `redirected off the inspected origin to '${redactToOrigin(url)}' — not inspected; this tool only observes ${originBaseUrl}`) };
162
+ }
161
163
  /**
162
164
  * Splits the requested paths into the ones this call will attempt and the ones it will not,
163
165
  * applying the syntactic guard first and the page cap second.
@@ -2,4 +2,5 @@ export * from "./browser-port.js";
2
2
  export * from "./collect-page-evidence.js";
3
3
  export * from "./same-origin.js";
4
4
  export { collectPageStructure, type PageStructureCapture, type PageStructureLimits } from "./page-structure-script.js";
5
+ export { collectPagePerformance, type PagePerformanceEvidence } from "./page-performance-script.js";
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -2,4 +2,5 @@ export * from "./browser-port.js";
2
2
  export * from "./collect-page-evidence.js";
3
3
  export * from "./same-origin.js";
4
4
  export { collectPageStructure } from "./page-structure-script.js";
5
+ export { collectPagePerformance } from "./page-performance-script.js";
5
6
  //# sourceMappingURL=index.js.map
@@ -86,19 +86,19 @@ export function createRenderBrowserPool({ launch }, { maxConcurrent = 2, idleClo
86
86
  void acquisition.then(() => { acquired = true; if (released)
87
87
  lazy.release(); }, () => { });
88
88
  let onAbort;
89
+ let browser;
89
90
  try {
90
- const browser = signal ? await Promise.race([
91
+ browser = signal ? await Promise.race([
91
92
  acquisition,
93
+ // No await separates the entry `signal?.throwIfAborted()` from this registration, so the
94
+ // signal cannot already be aborted here and the listener alone observes cancellation.
92
95
  new Promise((_resolve, reject) => {
93
96
  onAbort = () => reject(signal.reason);
94
97
  signal.addEventListener("abort", onAbort, { once: true });
95
- if (signal.aborted)
96
- onAbort();
97
98
  }),
98
99
  ]) : await acquisition;
99
100
  acquired = true;
100
101
  signal?.throwIfAborted();
101
- return { browser, release };
102
102
  }
103
103
  catch (error) {
104
104
  release();
@@ -108,6 +108,7 @@ export function createRenderBrowserPool({ launch }, { maxConcurrent = 2, idleClo
108
108
  if (onAbort)
109
109
  signal?.removeEventListener("abort", onAbort);
110
110
  }
111
+ return { browser, release };
111
112
  },
112
113
  close: () => lazy.close(),
113
114
  };
@@ -0,0 +1,38 @@
1
+ /** Numeric-only on-demand page evidence; no DOM content, attributes, URLs or heap objects leave the page. */
2
+ export interface PagePerformanceEvidence {
3
+ context: 'fresh-isolated-page';
4
+ /** Chromium exposes an approximate heap; null means this API was unavailable. */
5
+ heap: {
6
+ usedBytes: number;
7
+ allocatedBytes: number;
8
+ limitBytes: number;
9
+ } | null;
10
+ /** Attached light-DOM nodes; excludes shadow roots, detached nodes and iframe documents. */
11
+ domNodes: number;
12
+ domTruncated: boolean;
13
+ mountedHiddenPanels: number;
14
+ hiddenPreElements: number;
15
+ hiddenPreTextChars: number;
16
+ iframes: number;
17
+ /** Buffered tasks since navigation plus a 100ms sample, capped at 200; not field INP. */
18
+ longTasks: {
19
+ supported: boolean;
20
+ count: number;
21
+ totalMs: number;
22
+ maxMs: number;
23
+ truncated: boolean;
24
+ };
25
+ suspects: readonly string[];
26
+ }
27
+ /** Serialized into the browser like collectPageStructure; all runtime references are local or Web APIs.
28
+ * Counts nodes up to a fixed cap and samples buffered navigation long tasks for 100ms. Unsupported
29
+ * heap/long-task APIs remain explicit, never zero measurements. Hidden counts cover the scanned DOM.
30
+ * @returns Numeric evidence from this newly loaded context, never the user's existing admin tab.
31
+ * @complexity O(min(nodes, 100000) * DOM depth) time, O(1) output; the observer caps its event sample at 200.
32
+ */
33
+ export declare function collectPagePerformance(_required: Record<string, never>, _options?: Record<string, never>): Promise<PagePerformanceEvidence>;
34
+ /** Use the same local name shim as the existing DOM evidence script so keepNames bundlers work.
35
+ * @complexity O(script length) for serialization; evaluation is performed only on explicit request.
36
+ */
37
+ export declare function buildPagePerformanceExpression(_required: Record<string, never>, _options?: {}): string;
38
+ //# sourceMappingURL=page-performance-script.d.ts.map
@@ -0,0 +1,80 @@
1
+ /// <reference lib="dom" />
2
+ /** Serialized into the browser like collectPageStructure; all runtime references are local or Web APIs.
3
+ * Counts nodes up to a fixed cap and samples buffered navigation long tasks for 100ms. Unsupported
4
+ * heap/long-task APIs remain explicit, never zero measurements. Hidden counts cover the scanned DOM.
5
+ * @returns Numeric evidence from this newly loaded context, never the user's existing admin tab.
6
+ * @complexity O(min(nodes, 100000) * DOM depth) time, O(1) output; the observer caps its event sample at 200.
7
+ */
8
+ export async function collectPagePerformance(_required, _options = {}) {
9
+ // Helpers stay nested: only this function's source is serialized into the page.
10
+ const maxNodes = 100_000, maxTasks = 200;
11
+ const counts = { domNodes: 0, mountedHiddenPanels: 0, hiddenPreElements: 0, hiddenPreTextChars: 0, iframes: 0 };
12
+ function countElement(element) {
13
+ const hidden = element.getClientRects().length === 0;
14
+ if (element.tagName === 'IFRAME')
15
+ counts.iframes++;
16
+ if (element.matches('details:not([open]),[hidden],[aria-hidden="true"]') ||
17
+ (element.getAttribute('role') === 'tabpanel' && hidden))
18
+ counts.mountedHiddenPanels++;
19
+ if (element.tagName === 'PRE' && hidden)
20
+ counts.hiddenPreElements++;
21
+ }
22
+ function countNode(node) {
23
+ if (node.nodeType === Node.ELEMENT_NODE)
24
+ countElement(node);
25
+ else if (node.nodeType === Node.TEXT_NODE && node.parentElement?.closest('pre')?.getClientRects().length === 0) {
26
+ // Count text once, without copying hidden output into model context.
27
+ counts.hiddenPreTextChars += node.textContent?.length ?? 0;
28
+ }
29
+ }
30
+ async function sampleLongTasks() {
31
+ const longTasks = { supported: false, count: 0, totalMs: 0, maxMs: 0, truncated: false };
32
+ if (typeof PerformanceObserver === 'undefined' || !PerformanceObserver.supportedEntryTypes.includes('longtask'))
33
+ return longTasks;
34
+ const observer = new PerformanceObserver(list => {
35
+ for (const entry of list.getEntries()) {
36
+ if (longTasks.count >= maxTasks) {
37
+ longTasks.truncated = true;
38
+ break;
39
+ }
40
+ longTasks.count++;
41
+ longTasks.totalMs += entry.duration;
42
+ longTasks.maxMs = Math.max(longTasks.maxMs, entry.duration);
43
+ }
44
+ });
45
+ try {
46
+ observer.observe({ type: 'longtask', buffered: true });
47
+ longTasks.supported = true;
48
+ await new Promise(resolve => setTimeout(resolve, 100));
49
+ }
50
+ finally {
51
+ observer.disconnect();
52
+ }
53
+ return longTasks;
54
+ }
55
+ const walker = document.createTreeWalker(document, NodeFilter.SHOW_ALL);
56
+ let node = walker.nextNode();
57
+ while (node && counts.domNodes < maxNodes) {
58
+ counts.domNodes++;
59
+ countNode(node);
60
+ node = walker.nextNode();
61
+ }
62
+ const memory = performance.memory;
63
+ const heap = memory ? { usedBytes: memory.usedJSHeapSize, allocatedBytes: memory.totalJSHeapSize, limitBytes: memory.jsHeapSizeLimit } : null;
64
+ const longTasks = await sampleLongTasks();
65
+ const { domNodes, mountedHiddenPanels, hiddenPreElements, hiddenPreTextChars, iframes } = counts;
66
+ const suspects = [
67
+ hiddenPreElements ? `${hiddenPreElements} hidden pre elements remain mounted with ${hiddenPreTextChars} text characters.` : '',
68
+ mountedHiddenPanels ? `${mountedHiddenPanels} hidden or collapsed panels remain mounted.` : '',
69
+ iframes ? `${iframes} iframes have separate documents; their DOM and heaps are outside this sample.` : '',
70
+ longTasks.count ? `${longTasks.count} long tasks were observed; the longest took ${Math.round(longTasks.maxMs)} ms.` : '',
71
+ ].filter(Boolean);
72
+ return { context: 'fresh-isolated-page', heap, domNodes, domTruncated: node !== null, mountedHiddenPanels, hiddenPreElements, hiddenPreTextChars, iframes, longTasks, suspects };
73
+ }
74
+ /** Use the same local name shim as the existing DOM evidence script so keepNames bundlers work.
75
+ * @complexity O(script length) for serialization; evaluation is performed only on explicit request.
76
+ */
77
+ export function buildPagePerformanceExpression(_required, _options = {}) {
78
+ return `(() => { var __name = function(fn) { return fn; }; return (${collectPagePerformance.toString()})({}); })()`;
79
+ }
80
+ //# sourceMappingURL=page-performance-script.js.map
@@ -1,6 +1,3 @@
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. */
4
1
  import type { SiteEvidenceBrowserAvailability } from "./browser-port.js";
5
2
  import { type PlaywrightAdapterOptions } from "./playwright-runtime.js";
6
3
  export { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./playwright-runtime.js";
@@ -1,3 +1,7 @@
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. */
4
+ import { buildPagePerformanceExpression } from "./page-performance-script.js";
1
5
  import { collectPageStructure } from "./page-structure-script.js";
2
6
  import { renderPage, OffOriginNavigationError } from "./render-page.js";
3
7
  import { openPlaywrightRenderBrowser } from "./playwright-runtime.js";
@@ -42,8 +46,9 @@ class PlaywrightSiteEvidenceBrowser {
42
46
  const requests = [];
43
47
  const notes = [];
44
48
  let phase = "before";
49
+ let result;
45
50
  try {
46
- return await renderPage({
51
+ result = await renderPage({
47
52
  browser: this.browser, url: request.url,
48
53
  consume: async ({ page, context, response, finalUrl, budget }) => {
49
54
  if (!response)
@@ -63,10 +68,14 @@ class PlaywrightSiteEvidenceBrowser {
63
68
  if (!context.cookies)
64
69
  throw new Error("Browser cannot observe cookies");
65
70
  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
- }) };
71
+ let performance;
72
+ if (request.collectPerformance) {
73
+ performance = await budget.run({ work: async () => await page.evaluate(buildPagePerformanceExpression({})) });
74
+ }
75
+ return { ok: true, observation: { ...buildObservation({
76
+ request, finalUrl, httpStatus: response.status(), headers: response.headers?.() ?? {},
77
+ title: structure.title, structure, cookies, requests, notes, consentPhase: phase,
78
+ }), ...(performance ? { performance } : {}) } };
70
79
  },
71
80
  }, {
72
81
  ...(router ? { router } : {}), signal: abort.signal,
@@ -91,11 +100,12 @@ class PlaywrightSiteEvidenceBrowser {
91
100
  });
92
101
  }
93
102
  catch (error) {
94
- return { ok: false, reason: `page capture failed after load or navigation: ${messageOf(error)}`, ...(error instanceof OffOriginNavigationError ? { offOriginUrl: error.origin } : {}) };
103
+ result = { ok: false, reason: `page capture failed after load or navigation: ${messageOf(error)}`, ...(error instanceof OffOriginNavigationError ? { offOriginUrl: error.origin } : {}) };
95
104
  }
96
105
  finally {
97
106
  abort.abort();
98
107
  }
108
+ return result;
99
109
  }
100
110
  async close(_required) {
101
111
  await this.browser.close();
@@ -267,16 +277,15 @@ function toCookieEvidence(cookie, request, phase) {
267
277
  * server on an ephemeral port, and it would have been a silently wrong citation in a privacy
268
278
  * finding, which is the worst failure this tool has available.
269
279
  *
270
- * Fails closed (`false`, i.e. treated as third-party) on an unparseable base URL: over-reporting
271
- * third-party makes a screening noisier, under-reporting it makes a screening wrong.
280
+ * An unparseable base URL must fail closed (treated as third-party): over-reporting third-party
281
+ * makes a screening noisier, under-reporting it makes a screening wrong. That failure is taken
282
+ * upstream, before this comparison can run: `observe` renders under the same-origin policy, whose
283
+ * `assertNavigable` → `isSameOriginUrl` treats an unparseable base as off-origin and refuses the
284
+ * navigation before any request or cookie is recorded. Every call here therefore has a base that
285
+ * already parsed, so no local parse guard is needed.
272
286
  */
273
287
  function sameHost(originBaseUrl, hostname) {
274
- try {
275
- return new URL(originBaseUrl).hostname.toLowerCase() === hostname.toLowerCase();
276
- }
277
- catch {
278
- return false;
279
- }
288
+ return new URL(originBaseUrl).hostname.toLowerCase() === hostname.toLowerCase();
280
289
  }
281
290
  /** Strips a single trailing slash so `https://x/pricing` and `https://x/pricing/` do not read as a
282
291
  * redirect. Anything else that differs genuinely is one. */
@@ -81,6 +81,9 @@ export interface PlaywrightAdapterOptions {
81
81
  chromiumSandbox?: boolean;
82
82
  };
83
83
  }
84
+ /** Default {@link PlaywrightAdapterOptions.moduleLoader}: a real dynamic import by module name, wired
85
+ * here at the composition edge so the optional `playwright` dependency is only resolved on use. */
86
+ export declare const nodeModuleLoader: NonNullable<PlaywrightAdapterOptions["moduleLoader"]>;
84
87
  /** Opens the optional browser capability; import and launch failures become availability results. */
85
88
  export declare function openPlaywrightRenderBrowser(_required: Record<string, never>, options?: PlaywrightAdapterOptions): Promise<{
86
89
  available: true;
@@ -1,13 +1,16 @@
1
+ /** Default {@link PlaywrightAdapterOptions.moduleLoader}: a real dynamic import by module name, wired
2
+ * here at the composition edge so the optional `playwright` dependency is only resolved on use. */
3
+ export const nodeModuleLoader = {
4
+ load: async ({ moduleName }) => (await import(moduleName)),
5
+ };
1
6
  /** Opens the optional browser capability; import and launch failures become availability results. */
2
7
  // A successful launch transfers process ownership to the caller; close the browser in a finally
3
8
  // block so an unreachable or unstable page cannot leak the browser process.
4
9
  export async function openPlaywrightRenderBrowser(_required, options = {}) {
5
10
  let playwright;
11
+ const { moduleLoader = nodeModuleLoader } = options;
6
12
  try {
7
- const moduleName = "playwright";
8
- playwright = options.moduleLoader
9
- ? await options.moduleLoader.load({ moduleName })
10
- : (await import(moduleName));
13
+ playwright = await moduleLoader.load({ moduleName: "playwright" });
11
14
  }
12
15
  catch (error) {
13
16
  return {
@@ -89,10 +89,9 @@ export declare function publicPageExpression({ maxChars, textMode }: {
89
89
  export declare function renderPublicPage({ input, httpClient }: {
90
90
  input: PublicPageInput;
91
91
  httpClient: HttpClientPort;
92
- }, { signal, timeoutMs, moduleLoader, browserPool }?: {
92
+ }, { signal, timeoutMs: requestedMs, browserPool, ...launch }?: {
93
93
  signal?: AbortSignal;
94
94
  timeoutMs?: number;
95
- moduleLoader?: PlaywrightAdapterOptions["moduleLoader"];
96
95
  browserPool?: RenderBrowserPool;
97
- }): Promise<PublicPageCapture>;
96
+ } & Pick<PlaywrightAdapterOptions, "moduleLoader">): Promise<PublicPageCapture>;
98
97
  //# sourceMappingURL=public-page.d.ts.map