feat(browser): capture controlled Playwright scenarios

This commit is contained in:
morluto
2026-07-24 13:16:01 +00:00
parent d9977286f9
commit 1ac3118aa2
32 changed files with 4800 additions and 166 deletions
+65
View File
@@ -0,0 +1,65 @@
import { createHash } from "node:crypto";
import type {
BrowserScenario,
BrowserScenarioUrl,
BrowserScenarioValue,
} from "../domain/browserScenario.js";
const REDACTION_PREFIX = "[REDACTED:";
/** Resolved secret values kept only for one in-memory scenario session. */
export class BrowserScenarioSecrets {
private constructor(private readonly values: ReadonlyMap<string, string>) {}
static resolve(
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
): BrowserScenarioSecrets | undefined {
const values = new Map<string, string>();
for (const declaration of scenario.secrets) {
const value = environment[declaration.environment_variable];
if (value === undefined) return undefined;
values.set(declaration.secret_id, value);
}
return new BrowserScenarioSecrets(values);
}
value(source: BrowserScenarioValue): string {
if (source.source === "literal") return source.value;
const value = this.values.get(source.secret_id);
if (value === undefined)
throw new Error("Validated browser secret was not resolved");
return value;
}
url(destination: BrowserScenarioUrl): string {
const url = new URL(destination.url);
for (const { name, value } of destination.query)
url.searchParams.append(name, this.value(value));
return url.href;
}
redact(value: string): string {
let output = value;
for (const [id, secret] of this.values)
if (secret !== "")
output = output.replaceAll(secret, `${REDACTION_PREFIX}${id}]`);
return output;
}
fingerprint(value: string): {
readonly value_state: "hashed" | "redacted-secret";
readonly value_sha256: string | null;
} {
for (const secret of this.values.values())
if (secret !== "" && value.includes(secret))
return { value_state: "redacted-secret", value_sha256: null };
return {
value_state: "hashed",
value_sha256: createHash("sha256")
.update(this.redact(value))
.digest("hex"),
};
}
}
+59
View File
@@ -0,0 +1,59 @@
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import type {
BrowserScenarioEvent,
BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
export interface BrowserScenarioSessionPort {
readonly mode: "launch" | "connect";
readonly processOwnership: "provider-owned" | "external";
readonly product: string;
readonly version: string;
readonly initialUrl: string;
currentUrl(): string;
setStep(index: number): void;
nextEventSequence(): number;
lastEventSequence(): number;
events(): {
readonly retained: number;
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
};
eventTruncationSections(): readonly (
| "events"
| "frames"
| "workers"
| "popups"
| "websockets"
)[];
perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<void>;
capture(
requested: ReadonlySet<SnapshotKind>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<BrowserStepArtifacts>;
close(): Promise<"terminated-owned-process" | "disconnected-external">;
redactError(error: unknown): string;
}
export interface BrowserScenarioSessionFactory {
open(
scenario: BrowserScenario,
options?: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
},
): Promise<BrowserScenarioSessionPort>;
}
+4 -3
View File
@@ -74,13 +74,13 @@ export const discoverCdpEndpoint = async (
operation: BrowserObservationOperation,
signal?: AbortSignal,
): Promise<CdpEndpointDiscovery> => {
const versionInput = await readJson(
const versionInput = await readBoundedCdpJson(
new URL("/json/version", endpoint),
MAX_VERSION_BYTES,
operation,
signal,
);
const targetsInput = await readJson(
const targetsInput = await readBoundedCdpJson(
new URL("/json/list", endpoint),
MAX_TARGET_LIST_BYTES,
operation,
@@ -289,7 +289,8 @@ const targetWebSocket = (
}
};
const readJson = async (
/** Read one bounded loopback CDP discovery document without redirects. */
export const readBoundedCdpJson = async (
url: URL,
maximumBytes: number,
operation: BrowserObservationOperation,
@@ -0,0 +1,380 @@
import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js";
import type {
ExecutionOptions,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import {
browserScenarioCaptureSchema,
browserScenarioCompletenessSchema,
browserScenarioStepSchema,
browserStepArtifactsSchema,
type BrowserScenarioCapture,
type BrowserScenarioCompleteness,
type BrowserScenarioStep,
type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import {
AnalysisError,
BrowserObservationError,
ProviderAdapterError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
BrowserScenarioSessionFactory,
BrowserScenarioSessionPort,
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioSessionFactory } from "./PlaywrightScenarioSession.js";
const OPERATION = "capture_browser_scenario" as const;
export const PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY: ProviderIdentity =
Object.freeze({
id: "rea-playwright-browser-scenario",
name: "REA Playwright browser scenario capture provider",
version: "1",
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
const requestedForStep = (
scenario: BrowserScenario,
stepIndex: number,
): ReadonlySet<SnapshotKind> =>
new Set([
...scenario.capture.after_each_step,
...(stepIndex === scenario.actions.length ? scenario.capture.at_end : []),
]);
const unavailableArtifacts = (
requested: ReadonlySet<SnapshotKind>,
reason: string,
): BrowserStepArtifacts => {
const state = (kind: SnapshotKind) =>
requested.has(kind)
? { state: "missing" as const, reason }
: { state: "not_requested" as const };
return browserStepArtifactsSchema.parse({
screenshot: state("screenshot"),
dom: state("dom"),
accessibility: state("accessibility"),
url: state("url"),
history: state("history"),
storage: state("storage"),
});
};
const stepCompleteness = (
artifacts: BrowserStepArtifacts,
status: BrowserScenarioStep["status"],
): BrowserScenarioCompleteness => {
const missing = Object.entries(artifacts)
.filter(([, state]) => state.state === "missing")
.map(([section]) => section);
const truncated = Object.entries(artifacts)
.filter(([, state]) => state.state === "truncated")
.map(([section]) => section);
if (status !== "completed") missing.push("action");
const condition =
truncated.length > 0
? "truncated"
: missing.length > 0
? "incomplete"
: "complete";
return browserScenarioCompletenessSchema.parse({
status: condition,
equality_eligible: condition === "complete",
missing_sections: [...new Set(missing)].sort(),
truncated_sections: [...new Set(truncated)].sort(),
});
};
const createStep = (input: {
readonly stepIndex: number;
readonly stepId: string;
readonly action: string;
readonly status: BrowserScenarioStep["status"];
readonly elapsedMs: number;
readonly beforeUrl: string;
readonly afterUrl: string;
readonly error: string | null;
readonly eventStart: number;
readonly eventEnd: number;
readonly artifacts: BrowserStepArtifacts;
}): BrowserScenarioStep =>
browserScenarioStepSchema.parse({
step_index: input.stepIndex,
step_id: input.stepId,
action: input.action,
status: input.status,
elapsed_ms: input.elapsedMs,
before_url: sanitizeBrowserUrl(input.beforeUrl),
after_url: sanitizeBrowserUrl(input.afterUrl),
error: input.error,
event_sequence_start: input.eventStart,
event_sequence_end: input.eventEnd,
artifacts: input.artifacts,
completeness: stepCompleteness(input.artifacts, input.status),
});
const initialStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly elapsedMs: number;
readonly maximumTimeoutMs: number;
readonly signal: AbortSignal | undefined;
}): Promise<BrowserScenarioStep> => {
const { session, scenario, budget, elapsedMs, maximumTimeoutMs, signal } =
input;
const artifacts = await session.capture(
requestedForStep(scenario, 0),
budget,
maximumTimeoutMs,
signal,
);
return createStep({
stepIndex: 0,
stepId: "scenario_start",
action: "goto_start",
status: "completed",
elapsedMs,
beforeUrl: session.initialUrl,
afterUrl: session.currentUrl(),
error: null,
eventStart: 1,
eventEnd: session.lastEventSequence(),
artifacts,
});
};
const executeStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly action: BrowserScenarioAction;
readonly stepIndex: number;
readonly startedAt: number;
readonly priorFailure: boolean;
readonly signal: AbortSignal | undefined;
}): Promise<BrowserScenarioStep> => {
const {
session,
scenario,
budget,
action,
stepIndex,
startedAt,
priorFailure,
signal,
} = input;
const beforeUrl = session.currentUrl();
const eventStart = session.nextEventSequence();
const requested = requestedForStep(scenario, stepIndex);
if (priorFailure)
return createStep({
stepIndex,
stepId: action.step_id,
action: action.action,
status: "cancelled",
elapsedMs: 0,
beforeUrl,
afterUrl: beforeUrl,
error: "not executed after an earlier action failure",
eventStart,
eventEnd: session.lastEventSequence(),
artifacts: unavailableArtifacts(
requested,
"action was not executed after an earlier failure",
),
});
const actionStartedAt = Date.now();
session.setStep(stepIndex);
const requestCancelled = (): boolean => signal?.aborted === true;
let status: BrowserScenarioStep["status"] = "completed";
let error: string | null = null;
if (requestCancelled()) {
status = "cancelled";
error = "scenario request cancelled";
} else {
try {
const elapsed = Date.now() - startedAt;
const remaining = scenario.limits.max_duration_ms - elapsed;
if (remaining <= 0) throw new Error("Scenario duration limit reached");
await session.perform(action, remaining, signal);
} catch (cause) {
status = requestCancelled() ? "cancelled" : "failed";
error = session.redactError(cause);
}
}
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
const artifacts =
status === "cancelled" || remaining <= 0
? unavailableArtifacts(
requested,
status === "cancelled"
? "scenario request cancelled"
: "scenario duration limit reached",
)
: await session.capture(requested, budget, remaining, signal);
return createStep({
stepIndex,
stepId: action.step_id,
action: action.action,
status,
elapsedMs: Date.now() - actionStartedAt,
beforeUrl,
afterUrl: session.currentUrl(),
error,
eventStart,
eventEnd: session.lastEventSequence(),
artifacts,
});
};
const globalCompleteness = (
scenario: BrowserScenario,
session: BrowserScenarioSessionPort,
steps: readonly BrowserScenarioStep[],
): BrowserScenarioCompleteness => {
const missing = steps.flatMap(
({ completeness }) => completeness.missing_sections,
);
const truncated = steps.flatMap(
({ completeness }) => completeness.truncated_sections,
);
truncated.push(...session.eventTruncationSections());
if (session.mode === "connect") missing.push("events");
const status =
truncated.length > 0
? "truncated"
: missing.length > 0
? "incomplete"
: "complete";
return browserScenarioCompletenessSchema.parse({
status,
equality_eligible: status === "complete",
missing_sections: [...new Set(missing)].sort(),
truncated_sections: [...new Set(truncated)].sort(),
});
};
const runScenario = async (
factory: BrowserScenarioSessionFactory,
scenario: BrowserScenario,
options: ExecutionOptions,
): Promise<BrowserScenarioCapture> => {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = Date.now();
const budget = new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
);
const session = await factory.open(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget,
deadlineAt: startedAt + scenario.limits.max_duration_ms,
});
const steps: BrowserScenarioStep[] = [];
let cleanup: "terminated-owned-process" | "disconnected-external" | undefined;
try {
steps.push(
await initialStep({
session,
scenario,
budget,
elapsedMs: Date.now() - startedAt,
maximumTimeoutMs:
scenario.limits.max_duration_ms - (Date.now() - startedAt),
signal: options.signal,
}),
);
let failed = false;
for (const [offset, action] of scenario.actions.entries()) {
const step = await executeStep({
session,
scenario,
budget,
action,
stepIndex: offset + 1,
startedAt,
priorFailure: failed,
signal: options.signal,
});
steps.push(step);
failed ||= step.status !== "completed";
}
} finally {
cleanup = await session.close();
}
const events = session.events();
const completeness = globalCompleteness(scenario, session, steps);
return browserScenarioCaptureSchema.parse({
schema_version: 1,
browser: {
mode: session.mode,
process_ownership: session.processOwnership,
cleanup,
product: session.product,
version: session.version,
},
scenario: {
start_origin: new URL(scenario.start_url.url).origin,
allowed_origins: scenario.allowed_origins,
action_count: scenario.actions.length,
secret_references: scenario.secrets.map(({ secret_id: id }) => id).sort(),
},
duration_ms: Date.now() - startedAt,
steps,
events,
completeness,
limitations: [
"Event sequence records provider receipt order; simultaneous browser causality is not inferred.",
"Response bodies are not retained.",
"Storage values are hashed only after declared-secret redaction.",
...(session.mode === "connect"
? [
"CDP attachment cannot recover pre-attach events or guarantee launch-time context options.",
]
: []),
],
});
};
/** Controlled Playwright/CDP scenario driver with exact process ownership. */
export class PlaywrightBrowserScenarioProvider
implements BrowserScenarioCapturePort
{
constructor(
private readonly factory: BrowserScenarioSessionFactory = new PlaywrightScenarioSessionFactory(),
) {}
identity(): ProviderIdentity {
return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY;
}
async captureScenario(
scenario: BrowserScenario,
options: ExecutionOptions = {},
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
try {
return ok(await runScenario(this.factory, scenario, options));
} catch (cause) {
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
OPERATION,
{ cause },
),
);
}
}
}
@@ -0,0 +1,54 @@
import {
AnalysisCancelledError,
AnalysisTimeoutError,
} from "../domain/errors.js";
const OPERATION = "capture_browser_scenario" as const;
export const withPlaywrightExecutionBoundary = <Value>(
work: () => Promise<Value>,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<Value> => {
if (maximumTimeoutMs <= 0)
return Promise.reject(
new AnalysisTimeoutError(OPERATION, maximumTimeoutMs),
);
if (signal?.aborted === true)
return Promise.reject(new AnalysisCancelledError(OPERATION));
return new Promise<Value>((resolve, reject) => {
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = (): void => {
if (timer !== undefined) clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
};
const succeed = (value: Value): void => {
if (settled) return;
settled = true;
cleanup();
resolve(value);
};
const fail = (error: unknown): void => {
if (settled) return;
settled = true;
cleanup();
reject(error);
};
const onAbort = (): void => {
fail(new AnalysisCancelledError(OPERATION));
};
timer = setTimeout(
() => fail(new AnalysisTimeoutError(OPERATION, maximumTimeoutMs)),
maximumTimeoutMs,
);
timer.unref();
signal?.addEventListener("abort", onAbort, { once: true });
if (signal?.aborted === true) {
onAbort();
return;
}
void work().then(succeed, fail);
});
};
+96
View File
@@ -0,0 +1,96 @@
import type { Locator, Page } from "playwright-core";
import type {
BrowserScenarioAction,
BrowserScenarioValue,
} from "../domain/browserScenario.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
type ScenarioLocator = Extract<
BrowserScenarioAction,
{ readonly locator: unknown }
>["locator"];
const resolveLocator = (page: Page, locator: ScenarioLocator): Locator => {
switch (locator.kind) {
case "test_id":
return page.getByTestId(locator.value);
case "role":
return page.getByRole(locator.role, {
name: locator.name,
exact: locator.exact,
});
case "css":
return page.locator(locator.selector);
}
};
const resolveValue = (
value: BrowserScenarioValue,
secrets: BrowserScenarioSecrets,
): string => secrets.value(value);
interface PerformActionInput {
readonly page: Page;
readonly action: BrowserScenarioAction;
readonly secrets: BrowserScenarioSecrets;
readonly defaultTimeoutMs: number;
readonly maximumTimeoutMs: number;
}
/** Execute one admitted declarative action with no caller-supplied code. */
export const performPlaywrightScenarioAction = async (
input: PerformActionInput,
): Promise<void> => {
const { page, action, secrets, defaultTimeoutMs, maximumTimeoutMs } = input;
const timeout = "timeout_ms" in action ? action.timeout_ms : undefined;
const options = {
timeout: Math.min(timeout ?? defaultTimeoutMs, maximumTimeoutMs),
};
switch (action.action) {
case "goto":
await page.goto(secrets.url(action.destination), {
timeout: options.timeout,
waitUntil: action.wait_until,
});
return;
case "click":
await resolveLocator(page, action.locator).click({
...options,
button: action.button,
clickCount: action.click_count,
});
return;
case "fill":
await resolveLocator(page, action.locator).fill(
resolveValue(action.value, secrets),
options,
);
return;
case "press":
await resolveLocator(page, action.locator).press(action.key, options);
return;
case "select_option":
await resolveLocator(page, action.locator).selectOption(
resolveValue(action.value, secrets),
options,
);
return;
case "check":
await resolveLocator(page, action.locator).check(options);
return;
case "uncheck":
await resolveLocator(page, action.locator).uncheck(options);
return;
case "wait_for":
await resolveLocator(page, action.locator).waitFor({
...options,
state: action.state,
});
return;
case "wait_for_timeout":
if (action.duration_ms > maximumTimeoutMs)
throw new Error("Scenario duration limit reached");
await page.waitForTimeout(action.duration_ms);
}
};
+349
View File
@@ -0,0 +1,349 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import type { BrowserContext, Page } from "playwright-core";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import {
browserStepArtifactsSchema,
type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
const TEXT_ARTIFACT_MAX_BYTES = 1_048_576;
const historyValueSchema = z.strictObject({
length: z.number().int().min(0),
navigation_entries: z
.array(
z.strictObject({
type: z.string(),
name: z.string(),
}),
)
.max(10_000),
});
const storageValueSchema = z.strictObject({
local_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
session_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
/** Shared retained-count budget for one scenario's screenshot artifacts. */
export class BrowserScenarioCaptureBudget {
private screenshotCount = 0;
private metadataBytes = 0;
constructor(
private readonly maximumScreenshots: number,
private readonly maximumMetadataBytes: number,
) {}
claimScreenshot(): boolean {
if (this.screenshotCount >= this.maximumScreenshots) return false;
this.screenshotCount += 1;
return true;
}
claimMetadata(bytes: number): boolean {
if (this.metadataBytes + bytes > this.maximumMetadataBytes) return false;
this.metadataBytes += bytes;
return true;
}
}
const notRequested = () => ({ state: "not_requested" as const });
const missing = (reason: string) => ({ state: "missing" as const, reason });
const truncated = (observed: number, retained: number, reason: string) => ({
state: "truncated" as const,
observed,
retained,
reason,
});
const textArtifact = (
text: string,
maximumBytes: number,
budget: BrowserScenarioCaptureBudget,
) => {
const bytes = Buffer.from(text);
if (bytes.byteLength > maximumBytes)
return truncated(
bytes.byteLength,
0,
`artifact exceeds ${maximumBytes} bytes`,
);
if (!budget.claimMetadata(bytes.byteLength))
return truncated(
bytes.byteLength,
0,
"scenario metadata byte limit reached",
);
return {
state: "captured" as const,
value: {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
text,
},
};
};
const captureScreenshot = async (
page: Page,
scenario: BrowserScenario,
budget: BrowserScenarioCaptureBudget,
) => {
if (!budget.claimScreenshot())
return truncated(1, 0, "scenario screenshot count limit reached");
try {
const bytes = await page.screenshot({
type: "png",
fullPage: false,
animations: "disabled",
caret: "hide",
});
if (bytes.byteLength > scenario.limits.max_screenshot_bytes)
return truncated(bytes.byteLength, 0, "screenshot byte limit reached");
const sha256 = createHash("sha256").update(bytes).digest("hex");
return {
state: "captured" as const,
value: {
uri: `rea://web-screenshot/sha256/${sha256}`,
sha256,
bytes: bytes.byteLength,
media_type: "image/png" as const,
data_base64: bytes.toString("base64"),
},
};
} catch {
return missing("screenshot capture failed");
}
};
const captureDom = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
try {
const nodes = await page.locator("*").count();
if (nodes > maximumNodes)
return truncated(nodes, 0, "DOM node limit reached");
return textArtifact(
secrets.redact(await page.content()),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
} catch {
return missing("DOM capture failed");
}
};
const captureAccessibility = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
try {
const text = await page.locator("html").ariaSnapshot();
const nodes = text.split("\n").filter((line) => line.trim() !== "").length;
if (nodes > maximumNodes)
return truncated(nodes, 0, "accessibility node limit reached");
return textArtifact(
secrets.redact(text),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
} catch {
return missing("accessibility capture failed");
}
};
const navigationType = (
value: string,
): "navigate" | "reload" | "back_forward" | "prerender" | "unknown" => {
switch (value) {
case "navigate":
case "reload":
case "back_forward":
case "prerender":
return value;
default:
return "unknown";
}
};
const captureHistory = async (
page: Page,
budget: BrowserScenarioCaptureBudget,
) => {
try {
const raw = historyValueSchema.parse(
await page.evaluate(`(() => ({
length: window.history.length,
navigation_entries: performance.getEntriesByType("navigation").map(
entry => ({
type: typeof entry.type === "string" ? entry.type : "unknown",
name: entry.name
})
)
}))()`),
);
if (raw.navigation_entries.length > 256)
return truncated(
raw.navigation_entries.length,
0,
"navigation history entry limit reached",
);
const value = {
length: raw.length,
current_url: sanitizeBrowserUrl(page.url()),
navigation_entries: raw.navigation_entries.map(({ type, name }) => ({
type: navigationType(type),
name: sanitizeBrowserUrl(name),
})),
};
const bytes = Buffer.byteLength(JSON.stringify(value));
if (!budget.claimMetadata(bytes))
return truncated(bytes, 0, "scenario metadata byte limit reached");
return {
state: "captured" as const,
value,
};
} catch {
return missing("history capture failed");
}
};
const captureStorage = async (input: {
readonly context: BrowserContext;
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { context, page, scenario, secrets, budget } = input;
try {
const cookies = await context.cookies(scenario.allowed_origins);
const pageStorage = storageValueSchema.parse(
await page.evaluate(`(() => ({
local_storage: Object.entries(window.localStorage),
session_storage: Object.entries(window.sessionStorage)
}))()`),
);
const observed =
cookies.length +
pageStorage.local_storage.length +
pageStorage.session_storage.length;
if (observed > scenario.limits.max_storage_entries)
return truncated(observed, 0, "storage entry limit reached");
const value = {
cookies: cookies.map((cookie) => ({
name: cookie.name,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
http_only: cookie.httpOnly,
same_site: cookie.sameSite,
...secrets.fingerprint(cookie.value),
})),
local_storage: pageStorage.local_storage.map(([name, value]) => ({
name,
...secrets.fingerprint(value),
})),
session_storage: pageStorage.session_storage.map(([name, value]) => ({
name,
...secrets.fingerprint(value),
})),
};
const bytes = Buffer.byteLength(JSON.stringify(value));
if (!budget.claimMetadata(bytes))
return truncated(bytes, 0, "scenario metadata byte limit reached");
return {
state: "captured" as const,
value,
};
} catch {
return missing("storage capture failed");
}
};
const isAllowedPage = (
page: Page,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(page.url()).origin);
} catch {
return false;
}
};
/** Capture selected step artifacts without retaining data after scope loss. */
export const capturePlaywrightStepArtifacts = async (input: {
readonly context: BrowserContext;
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly requested: ReadonlySet<SnapshotKind>;
readonly budget: BrowserScenarioCaptureBudget;
}): Promise<BrowserStepArtifacts> => {
const { context, page, scenario, secrets, requested, budget } = input;
const allowed = isAllowedPage(page, new Set(scenario.allowed_origins));
const denied = () => missing("current page is outside approved origins");
const state = <Value>(
kind: SnapshotKind,
capture: () => Promise<Value>,
): Promise<
Value | ReturnType<typeof notRequested> | ReturnType<typeof missing>
> =>
!requested.has(kind)
? Promise.resolve(notRequested())
: allowed || kind === "url"
? capture()
: Promise.resolve(denied());
return browserStepArtifactsSchema.parse({
screenshot: await state("screenshot", () =>
captureScreenshot(page, scenario, budget),
),
dom: await state("dom", () =>
captureDom({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_dom_nodes,
budget,
}),
),
accessibility: await state("accessibility", () =>
captureAccessibility({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_accessibility_nodes,
budget,
}),
),
url: await state("url", async () => {
const value = sanitizeBrowserUrl(page.url());
const bytes = Buffer.byteLength(JSON.stringify(value));
return budget.claimMetadata(bytes)
? { state: "captured" as const, value }
: truncated(bytes, 0, "scenario metadata byte limit reached");
}),
history: await state("history", () => captureHistory(page, budget)),
storage: await state("storage", () =>
captureStorage({ context, page, scenario, secrets, budget }),
),
});
};
+189
View File
@@ -0,0 +1,189 @@
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
chromium,
type Browser,
type BrowserContext,
type Page,
} from "playwright-core";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { BrowserObservationError } from "../domain/errors.js";
const OPERATION = "capture_browser_scenario" as const;
export interface OpenedScenarioBrowser {
readonly context: BrowserContext;
readonly page: Page;
readonly browser: Browser;
readonly profilePath: string | undefined;
}
const allowedBrowserEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
): Record<string, string | undefined> => {
const allowed = [
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"HOME",
"LANG",
"LD_LIBRARY_PATH",
"PATH",
"SystemRoot",
"TEMP",
"TMP",
"TMPDIR",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
];
return Object.fromEntries(
allowed
.map((name) => [name, environment[name]] as const)
.filter(
(entry): entry is readonly [string, string] => entry[1] !== undefined,
),
);
};
const originAllowed = (
value: string,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(value).origin);
} catch {
return false;
}
};
const findConnectedPage = async (
browser: Browser,
targetId: string,
allowedOrigins: ReadonlySet<string>,
): Promise<{ readonly context: BrowserContext; readonly page: Page }> => {
for (const context of browser.contexts())
for (const page of context.pages()) {
const session = await context.newCDPSession(page);
try {
const { targetInfo } = await session.send("Target.getTargetInfo");
if (targetInfo.targetId !== targetId) continue;
if (
page.url() !== "about:blank" &&
!originAllowed(page.url(), allowedOrigins)
)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
return { context, page };
} finally {
await session.detach();
}
}
throw new BrowserObservationError(OPERATION, "target_not_found");
};
const configureAttachedEnvironment = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
): Promise<void> => {
await page.setViewportSize({
width: scenario.environment.viewport.width,
height: scenario.environment.viewport.height,
});
await page.emulateMedia({
colorScheme: scenario.environment.color_scheme,
reducedMotion: scenario.environment.reduced_motion,
});
const session = await context.newCDPSession(page);
try {
await session.send("Emulation.setLocaleOverride", {
locale: scenario.environment.locale,
});
await session.send("Emulation.setTimezoneOverride", {
timezoneId: scenario.environment.timezone,
});
} finally {
await session.detach();
}
};
export const openPlaywrightScenarioBrowser = async (
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
maximumTimeoutMs: number,
): Promise<OpenedScenarioBrowser> => {
if (scenario.browser.mode === "connect") {
const browser = await chromium.connectOverCDP(
scenario.browser.cdp_endpoint,
{
timeout: Math.min(
scenario.limits.navigation_timeout_ms,
maximumTimeoutMs,
),
},
);
try {
const target = await findConnectedPage(
browser,
scenario.browser.target_id,
new Set(scenario.allowed_origins),
);
await configureAttachedEnvironment(target.context, target.page, scenario);
return { ...target, browser, profilePath: undefined };
} catch (error) {
await browser.close();
throw error;
}
}
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
await chmod(profilePath, 0o700);
try {
const context = await chromium.launchPersistentContext(profilePath, {
executablePath: scenario.browser.executable_path,
headless: true,
acceptDownloads: false,
viewport: {
width: scenario.environment.viewport.width,
height: scenario.environment.viewport.height,
},
deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
locale: scenario.environment.locale,
timezoneId: scenario.environment.timezone,
colorScheme: scenario.environment.color_scheme,
reducedMotion: scenario.environment.reduced_motion,
serviceWorkers: "block",
env: allowedBrowserEnvironment(environment),
handleSIGHUP: false,
handleSIGINT: false,
handleSIGTERM: false,
timeout: maximumTimeoutMs,
});
const browser = context.browser();
if (browser === null) {
await context.close();
throw new BrowserObservationError(OPERATION, "protocol_error");
}
const page = context.pages()[0] ?? (await context.newPage());
return { context, page, browser, profilePath };
} catch (error) {
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
throw error;
}
};
export const closePlaywrightScenarioBrowser = async ({
context,
browser,
profilePath,
}: OpenedScenarioBrowser): Promise<void> => {
try {
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
}
};
+313
View File
@@ -0,0 +1,313 @@
import type {
ConsoleMessage,
Download,
Frame,
Page,
Request,
Response,
WebSocket,
Worker,
} from "playwright-core";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
browserScenarioEventSchema,
type BrowserScenarioEvent,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
type EventName =
| "console"
| "page-errors"
| "network"
| "websockets"
| "frames"
| "workers"
| "popups"
| "downloads";
type UnindexedEvent = BrowserScenarioEvent extends infer Event
? Event extends BrowserScenarioEvent
? Omit<Event, "sequence" | "step_index">
: never
: never;
type LimitedSection = "frames" | "workers" | "popups" | "websockets";
type TruncatedSection = "events" | LimitedSection;
interface EventCaptureOptions {
readonly page: Page;
readonly enabled: ReadonlySet<EventName>;
readonly limits: Pick<
BrowserScenario["limits"],
| "max_events"
| "max_frames"
| "max_workers"
| "max_popups"
| "max_websockets"
>;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
}
/** Bounded, arrival-ordered Playwright event capture with current-step attribution. */
export class PlaywrightScenarioEvents {
private readonly items: BrowserScenarioEvent[] = [];
private readonly truncated = new Set<TruncatedSection>();
private readonly admitted = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly rejected = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly counts: Record<LimitedSection, number> = {
frames: 0,
workers: 0,
popups: 0,
websockets: 0,
};
private dropped = 0;
private stepIndex = 0;
private sequence = 0;
private readonly enabled: ReadonlySet<EventName>;
private readonly limits: EventCaptureOptions["limits"];
private readonly secrets: BrowserScenarioSecrets;
private readonly budget: BrowserScenarioCaptureBudget;
constructor(options: EventCaptureOptions) {
this.enabled = options.enabled;
this.limits = options.limits;
this.secrets = options.secrets;
this.budget = options.budget;
this.observePage(options.page);
}
setStep(index: number): void {
this.stepIndex = index;
}
nextSequence(): number {
return this.sequence + 1;
}
lastSequence(): number {
return this.sequence;
}
result(): {
readonly retained: number;
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
} {
return {
retained: this.items.length,
dropped: this.dropped,
items: this.items,
};
}
truncationSections(): readonly TruncatedSection[] {
return [...this.truncated].sort();
}
private push(event: UnindexedEvent): void {
this.sequence += 1;
if (this.items.length >= this.limits.max_events) {
this.dropped += 1;
this.truncated.add("events");
return;
}
const parsed = browserScenarioEventSchema.parse({
...event,
sequence: this.sequence,
step_index: this.stepIndex,
});
if (!this.budget.claimMetadata(Buffer.byteLength(JSON.stringify(parsed)))) {
this.dropped += 1;
this.truncated.add("events");
return;
}
this.items.push(parsed);
}
private admit(
section: LimitedSection,
value: object,
maximum: number,
): boolean {
if (this.admitted[section].has(value)) return true;
if (this.rejected[section].has(value)) return false;
if (this.counts[section] >= maximum) {
this.rejected[section].add(value);
this.sequence += 1;
this.dropped += 1;
this.truncated.add("events");
this.truncated.add(section);
return false;
}
this.admitted[section].add(value);
this.counts[section] += 1;
return true;
}
private observePage(page: Page): void {
if (this.enabled.has("console"))
page.on("console", (message) => this.console(message));
if (this.enabled.has("page-errors"))
page.on("pageerror", (error) =>
this.push({
kind: "page-error",
message: this.secrets.redact(error.message),
stack:
error.stack === undefined ? null : this.secrets.redact(error.stack),
}),
);
if (this.enabled.has("network")) {
page.on("request", (request) => this.request("request", request));
page.on("response", (response) => this.response(response));
page.on("requestfailed", (request) =>
this.request("request-failed", request),
);
}
if (this.enabled.has("websockets"))
page.on("websocket", (socket) => this.webSocket(socket));
if (this.enabled.has("frames")) {
page.on("frameattached", (frame) => this.frame("frame-attached", frame));
page.on("framedetached", (frame) => this.frame("frame-detached", frame));
page.on("framenavigated", (frame) =>
this.frame("frame-navigated", frame),
);
}
if (this.enabled.has("workers"))
page.on("worker", (worker) => this.worker(worker));
if (this.enabled.has("popups"))
page.on("popup", (popup) => this.popup(popup));
if (this.enabled.has("downloads"))
page.on("download", (download) => this.download(download));
}
private console(message: ConsoleMessage): void {
const location = message.location();
this.push({
kind: "console",
level: message.type(),
text: this.secrets.redact(message.text()).slice(0, 65_536),
url: location.url === "" ? null : sanitizeBrowserUrl(location.url),
});
}
private request(kind: "request" | "request-failed", request: Request): void {
this.push({
kind,
method: request.method(),
url: sanitizeBrowserUrl(request.url()),
resource_type: request.resourceType(),
status: null,
header_names: Object.keys(request.headers()).sort().slice(0, 256),
failure:
kind === "request-failed"
? (request.failure()?.errorText ?? "unknown")
: null,
});
}
private response(response: Response): void {
const request = response.request();
this.push({
kind: "response",
method: request.method(),
url: sanitizeBrowserUrl(response.url()),
resource_type: request.resourceType(),
status: response.status(),
header_names: Object.keys(response.headers()).sort().slice(0, 256),
failure: null,
});
}
private webSocket(socket: WebSocket): void {
if (!this.admit("websockets", socket, this.limits.max_websockets)) return;
const url = sanitizeBrowserUrl(socket.url());
this.push({ kind: "websocket-opened", url });
socket.on("framesent", ({ payload }) =>
this.webSocketFrame("websocket-frame-sent", url, payload),
);
socket.on("framereceived", ({ payload }) =>
this.webSocketFrame("websocket-frame-received", url, payload),
);
socket.on("close", () => this.push({ kind: "websocket-closed", url }));
}
private webSocketFrame(
kind: "websocket-frame-sent" | "websocket-frame-received",
url: ReturnType<typeof sanitizeBrowserUrl>,
payload: string | Buffer,
): void {
const bytes = Buffer.byteLength(payload);
const isText = typeof payload === "string";
const text = isText ? this.secrets.redact(payload).slice(0, 65_536) : null;
this.push({
kind,
url,
payload_type: isText ? "text" : "binary",
payload_bytes: bytes,
payload_text: text,
truncated: isText && text !== null && text.length < payload.length,
});
}
private frame(
kind: "frame-attached" | "frame-detached" | "frame-navigated",
frame: Frame,
): void {
if (!this.admit("frames", frame, this.limits.max_frames)) return;
this.push({
kind,
url: frame.url() === "" ? null : sanitizeBrowserUrl(frame.url()),
name: frame.name() || null,
});
}
private worker(worker: Worker): void {
if (!this.admit("workers", worker, this.limits.max_workers)) return;
const details = {
url: sanitizeBrowserUrl(worker.url()),
name: null,
};
this.push({ kind: "worker-created", ...details });
worker.on("close", () => this.push({ kind: "worker-closed", ...details }));
}
private popup(page: Page): void {
if (!this.admit("popups", page, this.limits.max_popups)) return;
const opened = {
url: page.url() === "" ? null : sanitizeBrowserUrl(page.url()),
name: null,
};
this.push({ kind: "popup-opened", ...opened });
page.on("close", () =>
this.push({
kind: "popup-closed",
url: page.url() === "" ? null : sanitizeBrowserUrl(page.url()),
name: null,
}),
);
this.observePage(page);
}
private download(download: Download): void {
this.push({
kind: "download-cancelled",
suggested_filename: download.suggestedFilename().slice(0, 1_024),
url: sanitizeBrowserUrl(download.url()),
});
void download.cancel().catch(() => undefined);
}
}
+407
View File
@@ -0,0 +1,407 @@
import {
type BrowserContext,
type Page,
type Route,
type WebSocketRoute,
} from "playwright-core";
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import { BrowserObservationError } from "../domain/errors.js";
import type {
BrowserScenarioSessionFactory,
BrowserScenarioSessionPort,
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import {
closePlaywrightScenarioBrowser,
openPlaywrightScenarioBrowser,
type OpenedScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";
import {
BrowserScenarioCaptureBudget,
capturePlaywrightStepArtifacts,
} from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
const OPERATION = "capture_browser_scenario" as const;
const originAllowed = (
value: string,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(value).origin);
} catch {
return false;
}
};
const installStorageSeeds = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
secrets: BrowserScenarioSecrets,
): Promise<void> => {
await context.addCookies(
scenario.storage.cookies.map((cookie) => ({
name: cookie.name,
value: secrets.value(cookie.value),
url: secrets.url(cookie.destination),
httpOnly: cookie.http_only,
secure: cookie.secure,
sameSite: cookie.same_site,
})),
);
const storage = {
local: Object.fromEntries(
scenario.storage.local_storage.map(({ origin, entries }) => [
origin,
entries.map(({ name, value }) => [name, secrets.value(value)]),
]),
),
session: Object.fromEntries(
scenario.storage.session_storage.map(({ origin, entries }) => [
origin,
entries.map(({ name, value }) => [name, secrets.value(value)]),
]),
),
};
const payload = JSON.stringify(storage).replaceAll("<", "\\u003c");
await page.addInitScript(`(() => {
const seeds = ${payload};
const local = seeds.local[window.location.origin] ?? [];
const session = seeds.session[window.location.origin] ?? [];
for (const [name, value] of local) window.localStorage.setItem(name, value);
for (const [name, value] of session)
window.sessionStorage.setItem(name, value);
})()`);
};
const installHttpPolicy = async (input: {
readonly context: BrowserContext;
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly ownedPages: Set<Page>;
}): Promise<void> => {
const { context, page, scenario, secrets, ownedPages } = input;
const routes =
scenario.request_replay.mode === "exact"
? new Map(
scenario.request_replay.routes.map((route) => [
`${route.method} ${secrets.url(route.request)}`,
route,
]),
)
: new Map();
await context.route("**/*", async (route, request) => {
let requestPage: Page | undefined;
try {
requestPage = request.frame().page();
} catch {
requestPage = undefined;
}
if (
scenario.browser.mode === "connect" &&
(requestPage === undefined || !ownedPages.has(requestPage))
) {
await route.continue();
return;
}
if (!originAllowed(request.url(), new Set(scenario.allowed_origins))) {
await route.abort("blockedbyclient");
return;
}
const replay = routes.get(`${request.method()} ${request.url()}`);
if (replay !== undefined) {
await fulfillReplayRoute(route, replay.response, secrets);
return;
}
if (
scenario.request_replay.mode === "exact" &&
scenario.request_replay.unmatched === "abort"
) {
await route.abort("blockedbyclient");
return;
}
await route.continue();
});
page.on("popup", (popup) => ownedPages.add(popup));
};
type ReplayResponse = Extract<
BrowserScenario["request_replay"],
{ readonly mode: "exact" }
>["routes"][number]["response"];
const fulfillReplayRoute = async (
route: Route,
response: ReplayResponse,
secrets: BrowserScenarioSecrets,
): Promise<void> => {
if (response.kind === "redirect") {
await route.fulfill({
status: response.status,
headers: { location: secrets.url(response.destination) },
});
return;
}
await route.fulfill({
status: response.status,
headers: Object.fromEntries(
response.headers.map(({ name, value }) => [name, secrets.value(value)]),
),
...(response.body === undefined
? {}
: { body: secrets.value(response.body) }),
});
};
const installWebSocketPolicy = async (
page: Page,
scenario: BrowserScenario,
): Promise<void> => {
const allowed = new Set(scenario.allowed_origins);
await page.routeWebSocket("**/*", async (route: WebSocketRoute) => {
const url = new URL(route.url());
const httpOrigin = `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}`;
if (
!allowed.has(httpOrigin) ||
(scenario.request_replay.mode === "exact" &&
scenario.request_replay.unmatched === "abort")
) {
await route.close({ code: 1008, reason: "outside scenario policy" });
return;
}
route.connectToServer();
});
};
const initializePage = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
secrets: BrowserScenarioSecrets,
): Promise<Set<Page>> => {
context.setDefaultTimeout(scenario.limits.action_timeout_ms);
context.setDefaultNavigationTimeout(scenario.limits.navigation_timeout_ms);
const ownedPages = new Set([page]);
await installHttpPolicy({ context, page, scenario, secrets, ownedPages });
await installWebSocketPolicy(page, scenario);
await installStorageSeeds(context, page, scenario, secrets);
return ownedPages;
};
export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly mode: "launch" | "connect";
readonly processOwnership: "provider-owned" | "external";
readonly product = "Chromium";
readonly version: string;
readonly initialUrl: string;
private closed = false;
private constructor(
private readonly opened: OpenedScenarioBrowser,
private readonly scenario: BrowserScenario,
private readonly secrets: BrowserScenarioSecrets,
private readonly eventCapture: PlaywrightScenarioEvents,
) {
this.mode = scenario.browser.mode;
this.processOwnership =
scenario.browser.mode === "launch" ? "provider-owned" : "external";
this.version = opened.browser.version();
this.initialUrl = opened.page.url();
}
static async open(
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
options: {
readonly signal?: AbortSignal;
readonly budget: BrowserScenarioCaptureBudget;
readonly deadlineAt: number;
},
): Promise<PlaywrightScenarioSession> {
const remaining = (): number => options.deadlineAt - Date.now();
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
if (secrets === undefined)
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const opening = openPlaywrightScenarioBrowser(
scenario,
environment,
remaining(),
);
let opened: OpenedScenarioBrowser;
try {
opened = await withPlaywrightExecutionBoundary(
() => opening,
remaining(),
options.signal,
);
} catch (error) {
void opening
.then((lateOpened) => closePlaywrightScenarioBrowser(lateOpened))
.catch(() => undefined);
throw error;
}
try {
await withPlaywrightExecutionBoundary(
() => initializePage(opened.context, opened.page, scenario, secrets),
remaining(),
options.signal,
);
const events = new PlaywrightScenarioEvents({
page: opened.page,
enabled: new Set(scenario.capture.events),
limits: scenario.limits,
secrets,
budget: options.budget,
});
const session = new PlaywrightScenarioSession(
opened,
scenario,
secrets,
events,
);
await withPlaywrightExecutionBoundary(
() =>
opened.page.goto(secrets.url(scenario.start_url), {
waitUntil: "load",
timeout: Math.min(
scenario.limits.navigation_timeout_ms,
remaining(),
),
}),
remaining(),
options.signal,
);
return session;
} catch (error) {
await closePlaywrightScenarioBrowser(opened);
throw error;
}
}
currentUrl(): string {
return this.opened.page.url();
}
setStep(index: number): void {
this.eventCapture.setStep(index);
}
nextEventSequence(): number {
return this.eventCapture.nextSequence();
}
lastEventSequence(): number {
return this.eventCapture.lastSequence();
}
events() {
return this.eventCapture.result();
}
eventTruncationSections() {
return this.eventCapture.truncationSections();
}
async perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<void> {
await withPlaywrightExecutionBoundary(
() =>
performPlaywrightScenarioAction({
page: this.opened.page,
action,
secrets: this.secrets,
defaultTimeoutMs: this.scenario.limits.action_timeout_ms,
maximumTimeoutMs,
}),
maximumTimeoutMs,
signal,
);
}
async capture(
requested: ReadonlySet<
BrowserScenario["capture"]["after_each_step"][number]
>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
) {
return withPlaywrightExecutionBoundary(
() =>
capturePlaywrightStepArtifacts({
context: this.opened.context,
page: this.opened.page,
scenario: this.scenario,
secrets: this.secrets,
requested,
budget,
}),
maximumTimeoutMs,
signal,
);
}
async close() {
if (this.closed)
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
this.closed = true;
await closePlaywrightScenarioBrowser(this.opened);
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
}
redactError(error: unknown): string {
return this.secrets
.redact(error instanceof Error ? error.message : "browser action failed")
.slice(0, 4_096);
}
}
/** Production Playwright/CDP session factory. */
export class PlaywrightScenarioSessionFactory
implements BrowserScenarioSessionFactory
{
constructor(
private readonly environment: Readonly<
Record<string, string | undefined>
> = process.env,
) {}
open(
scenario: BrowserScenario,
options: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
} = {},
): Promise<BrowserScenarioSessionPort> {
return PlaywrightScenarioSession.open(scenario, this.environment, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget:
options.budget ??
new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
),
deadlineAt:
options.deadlineAt ?? Date.now() + scenario.limits.max_duration_ms,
});
}
}