@locusqa/runner 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +105 -0
- package/README.md +50 -2
- package/bin/locus-runner +5492 -0
- package/bin/locus-runner.map +7 -0
- package/package.json +18 -4
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/cli.ts", "../src/concurrency.ts", "../src/engine-bundle.ts", "../src/executor.ts", "../src/browsers.ts", "../src/row-values.ts", "../src/placeholder-files.ts", "../src/locator-agreement.ts", "../src/host-guard.ts", "../src/trace-redaction.ts", "../src/screenshot-hide.ts", "../src/secret-screen.ts", "../src/exports.ts", "../src/generated-values.ts", "../src/target-reader.ts", "../src/target-verification.ts", "../src/dialogs.ts", "../src/conditions.ts", "../src/near-match.ts", "../src/logger.ts", "../src/dashboard-client.ts", "../src/runner-client.ts", "../src/junit.ts", "../src/local-consumer.ts"],
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\nimport { realpathSync, writeFileSync } from 'node:fs';\nimport { cpus, freemem } from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport { parseArgs } from 'node:util';\nimport { resolveConcurrency } from './concurrency.js';\nimport { loadEngineBundle } from './engine-bundle.js';\nimport { Executor } from './executor.js';\nimport { createLogger, type LogLevel } from './logger.js';\nimport { RunnerClient, RUNNER_VERSION } from './runner-client.js';\nimport { LocalRunnerConsumer } from './local-consumer.js';\nimport { generateJUnitXml, type RunSummary } from './junit.js';\nimport type { BrowserName } from './browsers.js';\n\n/**\n * Service identifier for log entries.\n */\nconst SERVICE_NAME = 'locus-runner';\n\n/**\n * Prints CLI usage instructions and available commands to stdout.\n *\n * What it does: outputs human-readable help text detailing run and listen commands.\n * How it works: writes directly to process.stdout.\n */\nexport function printHelp(): void {\n const helpText = `\nLocus Replay Runner v${RUNNER_VERSION}\nA customer-run Playwright test runner executing against the Locus platform.\n\nUsage:\n locus-runner <command> [options]\n\nCommands:\n run Start or execute a test collection run, stream results, and exit\n listen Continuously poll and execute local runs for your tenant\n\nOptions for 'run':\n --base-url <url> Locus API Gateway URL (or LOCUS_BASE_URL, default: http://localhost:9280)\n --token <token> Runner API token with RoleRunner (or LOCUS_TOKEN)\n --site <id> Target site ID\n --env <slug> Environment slug (e.g. staging, prod)\n --test-case <id...> One or more test case IDs (comma-separated or repeated)\n --folder <id> Pipeline or folder ID\n --all Run all active test cases in the site\n --collection-run <id> Target an existing collection run instead of creating one\n --browser <name> Browser to execute ('chromium' or 'firefox', default: chromium)\n --concurrency <n> Concurrent browsers (default: 1; lowered automatically to fit this machine, at most 4)\n --junit <path> Write standard JUnit XML report to file path upon completion\n --log-level <level> Log level: debug | info | warn | error (default: info)\n --help, -h Show this help message\n --version, -v Show runner version\n\nOptions for 'listen':\n --base-url <url> Locus API Gateway URL (or LOCUS_BASE_URL, default: http://localhost:9280)\n --token <token> Runner API token with RoleRunner (or LOCUS_TOKEN)\n --concurrency <n> Concurrent browsers (default: 1; lowered automatically to fit this machine, at most 4)\n --log-level <level> Log level: debug | info | warn | error (default: info)\n --help, -h Show this help message\n\nExamples:\n locus-runner run --site 6735... --env staging --all --token locus_tok_...\n locus-runner run --collection-run 6736... --token locus_tok_... --junit junit.xml\n locus-runner listen --token locus_tok_...\n`;\n process.stdout.write(helpText);\n}\n\n/**\n * Parsed configuration arguments for the run command.\n *\n * What it is: structured CLI arguments for execution in run mode.\n * What it does: carries connection credentials, targets, and reporting options.\n * How it works: normalized from command-line arguments and environment variables.\n */\nexport interface RunCommandOptions {\n baseUrl: string;\n token: string;\n siteId?: string | undefined;\n envSlug?: string | undefined;\n testCaseIds?: string[] | undefined;\n folderId?: string | undefined;\n all?: boolean | undefined;\n collectionRunId?: string | undefined;\n browser: BrowserName;\n concurrency: number;\n junitPath?: string | undefined;\n logLevel: LogLevel;\n}\n\n/**\n * Parsed configuration arguments for the listen command.\n *\n * What it is: structured CLI arguments for execution in listen daemon mode.\n * What it does: carries connection credentials and concurrency settings.\n * How it works: normalized from command-line arguments and environment variables.\n */\nexport interface ListenCommandOptions {\n baseUrl: string;\n token: string;\n concurrency: number;\n logLevel: LogLevel;\n}\n\n/**\n * Optional browser and execution overrides for local customer runner replay.\n *\n * What it is: configurable overrides for local browser execution.\n * What it does: allows tests or specialized hosts to explicitly set browser paths and sandboxing.\n * How it works: passed to createLocalExecutor and merged with environment variable defaults.\n */\nexport interface LocalExecutorOptions {\n chromiumPath?: string | undefined;\n chromiumSandbox?: boolean | undefined;\n firefoxPath?: string | undefined;\n firefoxSandbox?: boolean | undefined;\n}\n\n/**\n * Builds the Executor instance configured for local customer-run replay.\n *\n * What it does: initializes the Playwright executor with local network safety policy.\n * How it works: loads the IIFE locator engine bundle, sets allowPrivateNetworks to true\n * (permitting customer private network and loopback access while blocking cloud metadata),\n * connects fixture downloading to the RunnerClient, and applies browser settings where\n * sandboxing defaults to false for CI/container compatibility unless explicitly enabled.\n */\nexport function createLocalExecutor(\n client: RunnerClient,\n logLevel: LogLevel,\n options?: LocalExecutorOptions,\n): Executor {\n const log = createLogger(SERVICE_NAME, logLevel, (line) => process.stdout.write(`${line}\\n`));\n const engineBundle = loadEngineBundle();\n\n const chromiumSandbox =\n options?.chromiumSandbox ?? process.env.LOCUS_RUNNER_CHROMIUM_SANDBOX === 'true';\n const firefoxSandbox =\n options?.firefoxSandbox ?? process.env.LOCUS_RUNNER_FIREFOX_SANDBOX === 'true';\n const chromiumPath = options?.chromiumPath ?? process.env.LOCUS_RUNNER_CHROMIUM_PATH ?? '';\n const firefoxPath = options?.firefoxPath ?? process.env.LOCUS_RUNNER_FIREFOX_PATH ?? '';\n\n return new Executor({\n chromiumPath,\n chromiumSandbox,\n firefoxPath,\n firefoxSandbox,\n enabledBrowsers: ['chromium', 'firefox'],\n stepTimeoutMs: 15000,\n settleTimeoutMs: 5000,\n settleQuietMs: 500,\n stepRetries: 1,\n nearMatch: {\n engineBundle,\n scanCap: 200,\n timeoutMs: 5000,\n minScore: 0.85,\n },\n runTimeoutMs: 300000,\n allowLoopback: true,\n allowPrivateNetworks: true,\n log,\n fetchFixture: (runId, fixtureId) => client.fixture(runId, fixtureId),\n });\n}\n\n/**\n * Executes the 'run' command: creates or connects to a collection run and executes it.\n *\n * What it does: manages targeted execution for CI pipelines; streams results; writes JUnit report.\n * How it works: triggers collection run if site specified; runs LocalRunnerConsumer until finished;\n * generates summary table; writes optional JUnit XML; exits 0 on success or 1 on test failure.\n */\nexport async function executeRunCommand(options: RunCommandOptions): Promise<number> {\n const log = createLogger(SERVICE_NAME, options.logLevel, (line) =>\n process.stdout.write(`${line}\\n`),\n );\n const client = new RunnerClient({\n baseUrl: options.baseUrl,\n token: options.token,\n });\n\n let collectionRunId = options.collectionRunId;\n\n if (!collectionRunId) {\n if (!options.siteId) {\n process.stderr.write(\n 'Error: either --collection-run <id> or --site <id> is required for run command.\\n',\n );\n return 1;\n }\n\n const trimmedSite = options.siteId.trim();\n if (!/^[0-9a-fA-F]{24}$/.test(trimmedSite) && !trimmedSite.startsWith('sk_')) {\n process.stderr.write(\n `Error: '${trimmedSite}' is not a valid 24-character hex Site ID or site key ('sk_...').\\n`,\n );\n return 1;\n }\n\n log.info('creating collection run for local execution', {\n event: 'create_collection_run',\n siteId: options.siteId,\n envSlug: options.envSlug,\n });\n\n try {\n const coll = await client.createCollectionRun({\n site_id: options.siteId,\n environment_slug: options.envSlug,\n test_case_ids: options.testCaseIds,\n folder_id: options.folderId,\n all: options.all,\n browser: options.browser,\n executor: 'local',\n });\n collectionRunId = coll.id;\n log.info('collection run created', {\n event: 'collection_created',\n collectionRunId,\n totalRuns: coll.total_runs,\n });\n } catch (err) {\n process.stderr.write(\n `Error creating collection run: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 1;\n }\n }\n\n const executor = createLocalExecutor(client, options.logLevel);\n const runsCompleted: RunSummary[] = [];\n\n const consumer = new LocalRunnerConsumer({\n client,\n executor,\n log,\n concurrency: options.concurrency,\n collectionRunId,\n onRunFinished: (summary) => {\n runsCompleted.push(summary);\n const icon = summary.status === 'passed' ? '\u2714' : '\u2716';\n const durationSec = (summary.durationMs / 1000).toFixed(1);\n const details = summary.errorMessage ? ` - ${summary.errorMessage}` : '';\n process.stdout.write(\n ` ${icon} [${summary.status.toUpperCase()}] ${summary.testCaseName} (${durationSec}s)${details}\\n`,\n );\n },\n });\n\n const abort = (): void => {\n log.info('abort requested by signal, draining active runs', { event: 'abort_signal' });\n void consumer.stop();\n };\n\n process.once('SIGINT', abort);\n process.once('SIGTERM', abort);\n\n process.stdout.write(`\\n\uD83D\uDE80 Locus Runner executing collection run: ${collectionRunId}\\n\\n`);\n\n try {\n await consumer.start();\n } catch (err) {\n process.stderr.write(\n `Consumer execution failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 1;\n }\n\n // Print execution summary report.\n let passedCount = 0;\n let failedCount = 0;\n for (const r of runsCompleted) {\n if (r.status === 'passed') passedCount++;\n else failedCount++;\n }\n\n process.stdout.write(\n `\\n\uD83D\uDCCA Summary: ${runsCompleted.length} tests executed, ${passedCount} passed, ${failedCount} failed.\\n`,\n );\n\n if (options.junitPath) {\n try {\n const xml = generateJUnitXml(`CollectionRun-${collectionRunId}`, runsCompleted);\n writeFileSync(options.junitPath, xml, 'utf8');\n process.stdout.write(`\uD83D\uDCC4 JUnit report written to: ${options.junitPath}\\n`);\n } catch (err) {\n process.stderr.write(\n `Warning: Failed to write JUnit report: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n\n return failedCount === 0 ? 0 : 1;\n}\n\n/**\n * Executes the 'listen' command: polls continuously for any ready local runs.\n *\n * What it does: runs an infinite worker loop claiming local runs across the tenant.\n * How it works: starts LocalRunnerConsumer in daemon mode without collectionRunId;\n * handles graceful shutdown on SIGINT and SIGTERM.\n */\nexport async function executeListenCommand(options: ListenCommandOptions): Promise<number> {\n const log = createLogger(SERVICE_NAME, options.logLevel, (line) =>\n process.stdout.write(`${line}\\n`),\n );\n const client = new RunnerClient({\n baseUrl: options.baseUrl,\n token: options.token,\n });\n\n const executor = createLocalExecutor(client, options.logLevel);\n\n const consumer = new LocalRunnerConsumer({\n client,\n executor,\n log,\n concurrency: options.concurrency,\n onRunFinished: (summary) => {\n const icon = summary.status === 'passed' ? '\u2714' : '\u2716';\n const durationSec = (summary.durationMs / 1000).toFixed(1);\n process.stdout.write(\n ` ${icon} [${summary.status.toUpperCase()}] ${summary.testCaseName} (${durationSec}s)\\n`,\n );\n },\n });\n\n process.stdout.write(\n `\\n\uD83C\uDFA7 Locus Runner listening for local test runs on ${options.baseUrl}...\\n`,\n );\n process.stdout.write(` (Press Ctrl+C to stop)\\n\\n`);\n\n const shutdown = (): void => {\n process.stdout.write('\\nStopping listener, draining active runs...\\n');\n void consumer.stop();\n };\n\n process.once('SIGINT', shutdown);\n process.once('SIGTERM', shutdown);\n\n try {\n await consumer.start();\n return 0;\n } catch (err) {\n process.stderr.write(\n `Listener encountered fatal error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 1;\n }\n}\n\n/**\n * Main command line entrypoint for locus-runner.\n *\n * What it does: parses arguments, validates required credentials, and routes to command handlers.\n * How it works: inspects process.argv; handles --help and --version; executes run or listen.\n */\nexport async function main(args: string[] = process.argv.slice(2)): Promise<number> {\n if (args.length === 0 || args.includes('--help') || args.includes('-h')) {\n printHelp();\n return 0;\n }\n\n if (args.includes('--version') || args.includes('-v')) {\n process.stdout.write(`v${RUNNER_VERSION}\\n`);\n return 0;\n }\n\n const command = args[0];\n const commandArgs = args.slice(1);\n\n const optionsConfig = {\n 'base-url': { type: 'string' as const },\n token: { type: 'string' as const },\n site: { type: 'string' as const },\n env: { type: 'string' as const },\n 'test-case': { type: 'string' as const, multiple: true },\n folder: { type: 'string' as const },\n all: { type: 'boolean' as const },\n 'collection-run': { type: 'string' as const },\n browser: { type: 'string' as const, default: 'chromium' },\n concurrency: { type: 'string' as const, default: '1' },\n junit: { type: 'string' as const },\n 'log-level': { type: 'string' as const, default: 'info' },\n };\n\n let values: ReturnType<typeof parseArgs>['values'];\n try {\n const parsed = parseArgs({\n args: commandArgs,\n options: optionsConfig,\n allowPositionals: false,\n });\n values = parsed.values;\n } catch (err) {\n process.stderr.write(`Argument error: ${err instanceof Error ? err.message : String(err)}\\n`);\n printHelp();\n return 1;\n }\n\n const baseUrl =\n (values['base-url'] as string) || process.env.LOCUS_BASE_URL || 'http://localhost:9280';\n const token = (values['token'] as string) || process.env.LOCUS_TOKEN || '';\n\n if (!token) {\n process.stderr.write(\n 'Error: Runner API token is required. Pass --token <token> or set LOCUS_TOKEN.\\n',\n );\n return 1;\n }\n\n const resolved = resolveConcurrency(\n parseInt((values['concurrency'] as string) || '1', 10),\n cpus().length,\n freemem(),\n );\n if (resolved.warning !== undefined) {\n process.stderr.write(`Warning: ${resolved.warning}\\n`);\n }\n const concurrency = resolved.value;\n const rawLogLevel = (values['log-level'] as string | undefined) ?? 'info';\n const logLevel: LogLevel =\n rawLogLevel === 'debug' || rawLogLevel === 'warn' || rawLogLevel === 'error'\n ? rawLogLevel\n : 'info';\n const rawBrowser = (values['browser'] as string | undefined) ?? 'chromium';\n const browser: BrowserName = rawBrowser === 'firefox' ? 'firefox' : 'chromium';\n\n if (command === 'run') {\n const rawTestCases = (values['test-case'] as string[]) ?? [];\n const testCaseIds: string[] = [];\n for (const item of rawTestCases) {\n for (const id of item.split(',')) {\n const trimmed = id.trim();\n if (trimmed) testCaseIds.push(trimmed);\n }\n }\n\n return executeRunCommand({\n baseUrl,\n token,\n siteId: values['site'] as string | undefined,\n envSlug: values['env'] as string | undefined,\n testCaseIds: testCaseIds.length > 0 ? testCaseIds : undefined,\n folderId: values['folder'] as string | undefined,\n all: Boolean(values['all']),\n collectionRunId: values['collection-run'] as string | undefined,\n browser,\n concurrency: concurrency,\n junitPath: values['junit'] as string | undefined,\n logLevel,\n });\n }\n\n if (command === 'listen') {\n return executeListenCommand({\n baseUrl,\n token,\n concurrency: concurrency,\n logLevel,\n });\n }\n\n process.stderr.write(\n `Error: Unknown command '${command}'. Supported commands: 'run', 'listen'.\\n`,\n );\n printHelp();\n return 1;\n}\n\n/**\n * isEntrypoint says whether this file was started directly (not imported by a test).\n *\n * What it does: compares the real path of this file with the real path of the script Node was\n * asked to run. Real paths matter because the Docker image and npm bin links start the runner\n * through a symlink, and a plain string comparison then wrongly says \"imported\", so the\n * command would exit silently without doing anything.\n */\nfunction isEntrypoint(): boolean {\n const started = process.argv[1];\n if (started === undefined) {\n return false;\n }\n return realpathSync(started) === realpathSync(fileURLToPath(import.meta.url));\n}\n\n// Only invoke main when executed directly as entrypoint.\nif (isEntrypoint()) {\n main().then(\n (code) => process.exit(code),\n (err: unknown) => {\n process.stderr.write(`Fatal error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n },\n );\n}\n", "/** Memory one browser slot is assumed to need, in bytes (a headless browser plus the page, about 1 GiB). */\nconst BYTES_PER_SLOT = 1024 * 1024 * 1024;\n\n/** The most slots ever allowed, however large the machine is. */\nconst HARD_SLOT_CAP = 4;\n\n/** The answer of resolveConcurrency: the slot count to use and a message when it was lowered. */\nexport interface ResolvedConcurrency {\n value: number;\n warning: string | undefined;\n}\n\n/**\n * resolveConcurrency picks how many test cases this machine runs at the same time.\n *\n * What it is: a safety limit on the --concurrency flag for a customer's own computer.\n * What it does: returns the requested number when the machine can carry it, and a lower number\n * with a plain warning when it cannot, so a typo or an enthusiastic value never freezes the system.\n * How it works: each slot is a browser, so the limit is the smallest of half the CPU cores (the\n * rest stay free for the person using the machine), the free memory at one GiB a slot, and a hard\n * cap of four. A missing, non-numeric or below-one request means one slot. The result is never below one.\n */\nexport function resolveConcurrency(\n requested: number,\n cpuCount: number,\n freeMemoryBytes: number,\n): ResolvedConcurrency {\n const wanted = Number.isFinite(requested) && requested >= 1 ? Math.floor(requested) : 1;\n const byCpu = Math.floor(cpuCount / 2);\n const byMemory = Math.floor(freeMemoryBytes / BYTES_PER_SLOT);\n const limit = Math.max(1, Math.min(HARD_SLOT_CAP, byCpu, byMemory));\n if (wanted <= limit) {\n return { value: wanted, warning: undefined };\n }\n return {\n value: limit,\n warning:\n `--concurrency ${wanted} is too many for this machine (${cpuCount} CPU cores, ` +\n `${(freeMemoryBytes / BYTES_PER_SLOT).toFixed(1)} GiB free memory); using ${limit}.`,\n };\n}\n", "export function loadEngineBundle() { return \"\\\"use strict\\\";\\nvar LocusEngine = (() => {\\n var __defProp = Object.defineProperty;\\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\\n var __getOwnPropNames = Object.getOwnPropertyNames;\\n var __hasOwnProp = Object.prototype.hasOwnProperty;\\n var __export = (target, all) => {\\n for (var name in all)\\n __defProp(target, name, { get: all[name], enumerable: true });\\n };\\n var __copyProps = (to, from, except, desc) => {\\n if (from && typeof from === \\\"object\\\" || typeof from === \\\"function\\\") {\\n for (let key of __getOwnPropNames(from))\\n if (!__hasOwnProp.call(to, key) && key !== except)\\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\\n }\\n return to;\\n };\\n var __toCommonJS = (mod) => __copyProps(__defProp({}, \\\"__esModule\\\", { value: true }), mod);\\n\\n // src/index.ts\\n var src_exports = {};\\n __export(src_exports, {\\n UnsupportedSelectorError: () => UnsupportedSelectorError,\\n accessibleName: () => accessibleName,\\n buildLocatorSet: () => buildLocatorSet,\\n captureVerification: () => captureVerification,\\n captureVerificationForReplay: () => captureVerificationForReplay,\\n elementText: () => elementText,\\n idVolatility: () => idVolatility,\\n implicitRole: () => implicitRole,\\n isHidden: () => isHidden,\\n isTrustworthyName: () => isTrustworthyName,\\n normalizeSpace: () => normalizeSpace,\\n readIdentifier: () => readIdentifier,\\n readNeighbour: () => readNeighbour,\\n resolve: () => resolve,\\n sha256Hex: () => sha256Hex,\\n splitChain: () => splitChain,\\n storageCaptureTools: () => storageCaptureTools,\\n strategyFamily: () => strategyFamily,\\n textVolatility: () => textVolatility,\\n valueVolatility: () => valueVolatility\\n });\\n\\n // src/accessibility.ts\\n var LANDMARK_AND_TAG_ROLES = {\\n a: \\\"link\\\",\\n article: \\\"article\\\",\\n aside: \\\"complementary\\\",\\n button: \\\"button\\\",\\n dialog: \\\"dialog\\\",\\n form: \\\"form\\\",\\n h1: \\\"heading\\\",\\n h2: \\\"heading\\\",\\n h3: \\\"heading\\\",\\n h4: \\\"heading\\\",\\n h5: \\\"heading\\\",\\n h6: \\\"heading\\\",\\n li: \\\"listitem\\\",\\n main: \\\"main\\\",\\n nav: \\\"navigation\\\",\\n ol: \\\"list\\\",\\n option: \\\"option\\\",\\n progress: \\\"progressbar\\\",\\n table: \\\"table\\\",\\n tbody: \\\"rowgroup\\\",\\n td: \\\"cell\\\",\\n textarea: \\\"textbox\\\",\\n th: \\\"columnheader\\\",\\n tr: \\\"row\\\",\\n ul: \\\"list\\\"\\n };\\n var BUTTON_INPUT_TYPES = /* @__PURE__ */ new Set([\\\"button\\\", \\\"submit\\\", \\\"reset\\\", \\\"image\\\"]);\\n var TEXTBOX_INPUT_TYPES = /* @__PURE__ */ new Set([\\\"\\\", \\\"text\\\", \\\"email\\\", \\\"tel\\\", \\\"url\\\", \\\"password\\\"]);\\n function normalizeSpace(text) {\\n return text.replace(/\\\\s+/g, \\\" \\\").trim();\\n }\\n function implicitRole(el) {\\n const explicit = el.getAttribute(\\\"role\\\");\\n if (explicit !== null) {\\n const first = explicit.trim().split(/\\\\s+/)[0];\\n if (first) return first;\\n }\\n const tag = el.tagName.toLowerCase();\\n if (tag === \\\"a\\\") return el.hasAttribute(\\\"href\\\") ? \\\"link\\\" : null;\\n if (tag === \\\"img\\\") return el.getAttribute(\\\"alt\\\") === \\\"\\\" ? \\\"presentation\\\" : \\\"img\\\";\\n if (tag === \\\"select\\\") {\\n const size = Number(el.getAttribute(\\\"size\\\") ?? \\\"0\\\");\\n return el.hasAttribute(\\\"multiple\\\") || size > 1 ? \\\"listbox\\\" : \\\"combobox\\\";\\n }\\n if (tag === \\\"input\\\") {\\n const type = (el.getAttribute(\\\"type\\\") ?? \\\"\\\").toLowerCase();\\n if (BUTTON_INPUT_TYPES.has(type)) return \\\"button\\\";\\n if (type === \\\"checkbox\\\") return \\\"checkbox\\\";\\n if (type === \\\"radio\\\") return \\\"radio\\\";\\n if (type === \\\"range\\\") return \\\"slider\\\";\\n if (type === \\\"number\\\") return \\\"spinbutton\\\";\\n if (type === \\\"search\\\") return el.hasAttribute(\\\"list\\\") ? \\\"combobox\\\" : \\\"searchbox\\\";\\n if (TEXTBOX_INPUT_TYPES.has(type)) return el.hasAttribute(\\\"list\\\") ? \\\"combobox\\\" : \\\"textbox\\\";\\n return null;\\n }\\n return LANDMARK_AND_TAG_ROLES[tag] ?? null;\\n }\\n var NAME_FROM_CONTENT_ROLES = /* @__PURE__ */ new Set([\\n \\\"button\\\",\\n \\\"link\\\",\\n \\\"heading\\\",\\n \\\"cell\\\",\\n \\\"columnheader\\\",\\n \\\"listitem\\\",\\n \\\"option\\\",\\n \\\"tab\\\",\\n \\\"menuitem\\\",\\n \\\"checkbox\\\",\\n \\\"radio\\\"\\n ]);\\n function textOf(el) {\\n const parts = [];\\n function collect(node) {\\n if (node.nodeType === 3) {\\n const val = node.nodeValue?.trim();\\n if (val) parts.push(val);\\n return;\\n }\\n if (node.nodeType === 1) {\\n const childEl = node;\\n if (childEl.tagName.toLowerCase() === \\\"svg\\\" && !childEl.getAttribute(\\\"aria-label\\\")) {\\n return;\\n }\\n if (isHidden(childEl)) return;\\n const childAria = childEl.getAttribute(\\\"aria-label\\\");\\n if (childAria && childAria.trim()) {\\n parts.push(childAria.trim());\\n return;\\n }\\n const childAlt = childEl.getAttribute(\\\"alt\\\");\\n if (childAlt && childAlt.trim()) {\\n parts.push(childAlt.trim());\\n return;\\n }\\n for (let child = childEl.firstChild; child; child = child.nextSibling) {\\n collect(child);\\n }\\n }\\n }\\n for (let child = el.firstChild; child; child = child.nextSibling) {\\n collect(child);\\n }\\n const result = parts.join(\\\" \\\").replace(/\\\\s+/g, \\\" \\\").trim();\\n if (result) return result;\\n return normalizeSpace(el.textContent ?? \\\"\\\");\\n }\\n function labelText(el) {\\n const doc = el.ownerDocument;\\n const parts = [];\\n if (el.id) {\\n for (const label of Array.from(doc.querySelectorAll(\\\"label\\\"))) {\\n if (label.getAttribute(\\\"for\\\") === el.id) parts.push(textOf(label));\\n }\\n }\\n const wrapping = el.closest(\\\"label\\\");\\n if (wrapping) parts.push(textOf(wrapping));\\n const joined = normalizeSpace(parts.join(\\\" \\\"));\\n return joined === \\\"\\\" ? null : joined;\\n }\\n function accessibleName(el) {\\n const doc = el.ownerDocument;\\n const labelledBy = el.getAttribute(\\\"aria-labelledby\\\");\\n if (labelledBy) {\\n const text = normalizeSpace(\\n labelledBy.split(/\\\\s+/).map((id) => doc.getElementById(id)?.textContent ?? \\\"\\\").join(\\\" \\\")\\n );\\n if (text) return { name: text, source: \\\"aria-labelledby\\\" };\\n }\\n const ariaLabel = el.getAttribute(\\\"aria-label\\\");\\n if (ariaLabel && ariaLabel.trim())\\n return { name: normalizeSpace(ariaLabel), source: \\\"aria-label\\\" };\\n const tag = el.tagName.toLowerCase();\\n const type = (el.getAttribute(\\\"type\\\") ?? \\\"\\\").toLowerCase();\\n if (tag === \\\"img\\\") {\\n const alt = el.getAttribute(\\\"alt\\\");\\n if (alt && alt.trim()) return { name: normalizeSpace(alt), source: \\\"alt\\\" };\\n }\\n if (tag === \\\"input\\\" && BUTTON_INPUT_TYPES.has(type)) {\\n const value = el.getAttribute(\\\"value\\\");\\n if (value && value.trim()) return { name: normalizeSpace(value), source: \\\"value\\\" };\\n if (type === \\\"submit\\\") return { name: \\\"Submit\\\", source: \\\"value\\\" };\\n if (type === \\\"reset\\\") return { name: \\\"Reset\\\", source: \\\"value\\\" };\\n }\\n if (tag === \\\"input\\\" || tag === \\\"select\\\" || tag === \\\"textarea\\\") {\\n const label = labelText(el);\\n if (label) return { name: label, source: \\\"label\\\" };\\n const placeholder = el.getAttribute(\\\"placeholder\\\");\\n if (placeholder && placeholder.trim())\\n return { name: normalizeSpace(placeholder), source: \\\"placeholder\\\" };\\n }\\n const role = implicitRole(el);\\n if (role !== null && NAME_FROM_CONTENT_ROLES.has(role) && tag !== \\\"input\\\") {\\n const text = textOf(el);\\n if (text) return { name: text, source: \\\"content\\\" };\\n }\\n const title = el.getAttribute(\\\"title\\\");\\n if (title && title.trim()) return { name: normalizeSpace(title), source: \\\"title\\\" };\\n return null;\\n }\\n function isHidden(el) {\\n const view = el.ownerDocument.defaultView;\\n for (let node = el; node; node = node.parentElement) {\\n if (node.hasAttribute(\\\"hidden\\\") || node.getAttribute(\\\"aria-hidden\\\") === \\\"true\\\") return true;\\n if (view) {\\n const style = view.getComputedStyle(node);\\n if (style.display === \\\"none\\\" || style.visibility === \\\"hidden\\\") return true;\\n }\\n }\\n return false;\\n }\\n\\n // src/resolve.ts\\n var UnsupportedSelectorError = class extends Error {\\n constructor(expression, reason) {\\n super(`unsupported selector ${JSON.stringify(expression)}: ${reason}`);\\n this.name = \\\"UnsupportedSelectorError\\\";\\n }\\n };\\n function splitChain(expression) {\\n const parts = [];\\n let depth = 0;\\n let quote = null;\\n let start = 0;\\n for (let i = 0; i < expression.length; i++) {\\n const ch = expression.charAt(i);\\n if (quote !== null) {\\n if (ch === \\\"\\\\\\\\\\\") i++;\\n else if (ch === quote) quote = null;\\n continue;\\n }\\n if (ch === '\\\"' || ch === \\\"'\\\") quote = ch;\\n else if (ch === \\\"[\\\" || ch === \\\"(\\\") depth++;\\n else if (ch === \\\"]\\\" || ch === \\\")\\\") depth--;\\n else if (depth === 0 && expression.startsWith(\\\">>\\\", i)) {\\n parts.push(expression.slice(start, i).trim());\\n start = i + 2;\\n i++;\\n }\\n }\\n parts.push(expression.slice(start).trim());\\n if (parts.some((p) => p === \\\"\\\"))\\n throw new UnsupportedSelectorError(expression, \\\"empty chain segment\\\");\\n return parts;\\n }\\n function readQuoted(source, from, expression) {\\n const quote = source.charAt(from);\\n if (quote !== '\\\"' && quote !== \\\"'\\\")\\n throw new UnsupportedSelectorError(expression, \\\"expected a quoted value\\\");\\n let value = \\\"\\\";\\n for (let i = from + 1; i < source.length; i++) {\\n const ch = source.charAt(i);\\n if (ch === \\\"\\\\\\\\\\\") {\\n value += source.charAt(i + 1);\\n i++;\\n } else if (ch === quote) {\\n return { value, next: i + 1 };\\n } else {\\n value += ch;\\n }\\n }\\n throw new UnsupportedSelectorError(expression, \\\"unterminated quoted value\\\");\\n }\\n function parseRole(part) {\\n const match = /^role=([a-zA-Z]+)/.exec(part);\\n if (!match || match[1] === void 0)\\n throw new UnsupportedSelectorError(part, \\\"malformed role selector\\\");\\n const query = { role: match[1].toLowerCase(), name: null };\\n let i = match[0].length;\\n while (i < part.length) {\\n if (part.charAt(i) !== \\\"[\\\") throw new UnsupportedSelectorError(part, \\\"expected [\\\");\\n const eq = part.indexOf(\\\"=\\\", i);\\n if (eq < 0) throw new UnsupportedSelectorError(part, \\\"expected =\\\");\\n const key = part.slice(i + 1, eq).trim();\\n if (key !== \\\"name\\\")\\n throw new UnsupportedSelectorError(part, `unsupported role attribute ${key}`);\\n const quoted = readQuoted(part, eq + 1, part);\\n i = quoted.next;\\n let exact = false;\\n const flag = part.charAt(i);\\n if (flag === \\\"s\\\") {\\n exact = true;\\n i++;\\n } else if (flag === \\\"i\\\") {\\n i++;\\n }\\n if (part.charAt(i) !== \\\"]\\\") throw new UnsupportedSelectorError(part, \\\"expected ]\\\");\\n i++;\\n query.name = { value: quoted.value, exact };\\n }\\n return query;\\n }\\n function nameMatches(actual, wanted) {\\n const normalized = normalizeSpace(wanted.value);\\n if (wanted.exact) return actual === normalized;\\n return actual.toLowerCase() === normalized.toLowerCase();\\n }\\n function queryRole(scope, query) {\\n const out = [];\\n for (const el of Array.from(scope.querySelectorAll(\\\"*\\\"))) {\\n if (implicitRole(el) !== query.role) continue;\\n if (isHidden(el)) continue;\\n if (query.name !== null) {\\n const name = accessibleName(el);\\n if (name === null || !nameMatches(name.name, query.name)) continue;\\n }\\n out.push(el);\\n }\\n return out;\\n }\\n var TEXT_IS = /^([a-zA-Z][a-zA-Z0-9-]*)?:text-is\\\\(/;\\n var SKIPPED_TEXT_TAGS = /* @__PURE__ */ new Set([\\\"SCRIPT\\\", \\\"NOSCRIPT\\\", \\\"STYLE\\\"]);\\n function elementText(el) {\\n if (SKIPPED_TEXT_TAGS.has(el.tagName)) return \\\"\\\";\\n let out = \\\"\\\";\\n for (let child = el.firstChild; child; child = child.nextSibling) {\\n if (child.nodeType === 3) out += child.nodeValue ?? \\\"\\\";\\n else if (child.nodeType === 1) out += elementText(child);\\n }\\n return normalizeSpace(out.replace(/\\\\u200b/g, \\\"\\\"));\\n }\\n function parseTextIs(part) {\\n const match = TEXT_IS.exec(part);\\n if (!match) throw new UnsupportedSelectorError(part, \\\"malformed text selector\\\");\\n const quoted = readQuoted(part, match[0].length, part);\\n if (part.slice(quoted.next) !== \\\")\\\") throw new UnsupportedSelectorError(part, \\\"expected )\\\");\\n return { tag: match[1] ?? \\\"*\\\", text: normalizeSpace(quoted.value) };\\n }\\n function queryTextIs(scope, part) {\\n const query = parseTextIs(part);\\n const out = [];\\n for (const el of Array.from(scope.querySelectorAll(query.tag))) {\\n if (elementText(el) !== query.text) continue;\\n if (Array.from(el.children).some((child) => elementText(child) === query.text)) continue;\\n out.push(el);\\n }\\n return out;\\n }\\n function queryXPath(scope, xpath, doc) {\\n const snapshot = doc.evaluate(xpath, scope, null, 7, null);\\n const out = [];\\n for (let i = 0; i < snapshot.snapshotLength; i++) {\\n const node = snapshot.snapshotItem(i);\\n if (node !== null && node.nodeType === 1) out.push(node);\\n }\\n return out;\\n }\\n function queryPart(scope, part, doc) {\\n if (part.startsWith(\\\"role=\\\")) return queryRole(scope, parseRole(part));\\n if (part.startsWith(\\\"xpath=\\\")) return queryXPath(scope, part.slice(\\\"xpath=\\\".length), doc);\\n if (TEXT_IS.test(part)) return queryTextIs(scope, part);\\n if (part.startsWith(\\\"text=\\\") || part.includes(\\\":has-text(\\\") || part.includes(\\\":text(\\\")) {\\n throw new UnsupportedSelectorError(part, \\\"text selectors are not supported\\\");\\n }\\n return Array.from(scope.querySelectorAll(part));\\n }\\n var NTH_PART = /^nth=(.*)$/;\\n function parseNth(part, raw) {\\n if (!/^-?\\\\d+$/.test(raw.trim()))\\n throw new UnsupportedSelectorError(part, \\\"nth= needs a whole number\\\");\\n return Number.parseInt(raw.trim(), 10);\\n }\\n function pickNth(matches, index) {\\n const at = index < 0 ? matches.length + index : index;\\n const picked = matches[at];\\n return picked === void 0 ? [] : [picked];\\n }\\n function resolve(expression, doc) {\\n let scopes = [doc];\\n for (const part of splitChain(expression)) {\\n const nth = NTH_PART.exec(part);\\n if (nth !== null) {\\n if (scopes.length === 1 && scopes[0] === doc)\\n throw new UnsupportedSelectorError(part, \\\"nth= needs a selector before it\\\");\\n scopes = pickNth(scopes, parseNth(part, nth[1] ?? \\\"\\\"));\\n if (scopes.length === 0) return [];\\n continue;\\n }\\n const seen = /* @__PURE__ */ new Set();\\n const next = [];\\n for (const scope of scopes) {\\n for (const el of queryPart(scope, part, doc)) {\\n if (!seen.has(el)) {\\n seen.add(el);\\n next.push(el);\\n }\\n }\\n }\\n scopes = next;\\n if (scopes.length === 0) return [];\\n }\\n return scopes;\\n }\\n\\n // src/volatility.ts\\n var UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;\\n var LONG_HEX = /[0-9a-f]{8,}/i;\\n var LONG_DIGITS = /\\\\d{5,}/;\\n var GENERATED_PREFIX = /^(css|sc|jsx|emotion|styled|makeStyles|MuiBox)[-_]/i;\\n var FRAMEWORK_ID = /^(:r[0-9a-z]*:|ember\\\\d+|ng-\\\\d+|react-select-\\\\d+|mui-\\\\d+|radix-|headlessui-|__next|rc_select_\\\\d+)/i;\\n var COUNTER_ID = /^[a-z]+(?:[-_][a-z]+)*(?:[-_]\\\\d{1,4})+$/i;\\n var GENERATED_ID = /^(\\\\u00ab.*\\\\u00bb|_r_[0-9a-z]+_|__BVID__\\\\d+|j_idt\\\\d+)$/i;\\n function valueVolatility(value) {\\n if (value.length > 60) return { volatile: true, reason: \\\"value is unusually long\\\" };\\n if (UUID.test(value)) return { volatile: true, reason: \\\"value contains a UUID\\\" };\\n if (FRAMEWORK_ID.test(value))\\n return { volatile: true, reason: \\\"value looks framework-generated\\\" };\\n if (GENERATED_PREFIX.test(value))\\n return { volatile: true, reason: \\\"value looks like a generated class\\\" };\\n if (LONG_HEX.test(value) && /\\\\d/.test(value))\\n return { volatile: true, reason: \\\"value contains a hash-like run\\\" };\\n if (LONG_DIGITS.test(value)) return { volatile: true, reason: \\\"value contains a long number\\\" };\\n const digits = (value.match(/\\\\d/g) ?? []).length;\\n if (value.length >= 6 && digits / value.length > 0.4)\\n return { volatile: true, reason: \\\"value is mostly digits\\\" };\\n return { volatile: false, reason: null };\\n }\\n function textVolatility(text) {\\n if (text.length > 80) return { volatile: true, reason: \\\"text is long\\\" };\\n if (/\\\\d{2,}/.test(text))\\n return { volatile: true, reason: \\\"text contains numbers that may change\\\" };\\n return { volatile: false, reason: null };\\n }\\n function idVolatility(id) {\\n const value = valueVolatility(id);\\n if (value.volatile) return value;\\n if (GENERATED_ID.test(id)) return { volatile: true, reason: \\\"id looks framework-generated\\\" };\\n if (COUNTER_ID.test(id))\\n return { volatile: true, reason: \\\"id looks like a render-order counter\\\" };\\n return { volatile: false, reason: null };\\n }\\n\\n // src/generate.ts\\n var TESTID_ATTRS = [\\n \\\"data-testid\\\",\\n \\\"data-test-id\\\",\\n \\\"data-test\\\",\\n \\\"data-qa\\\",\\n \\\"data-cy\\\",\\n \\\"data-automation-id\\\"\\n ];\\n var DESCRIPTIVE_ATTRS = [\\\"aria-label\\\", \\\"placeholder\\\", \\\"alt\\\", \\\"title\\\"];\\n var RECORDED_ATTRS = [\\n \\\"id\\\",\\n \\\"name\\\",\\n \\\"type\\\",\\n \\\"role\\\",\\n \\\"href\\\",\\n \\\"download\\\",\\n \\\"for\\\",\\n \\\"aria-label\\\",\\n \\\"placeholder\\\",\\n \\\"alt\\\",\\n \\\"title\\\",\\n ...TESTID_ATTRS\\n ];\\n var CONTAINER_TAGS = /* @__PURE__ */ new Set([\\n \\\"form\\\",\\n \\\"dialog\\\",\\n \\\"table\\\",\\n \\\"nav\\\",\\n \\\"main\\\",\\n \\\"aside\\\",\\n \\\"fieldset\\\",\\n \\\"section\\\",\\n \\\"header\\\",\\n \\\"footer\\\",\\n \\\"ul\\\",\\n \\\"ol\\\",\\n \\\"tr\\\"\\n ]);\\n var NAMED_CONTAINER_ROLES = /* @__PURE__ */ new Set([\\n \\\"form\\\",\\n \\\"dialog\\\",\\n \\\"navigation\\\",\\n \\\"main\\\",\\n \\\"complementary\\\",\\n \\\"table\\\",\\n \\\"region\\\",\\n \\\"list\\\"\\n ]);\\n var MAX_ANCESTORS_CHECKED = 6;\\n var MAX_NAME_LENGTH = 100;\\n var MAX_TEXT_LENGTH = 80;\\n var STRATEGY_ORDER = [\\\"semantic\\\", \\\"stable_attribute\\\", \\\"relational\\\", \\\"css\\\", \\\"xpath\\\"];\\n var INDEPENDENT_FAMILIES = /* @__PURE__ */ new Set([\\\"semantic\\\", \\\"stable_attribute\\\", \\\"relational\\\"]);\\n var BASE_CONFIDENCE = {\\n semantic: 0.85,\\n stable_attribute: 0.8,\\n relational: 0.7,\\n css: 0.35,\\n xpath: 0.25\\n };\\n var STABILITY_FACTOR = { stable: 1, moderate: 0.85, volatile: 0.6 };\\n function esc(value) {\\n return value.replace(/\\\\\\\\/g, \\\"\\\\\\\\\\\\\\\\\\\").replace(/\\\"/g, '\\\\\\\\\\\"');\\n }\\n function attrSelector(name, value) {\\n return `[${name}=\\\"${esc(value)}\\\"]`;\\n }\\n function tagOf(el) {\\n return el.tagName.toLowerCase();\\n }\\n function measure(expression, target) {\\n const matches = resolve(expression, target.ownerDocument);\\n return { count: matches.length, unique: matches.length === 1 && matches[0] === target };\\n }\\n function ownText(el) {\\n if ([\\\"input\\\", \\\"select\\\", \\\"textarea\\\"].includes(tagOf(el))) return null;\\n const text = textOf(el);\\n return text !== \\\"\\\" && text.length <= MAX_TEXT_LENGTH ? text : null;\\n }\\n function recordedAttributes(el) {\\n const out = {};\\n for (const name of RECORDED_ATTRS) {\\n const value = el.getAttribute(name);\\n if (value !== null && value !== \\\"\\\") out[name] = value.slice(0, 200);\\n }\\n return out;\\n }\\n function confidenceOf(strategy, stability, unique, boost) {\\n const base = boost ? 0.95 : BASE_CONFIDENCE[strategy];\\n const value = base * STABILITY_FACTOR[stability] * (unique ? 1 : 0.4);\\n return Math.round(Math.min(1, Math.max(0, value)) * 100) / 100;\\n }\\n function build(strategy, el, candidate, context) {\\n const measured = measure(candidate.expression, el);\\n const name = accessibleName(el);\\n return {\\n strategy,\\n expression: candidate.expression,\\n tag: tagOf(el),\\n role: implicitRole(el),\\n accessible_name: name === null ? null : name.name.slice(0, MAX_NAME_LENGTH),\\n text: ownText(el),\\n attributes: recordedAttributes(el),\\n context,\\n match_count: measured.count,\\n unique: measured.unique,\\n confidence: confidenceOf(strategy, candidate.stability, measured.unique, candidate.boost),\\n stability: candidate.stability,\\n evidence: candidate.evidence,\\n fragility: candidate.fragility\\n };\\n }\\n function semanticCandidate(el) {\\n const role = implicitRole(el);\\n const name = accessibleName(el);\\n if (role === null || role === \\\"presentation\\\" || role === \\\"generic\\\" || name === null) return null;\\n const text = name.name.slice(0, MAX_NAME_LENGTH);\\n const textRisk = textVolatility(text);\\n let stability = [\\\"aria-label\\\", \\\"aria-labelledby\\\", \\\"label\\\"].includes(name.source) ? \\\"stable\\\" : \\\"moderate\\\";\\n const fragility = [];\\n if (textRisk.volatile) {\\n stability = \\\"volatile\\\";\\n fragility.push(textRisk.reason ?? \\\"name may change\\\");\\n }\\n if (name.source === \\\"content\\\" || name.source === \\\"placeholder\\\" || name.source === \\\"title\\\") {\\n fragility.push(\\\"depends on visible copy; breaks if the wording changes\\\");\\n }\\n return {\\n expression: `role=${role}[name=\\\"${esc(text)}\\\"]`,\\n stability,\\n evidence: [`role ${role}`, `accessible name from ${name.source}`],\\n fragility,\\n boost: false\\n };\\n }\\n function attributeCandidates(el, scopeTag) {\\n const tag = scopeTag ? tagOf(el) : \\\"\\\";\\n const out = [];\\n for (const attr of TESTID_ATTRS) {\\n const value = el.getAttribute(attr);\\n if (value) {\\n out.push({\\n expression: `${tag}${attrSelector(attr, value)}`,\\n stability: \\\"stable\\\",\\n evidence: [`${attr} attribute`],\\n fragility: [],\\n boost: true\\n });\\n }\\n }\\n const id = el.getAttribute(\\\"id\\\");\\n if (id) {\\n const risk = idVolatility(id);\\n if (!risk.volatile) {\\n out.push({\\n expression: `${tag}${attrSelector(\\\"id\\\", id)}`,\\n stability: \\\"stable\\\",\\n evidence: [\\\"id attribute\\\"],\\n fragility: [],\\n boost: false\\n });\\n }\\n }\\n const nameAttr = el.getAttribute(\\\"name\\\");\\n if (nameAttr && !valueVolatility(nameAttr).volatile) {\\n out.push({\\n expression: `${tag}${attrSelector(\\\"name\\\", nameAttr)}`,\\n stability: \\\"moderate\\\",\\n evidence: [\\\"name attribute\\\"],\\n fragility: [],\\n boost: false\\n });\\n const type = el.getAttribute(\\\"type\\\");\\n if (type) {\\n out.push({\\n expression: `${tag}${attrSelector(\\\"name\\\", nameAttr)}${attrSelector(\\\"type\\\", type)}`,\\n stability: \\\"moderate\\\",\\n evidence: [\\\"name and type attributes\\\"],\\n fragility: [],\\n boost: false\\n });\\n }\\n }\\n for (const attr of DESCRIPTIVE_ATTRS) {\\n const value = el.getAttribute(attr);\\n if (value && value.length <= MAX_NAME_LENGTH && !textVolatility(value).volatile) {\\n out.push({\\n expression: `${tag}${attrSelector(attr, value)}`,\\n stability: \\\"moderate\\\",\\n evidence: [`${attr} attribute`],\\n fragility: [\\\"depends on copy; breaks if the wording changes\\\"],\\n boost: false\\n });\\n }\\n }\\n const href = el.getAttribute(\\\"href\\\");\\n if (tagOf(el) === \\\"a\\\" && href && !valueVolatility(href).volatile) {\\n out.push({\\n expression: `${tag}${attrSelector(\\\"href\\\", href)}`,\\n stability: \\\"moderate\\\",\\n evidence: [\\\"href attribute\\\"],\\n fragility: [\\\"breaks if the route changes\\\"],\\n boost: false\\n });\\n }\\n return out;\\n }\\n function pickBest(el, candidates) {\\n for (const candidate of candidates) {\\n if (measure(candidate.expression, el).unique) return candidate;\\n }\\n return candidates[0] ?? null;\\n }\\n function nthOfType(el) {\\n let index = 1;\\n for (let sibling = el.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {\\n if (sibling.tagName === el.tagName) index++;\\n }\\n return index;\\n }\\n function sameTagSiblings(el) {\\n const parent = el.parentElement;\\n if (!parent) return 1;\\n return Array.from(parent.children).filter((c) => c.tagName === el.tagName).length;\\n }\\n function anchorFor(ancestor) {\\n for (const attr of TESTID_ATTRS) {\\n const value = ancestor.getAttribute(attr);\\n if (value)\\n return {\\n expression: `${tagOf(ancestor)}${attrSelector(attr, value)}`,\\n evidence: `ancestor ${attr}`\\n };\\n }\\n const id = ancestor.getAttribute(\\\"id\\\");\\n if (id && !idVolatility(id).volatile) {\\n return { expression: `${tagOf(ancestor)}${attrSelector(\\\"id\\\", id)}`, evidence: \\\"ancestor id\\\" };\\n }\\n const role = implicitRole(ancestor);\\n const name = accessibleName(ancestor);\\n if (role !== null && NAMED_CONTAINER_ROLES.has(role) && name !== null && !textVolatility(name.name).volatile) {\\n return {\\n expression: `role=${role}[name=\\\"${esc(name.name.slice(0, MAX_NAME_LENGTH))}\\\"]`,\\n evidence: `ancestor ${role} \\\"${name.name}\\\"`\\n };\\n }\\n if (CONTAINER_TAGS.has(tagOf(ancestor)))\\n return { expression: tagOf(ancestor), evidence: `ancestor <${tagOf(ancestor)}>` };\\n return null;\\n }\\n function textCandidate(el) {\\n if ([\\\"input\\\", \\\"select\\\", \\\"textarea\\\"].includes(tagOf(el))) return null;\\n const text = elementText(el);\\n if (text === \\\"\\\" || text.length > MAX_NAME_LENGTH || textVolatility(text).volatile) return null;\\n if (text !== textOf(el)) return null;\\n return {\\n expression: `${tagOf(el)}:text-is(\\\"${esc(text)}\\\")`,\\n stability: \\\"moderate\\\",\\n evidence: [\\\"exact visible text\\\"],\\n fragility: [\\\"depends on visible copy; breaks if the wording changes\\\"],\\n boost: false\\n };\\n }\\n function innerCandidates(el) {\\n const out = [];\\n const semantic = semanticCandidate(el);\\n if (semantic) out.push(semantic);\\n out.push(...attributeCandidates(el, true));\\n const text = textCandidate(el);\\n if (text) out.push(text);\\n const tag = tagOf(el);\\n const nth = sameTagSiblings(el) > 1 ? `:nth-of-type(${nthOfType(el)})` : \\\"\\\";\\n out.push({\\n expression: `${tag}${nth}`,\\n stability: nth === \\\"\\\" ? \\\"moderate\\\" : \\\"volatile\\\",\\n evidence: nth === \\\"\\\" ? [\\\"tag within anchor\\\"] : [\\\"tag position within anchor\\\"],\\n fragility: nth === \\\"\\\" ? [] : [\\\"position-dependent; breaks if siblings are added or reordered\\\"],\\n boost: false\\n });\\n return out;\\n }\\n function relationalCandidate(el) {\\n let checked = 0;\\n for (let ancestor = el.parentElement; ancestor && checked < MAX_ANCESTORS_CHECKED; ancestor = ancestor.parentElement) {\\n if (ancestor === el.ownerDocument.body || ancestor === el.ownerDocument.documentElement) break;\\n const anchor = anchorFor(ancestor);\\n if (anchor === null) continue;\\n checked++;\\n for (const inner of innerCandidates(el)) {\\n const expression = `${anchor.expression} >> ${inner.expression}`;\\n const candidate = {\\n expression,\\n stability: inner.stability === \\\"volatile\\\" ? \\\"volatile\\\" : \\\"moderate\\\",\\n evidence: [anchor.evidence, ...inner.evidence],\\n fragility: inner.fragility,\\n boost: false\\n };\\n if (measure(expression, el).unique) return { candidate, anchor: anchor.expression };\\n }\\n }\\n return null;\\n }\\n function structuralCss(el) {\\n const segments = [];\\n let node = el;\\n let anchored = false;\\n while (node && node !== el.ownerDocument.documentElement) {\\n const tag = tagOf(node);\\n if (node !== el.ownerDocument.body) {\\n const id = node.getAttribute(\\\"id\\\");\\n if (id && !idVolatility(id).volatile) {\\n segments.unshift(`${tag}${attrSelector(\\\"id\\\", id)}`);\\n anchored = true;\\n break;\\n }\\n if (node !== el && [\\\"header\\\", \\\"main\\\", \\\"nav\\\", \\\"footer\\\"].includes(tag) && node.ownerDocument.querySelectorAll(tag).length === 1) {\\n segments.unshift(tag);\\n anchored = true;\\n break;\\n }\\n }\\n if (node === el.ownerDocument.body) {\\n segments.unshift(\\\"body\\\");\\n break;\\n }\\n segments.unshift(sameTagSiblings(node) > 1 ? `${tag}:nth-of-type(${nthOfType(node)})` : tag);\\n node = node.parentElement;\\n }\\n return {\\n expression: segments.join(\\\" > \\\"),\\n stability: \\\"volatile\\\",\\n evidence: [anchored ? \\\"structural path from nearest anchor\\\" : \\\"structural path from body\\\"],\\n fragility: [\\\"position-dependent; breaks if the layout changes\\\"],\\n boost: false\\n };\\n }\\n function structuralXPath(el) {\\n const segments = [];\\n for (let node = el; node; node = node.parentElement) {\\n const tag = tagOf(node);\\n segments.unshift(sameTagSiblings(node) > 1 ? `${tag}[${nthOfType(node)}]` : tag);\\n if (node === el.ownerDocument.documentElement) break;\\n }\\n return {\\n expression: `xpath=/${segments.join(\\\"/\\\")}`,\\n stability: \\\"volatile\\\",\\n evidence: [\\\"absolute structural path\\\"],\\n fragility: [\\\"position-dependent; breaks if the layout changes\\\"],\\n boost: false\\n };\\n }\\n function ancestorContext(el) {\\n const out = [];\\n for (let node = el.parentElement; node && out.length < 3; node = node.parentElement) {\\n if (node === el.ownerDocument.documentElement) break;\\n out.push({ tag: tagOf(node), role: implicitRole(node) });\\n }\\n return out;\\n }\\n function isExplicitIdentifier(locator) {\\n return locator.strategy === \\\"stable_attribute\\\" && locator.stability === \\\"stable\\\";\\n }\\n var REQUIRED_STRATEGIES = 3;\\n var REQUIRED_STRATEGIES_WITH_ID = 2;\\n function hasUniqueExplicitIdentifier(locators) {\\n return locators.some((l) => l.unique && isExplicitIdentifier(l));\\n }\\n function isTrustworthyName(name, role, tag) {\\n if (name === null) return false;\\n const trimmed = name.trim();\\n if (Array.from(trimmed).length < 3) return false;\\n if (!/\\\\p{L}/u.test(trimmed)) return false;\\n const lower = trimmed.toLowerCase();\\n return lower !== (role ?? \\\"\\\").toLowerCase() && lower !== tag.toLowerCase();\\n }\\n function uniqueNamedSemantic(locators) {\\n return locators.find(\\n (l) => l.strategy === \\\"semantic\\\" && l.unique && l.stability !== \\\"volatile\\\" && l.role !== null && isTrustworthyName(l.accessible_name, l.role, l.tag)\\n ) ?? null;\\n }\\n function hasUniqueNamedSemanticWithBackup(locators) {\\n const semantic = uniqueNamedSemantic(locators);\\n if (semantic === null || semantic.accessible_name === null) return false;\\n const name = semantic.accessible_name.trim();\\n return locators.some(\\n (l) => l !== semantic && l.unique && (l.strategy === \\\"stable_attribute\\\" || l.strategy === \\\"relational\\\" && !l.expression.includes(name))\\n );\\n }\\n function compareLocators(a, b) {\\n if (a.unique !== b.unique) return a.unique ? -1 : 1;\\n const idA = isExplicitIdentifier(a);\\n const idB = isExplicitIdentifier(b);\\n if (idA !== idB) return idA ? -1 : 1;\\n return STRATEGY_ORDER.indexOf(a.strategy) - STRATEGY_ORDER.indexOf(b.strategy);\\n }\\n function buildLocatorSet(el) {\\n const base = { sibling_index: nthOfType(el), ancestors: ancestorContext(el) };\\n const locators = [];\\n const semantic = semanticCandidate(el);\\n if (semantic) locators.push(build(\\\"semantic\\\", el, semantic, { ...base, anchor: null }));\\n const attribute = pickBest(el, attributeCandidates(el, true));\\n if (attribute) locators.push(build(\\\"stable_attribute\\\", el, attribute, { ...base, anchor: null }));\\n const relational = relationalCandidate(el);\\n if (relational)\\n locators.push(\\n build(\\\"relational\\\", el, relational.candidate, { ...base, anchor: relational.anchor })\\n );\\n locators.push(build(\\\"css\\\", el, structuralCss(el), { ...base, anchor: null }));\\n locators.push(build(\\\"xpath\\\", el, structuralXPath(el), { ...base, anchor: null }));\\n locators.sort(compareLocators);\\n const families = new Set(\\n locators.map((l) => l.strategy).filter((s) => INDEPENDENT_FAMILIES.has(s))\\n );\\n const independent = Math.max(1, Math.min(3, families.size));\\n const hasUnique = locators.some((l) => l.unique);\\n const reasons = [];\\n const required = hasUniqueExplicitIdentifier(locators) || hasUniqueNamedSemanticWithBackup(locators) ? REQUIRED_STRATEGIES_WITH_ID : REQUIRED_STRATEGIES;\\n if (independent < required) {\\n const missing = Array.from(INDEPENDENT_FAMILIES).filter((s) => !families.has(s));\\n reasons.push(\\n `only ${independent} independent strateg${independent === 1 ? \\\"y\\\" : \\\"ies\\\"} (no ${missing.join(\\\" or \\\")} locator could be built)`\\n );\\n }\\n if (!hasUnique) {\\n reasons.push(\\\"no locator matches exactly one element\\\");\\n } else if (!locators.some((l) => l.unique && l.stability !== \\\"volatile\\\")) {\\n reasons.push(\\\"only position-based locators are unique\\\");\\n }\\n const needsReview = reasons.length > 0;\\n return {\\n locators,\\n independent_strategy_count: independent,\\n has_unique: hasUnique,\\n needs_review: needsReview,\\n review_reason: needsReview ? reasons.join(\\\"; \\\") : null\\n };\\n }\\n\\n // src/sha256.ts\\n var K = new Uint32Array([\\n 1116352408,\\n 1899447441,\\n 3049323471,\\n 3921009573,\\n 961987163,\\n 1508970993,\\n 2453635748,\\n 2870763221,\\n 3624381080,\\n 310598401,\\n 607225278,\\n 1426881987,\\n 1925078388,\\n 2162078206,\\n 2614888103,\\n 3248222580,\\n 3835390401,\\n 4022224774,\\n 264347078,\\n 604807628,\\n 770255983,\\n 1249150122,\\n 1555081692,\\n 1996064986,\\n 2554220882,\\n 2821834349,\\n 2952996808,\\n 3210313671,\\n 3336571891,\\n 3584528711,\\n 113926993,\\n 338241895,\\n 666307205,\\n 773529912,\\n 1294757372,\\n 1396182291,\\n 1695183700,\\n 1986661051,\\n 2177026350,\\n 2456956037,\\n 2730485921,\\n 2820302411,\\n 3259730800,\\n 3345764771,\\n 3516065817,\\n 3600352804,\\n 4094571909,\\n 275423344,\\n 430227734,\\n 506948616,\\n 659060556,\\n 883997877,\\n 958139571,\\n 1322822218,\\n 1537002063,\\n 1747873779,\\n 1955562222,\\n 2024104815,\\n 2227730452,\\n 2361852424,\\n 2428436474,\\n 2756734187,\\n 3204031479,\\n 3329325298\\n ]);\\n var rotr = (x, n) => x >>> n | x << 32 - n;\\n function sha256Hex(data) {\\n const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);\\n padded.set(data);\\n padded[data.length] = 128;\\n const view = new DataView(padded.buffer);\\n view.setUint32(padded.length - 8, Math.floor(data.length / 536870912));\\n view.setUint32(padded.length - 4, data.length << 3 >>> 0);\\n const h = new Uint32Array([\\n 1779033703,\\n 3144134277,\\n 1013904242,\\n 2773480762,\\n 1359893119,\\n 2600822924,\\n 528734635,\\n 1541459225\\n ]);\\n const w = new Uint32Array(64);\\n for (let off = 0; off < padded.length; off += 64) {\\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\\n for (let i = 16; i < 64; i++) {\\n const a2 = w[i - 15];\\n const b2 = w[i - 2];\\n const s0 = rotr(a2, 7) ^ rotr(a2, 18) ^ a2 >>> 3;\\n const s1 = rotr(b2, 17) ^ rotr(b2, 19) ^ b2 >>> 10;\\n w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;\\n }\\n let [a, b, c, d, e, f, g, hh] = h;\\n for (let i = 0; i < 64; i++) {\\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\\n const ch = e & f ^ ~e & g;\\n const t1 = hh + s1 + ch + K[i] + w[i] | 0;\\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\\n const maj = a & b ^ a & c ^ b & c;\\n const t2 = s0 + maj | 0;\\n hh = g;\\n g = f;\\n f = e;\\n e = d + t1 | 0;\\n d = c;\\n c = b;\\n b = a;\\n a = t1 + t2 | 0;\\n }\\n const next = [a, b, c, d, e, f, g, hh];\\n for (let i = 0; i < 8; i++) h[i] = h[i] + next[i] | 0;\\n }\\n return Array.from(h, (x) => x.toString(16).padStart(8, \\\"0\\\")).join(\\\"\\\");\\n }\\n\\n // src/family.ts\\n var NTH_PICK = /\\\\s>>\\\\snth=-?\\\\d+\\\\s*$/;\\n var XPATH_INDEX = /\\\\[\\\\d+\\\\]/;\\n var CSS_NTH = /:nth-(of-type|child)\\\\(/;\\n function withoutQuotedText(expression) {\\n return expression.replace(/'[^']*'|\\\"[^\\\"]*\\\"/g, \\\"''\\\");\\n }\\n function strategyFamily(locator) {\\n const expression = locator.expression;\\n if (NTH_PICK.test(expression)) return \\\"position\\\";\\n const unquoted = withoutQuotedText(expression);\\n if (locator.strategy !== \\\"xpath\\\" && CSS_NTH.test(unquoted)) return \\\"position\\\";\\n if (locator.strategy === \\\"xpath\\\" && XPATH_INDEX.test(unquoted)) return \\\"position\\\";\\n if (locator.strategy === \\\"semantic\\\") return \\\"semantic\\\";\\n if (locator.strategy === \\\"relational\\\") return \\\"relational\\\";\\n return \\\"attribute\\\";\\n }\\n\\n // src/verification.ts\\n var LONG_TEXT = 80;\\n var MAX_WORDS = 40;\\n var MAX_WORD_LENGTH = 80;\\n var MAX_VALUE_LENGTH = 200;\\n var IDENTIFIER_KINDS = [\\n \\\"name\\\",\\n \\\"id\\\",\\n \\\"type\\\",\\n \\\"autocomplete\\\",\\n \\\"test_id\\\",\\n \\\"role\\\",\\n \\\"accessible_name\\\",\\n \\\"label_text\\\"\\n ];\\n var TEST_ID_ATTRS = [\\\"data-testid\\\", \\\"data-test-id\\\", \\\"data-test\\\", \\\"data-cy\\\", \\\"data-qa\\\"];\\n function isSecretField(el, tools) {\\n if (el.tagName === \\\"INPUT\\\") {\\n const type = (el.getAttribute(\\\"type\\\") ?? \\\"\\\").toLowerCase();\\n if (type === \\\"password\\\" || type === \\\"hidden\\\") return true;\\n }\\n return tools.isSecret(el);\\n }\\n function readIdentifier(el, kind) {\\n let raw = null;\\n if (kind === \\\"name\\\" || kind === \\\"id\\\" || kind === \\\"type\\\" || kind === \\\"autocomplete\\\") {\\n raw = el.getAttribute(kind);\\n } else if (kind === \\\"test_id\\\") {\\n for (const attr of TEST_ID_ATTRS) {\\n const found = el.getAttribute(attr);\\n if (found !== null && found.trim() !== \\\"\\\") {\\n raw = found;\\n break;\\n }\\n }\\n } else if (kind === \\\"role\\\") {\\n raw = el.getAttribute(\\\"role\\\") ?? implicitRole(el);\\n } else {\\n const named = accessibleName(el);\\n if (named !== null) {\\n const fromLabel = named.source === \\\"label\\\";\\n if (kind === \\\"label_text\\\" === fromLabel) raw = named.name;\\n }\\n }\\n if (raw === null) return null;\\n const value = normalizeSpace(raw);\\n return value === \\\"\\\" ? null : value.slice(0, MAX_VALUE_LENGTH);\\n }\\n function countSameValue(el, kind, value) {\\n let count = 0;\\n const doc = el.ownerDocument;\\n for (const other of Array.from(doc.getElementsByTagName(el.tagName))) {\\n if (readIdentifier(other, kind) === value) count++;\\n }\\n return count;\\n }\\n function repeatedRow(el) {\\n const parent = el.parentElement;\\n if (parent === null) return null;\\n const tag = el.tagName;\\n if (tag === \\\"TD\\\" || tag === \\\"TH\\\" || tag === \\\"OPTION\\\") return null;\\n const role = el.getAttribute(\\\"role\\\");\\n const rowLike = tag === \\\"TR\\\" || tag === \\\"LI\\\" || role === \\\"row\\\" || role === \\\"listitem\\\";\\n if (!rowLike && el.className.trim() === \\\"\\\") return null;\\n const same = Array.from(parent.children).filter(\\n (child) => child.tagName === tag && child.getAttribute(\\\"role\\\") === role && (rowLike || child.className === el.className)\\n );\\n if (same.length < 2) return null;\\n return { kind: rowLike ? \\\"row\\\" : \\\"card\\\", index: same.indexOf(el) };\\n }\\n var SKIPPED_TEXT_TAGS2 = /* @__PURE__ */ new Set([\\n \\\"SCRIPT\\\",\\n \\\"STYLE\\\",\\n \\\"NOSCRIPT\\\",\\n \\\"TEXTAREA\\\",\\n \\\"SELECT\\\",\\n \\\"TEMPLATE\\\"\\n ]);\\n function spacedText(el) {\\n if (SKIPPED_TEXT_TAGS2.has(el.tagName)) return \\\"\\\";\\n const parts = [];\\n for (let child = el.firstChild; child; child = child.nextSibling) {\\n if (child.nodeType === 3) parts.push(child.nodeValue ?? \\\"\\\");\\n else if (child.nodeType === 1) parts.push(spacedText(child));\\n }\\n return parts.join(\\\" \\\");\\n }\\n function wordsOf(text) {\\n return text.toLowerCase().split(/\\\\s+/).map((word) => word.replace(/[^\\\\p{L}\\\\p{N}]/gu, \\\"\\\")).filter((word) => word !== \\\"\\\");\\n }\\n function rowTextOf(row, tools, keepWords) {\\n const raw = normalizeSpace(spacedText(row)).trim();\\n if (raw === \\\"\\\") return null;\\n const text = normalizeSpace(tools.scrub(raw)).trim();\\n if (text !== raw) return null;\\n const digits = (text.match(/\\\\d/g) ?? []).length;\\n const volatile = digits >= 2 || text.length > LONG_TEXT;\\n const stable = volatile && !keepWords ? [] : wordsOf(text).filter((word) => !/\\\\d/.test(word)).slice(0, MAX_WORDS).map((word) => word.slice(0, MAX_WORD_LENGTH));\\n return {\\n stable_words: stable,\\n volatile,\\n length: text.length,\\n hash: sha256Hex(new TextEncoder().encode(text.toLowerCase()))\\n };\\n }\\n function readNeighbour(el, tools) {\\n return neighbourOf(el, tools, false);\\n }\\n function neighbourOf(el, tools, keepWords) {\\n let node = el.parentElement;\\n while (node !== null && node.tagName !== \\\"BODY\\\" && node.tagName !== \\\"HTML\\\") {\\n const tag = node.tagName;\\n let kind = null;\\n let rowIndex = null;\\n if (tag === \\\"FORM\\\") kind = \\\"form\\\";\\n else if (tag === \\\"FIELDSET\\\") kind = \\\"fieldset\\\";\\n else {\\n const row = repeatedRow(node);\\n if (row !== null) {\\n kind = row.kind;\\n rowIndex = row.index;\\n }\\n }\\n if (kind !== null) {\\n const role = el.getAttribute(\\\"role\\\") ?? implicitRole(el);\\n const peers = Array.from(node.getElementsByTagName(el.tagName)).filter(\\n (peer) => (peer.getAttribute(\\\"role\\\") ?? implicitRole(peer)) === role\\n );\\n return {\\n container_kind: kind,\\n row_index: rowIndex,\\n index_in_container: Math.max(0, peers.indexOf(el)),\\n row_text: kind === \\\"form\\\" || kind === \\\"fieldset\\\" ? null : rowTextOf(node, tools, keepWords)\\n };\\n }\\n node = node.parentElement;\\n }\\n return null;\\n }\\n function captureVerification(el, tools) {\\n return captureWith(el, tools, false);\\n }\\n function captureVerificationForReplay(el, tools) {\\n return captureWith(el, tools, true);\\n }\\n function captureWith(el, tools, keepWords) {\\n const identifiers = [];\\n if (!isSecretField(el, tools)) {\\n for (const kind of IDENTIFIER_KINDS) {\\n const value = readIdentifier(el, kind);\\n if (value === null) continue;\\n if (tools.scrub(value) !== value) continue;\\n const unique = countSameValue(el, kind, value) === 1;\\n const trusted = kind === \\\"id\\\" ? unique && !idVolatility(value).volatile : unique;\\n identifiers.push({ kind, value, unique_at_record: trusted });\\n }\\n }\\n return { captured_by: \\\"recorder\\\", identifiers, neighbour: neighbourOf(el, tools, keepWords) };\\n }\\n var SECRET_FIELD_HINT = /pass|pwd|secret|token|api.?key|auth|otp|cvv|cvc|card|ssn|\\\\bpin\\\\b/i;\\n var UNSAFE_TEXT = /@|:\\\\/\\\\/|www\\\\.|\\\\d{4,}|(?=[A-Za-z0-9_+/=-]*\\\\d)(?=[A-Za-z0-9_+/=-]*[A-Za-z])[A-Za-z0-9_+/=-]{20,}/;\\n var storageCaptureTools = {\\n scrub: (text) => UNSAFE_TEXT.test(text) ? \\\"[REDACTED]\\\" : text,\\n isSecret: (el) => {\\n const type = (el.getAttribute(\\\"type\\\") ?? \\\"\\\").toLowerCase();\\n if (type === \\\"password\\\" || type === \\\"hidden\\\") return true;\\n return [\\\"name\\\", \\\"id\\\", \\\"autocomplete\\\"].some(\\n (attr) => SECRET_FIELD_HINT.test(el.getAttribute(attr) ?? \\\"\\\")\\n );\\n }\\n };\\n return __toCommonJS(src_exports);\\n})();\\n\"; }", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { errors } from 'playwright';\nimport { BrowserUnavailableError, isBrowserName, launchBrowser } from './browsers.js';\nimport type { BrowserName, BrowserSettings } from './browsers.js';\nimport type {\n Browser,\n BrowserContext,\n Page,\n Route,\n Request,\n Response,\n ConsoleMessage,\n Locator,\n Download,\n FrameLocator,\n} from 'playwright';\nimport type { RunBundle } from './dashboard-client.js';\nimport { RowValues } from './row-values.js';\nimport { placeholderFile, type PlaceholderFile } from './placeholder-files.js';\nimport { createHash } from 'node:crypto';\nimport {\n findAmbiguousConflicts,\n findLocatorConflicts,\n nameElement,\n type LocatorConflict,\n type UniqueLocator,\n} from './locator-agreement.js';\nimport { HostGuard, systemResolver, type HostResolver } from './host-guard.js';\nimport { maskSecretsInTrace } from './trace-redaction.js';\nimport { installScreenshotHide } from './screenshot-hide.js';\nimport { hideField, hideSecretFields, holdsSecret } from './secret-screen.js';\nimport { ExportCollector, type ExportWithheld } from './exports.js';\nimport type { Logger } from './logger.js';\nimport {\n GeneratedValues,\n isGeneratedKind,\n systemGeneratedValues,\n type GeneratedValuesOptions,\n} from './generated-values.js';\nimport type { Verification } from '@locus/locator-engine';\nimport { inspectFoundElement } from './target-reader.js';\nimport { ambiguousBlocksWinner, verifyTarget, type TargetCheck } from './target-verification.js';\nimport { DialogResponder, armsDialogs, type DialogExpectation } from './dialogs.js';\nimport {\n NetworkSettler,\n REPLAY_MARKER_SCRIPT,\n collapseWhitespace,\n describeExpected,\n errorLine,\n matchesExpected,\n pollCondition,\n PhaseTimer,\n RunBudget,\n} from './conditions.js';\nimport type { ConditionProbe, ExpectedValue, StepTimings } from './conditions.js';\nimport {\n captureNearMatches,\n captureResolvedMatch,\n recordedTargetOf,\n type NearMatch,\n type NearMatchOptions,\n} from './near-match.js';\n\nexport type { RunBundle } from './dashboard-client.js';\n\n/**\n * Makes text safe to put inside a regular expression.\n * Characters like `.` or `*` have special meaning in a regex; this adds a\n * backslash before them so the text is matched exactly as written.\n */\nexport function escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * How a saved value is put into a field:\n * 'literal' means as written, 'regex' means escaped so it is matched\n * exactly when the field is a regular expression.\n */\nexport type FieldMode = 'literal' | 'regex';\n\n/**\n * Returns the test case's own variables as name to default value.\n *\n * What it is: the `definition.variables` list (each `{name, value}`) as a plain table.\n * What it does: lets `{{name}}` of a declared variable resolve to its default when no data\n * row, environment variable or secret of that name exists, so a check bound to a data column\n * keeps working after the data set is removed.\n * How: copies only entries with a string name and value, through a Map so a strange name\n * cannot touch the object prototype.\n */\nfunction definitionDefaults(bundle: RunBundle): Record<string, string> {\n const list = (bundle.definition.variables || []) as Array<{ name?: unknown; value?: unknown }>;\n const table = new Map<string, string>();\n for (const variable of list) {\n if (typeof variable.name === 'string' && typeof variable.value === 'string') {\n table.set(variable.name, variable.value);\n }\n }\n return Object.fromEntries(table);\n}\n\n/**\n * Fills in {{name}} placeholders in a test's text.\n * It knows three kinds of values: fixed ones (BASE_URL, HOST, ORIGIN, ENV\n * plus the environment's variables and secrets), values extracted from\n * responses (`setVariable`), and values saved from earlier fill steps\n * (`saveValue`). Keeping them in separate places lets us refuse a saved\n * name that would hide a secret or variable.\n */\nexport class VariableInterpolator {\n /**\n * Fixed and extracted values by name, for example BASE_URL or a secret.\n * This is what `interpolate` reads.\n */\n private readonly tokens: Record<string, string>;\n /**\n * The data-driven row of this run (empty when the test case has no data set).\n * The \"variable\" fill step reads it through `rowValueFor`, and a check's expected text\n * uses it to refuse secret columns.\n */\n private readonly row: RowValues;\n /**\n * Every `save_as` name the test declares. A {{name}} that is in this\n * list must have been saved by an earlier step, otherwise the step fails.\n */\n private readonly savedNames: ReadonlySet<string>;\n /**\n * Values saved so far in this run, by name.\n */\n private readonly saved = new Map<string, string>();\n /**\n * The names of the vault secrets this run received (names only, never values).\n * Used to refuse saving a value whose text names a secret as `{{name}}`: the saved\n * value would carry the secret into a check's expected text, which a failed check prints.\n */\n private readonly vaultNames: ReadonlySet<string>;\n /**\n * The name of the step now running, used only to word the message when a\n * {{token}} is not defined. Empty before the first step starts.\n */\n private stepLabel = '';\n\n /**\n * Builds the value table from the run bundle.\n * Collects the declared `save_as` names, works out host and origin from\n * the base URL (an invalid URL is ignored here; it is reported when the\n * run is validated) and merges the built-ins, variables and secrets.\n * Order, lowest first: built-ins, the test case's own variable defaults, environment\n * variables, the data row, secrets. The test case defaults sit lowest so `{{name}}` of a\n * declared variable still works when the test case has no data set (the same fallback\n * the \"variable\" fill source uses); an environment variable or a row value of the same\n * name wins over the default. Secrets come last so they win over everything. Every\n * replace pass runs once over the field's own text, so a value put in (a row cell, a\n * saved value) is never expanded again.\n */\n constructor(bundle: RunBundle) {\n // The `save_as` names found in the steps.\n const declared = new Set<string>();\n for (const step of bundle.definition.steps ?? []) {\n const name = (step as { save_as?: unknown }).save_as;\n if (typeof name === 'string' && name !== '') {\n declared.add(name);\n }\n }\n this.savedNames = declared;\n // The base URL without trailing slashes.\n // If no override was supplied, fall back to the origin of the test's start URL so\n // that {{BASE_URL}} and built-ins remain usable in single-environment replays.\n let baseUrl = bundle.base_url_override?.replace(/\\/+$/, '') || '';\n if (!baseUrl && bundle.definition?.start_url) {\n try {\n const u = new URL(bundle.definition.start_url);\n baseUrl = u.origin;\n } catch {\n // invalid URL handled during validation\n }\n }\n // Host part of the base URL, for the HOST value.\n let host = '';\n // Origin (scheme, host and port) of the base URL, for ORIGIN.\n let origin = '';\n if (baseUrl) {\n try {\n const u = new URL(baseUrl);\n host = u.host;\n origin = u.origin;\n } catch {\n // invalid URL handled during validation\n }\n }\n\n this.row = new RowValues(bundle.row, bundle.secrets || {});\n this.vaultNames = new Set(Object.keys(bundle.secrets || {}));\n this.tokens = {\n BASE_URL: baseUrl,\n HOST: host,\n ORIGIN: origin,\n ENV: bundle.environment_slug || 'default',\n ...definitionDefaults(bundle),\n ...(bundle.variables || {}),\n ...this.row.asTokens(),\n ...(bundle.secrets || {}),\n };\n }\n\n /**\n * Returns this run's row value for a variable name, or undefined when the row has no such\n * column. The fill step with value source \"variable\" calls this first and falls back to\n * the definition's own default, so both lookups read the same row.\n */\n rowValueFor(name: string): string | undefined {\n return this.row.valueFor(name);\n }\n\n /**\n * Tells whether a variable name is a secret column of this run's row. The fill step uses\n * it to refuse `save_as` on a step backed by a secret column.\n */\n isRowSecretColumn(name: string): boolean {\n return this.row.isSecretColumn(name);\n }\n\n /**\n * Stores a value (for example one extracted from a response) so later\n * {{key}} placeholders pick it up. Replaces an existing value.\n */\n setVariable(key: string, value: string): void {\n this.tokens[key] = value;\n }\n\n /**\n * Remembers the text a fill step typed, under its `save_as` name, so later\n * steps can use it.\n * The text must be the final text the field received (every token already filled in):\n * later fields insert it as it is and never expand it again. The caller refuses text that\n * holds or names a secret before it gets here.\n * A name that already exists as a built-in, variable, secret or extracted\n * value is refused, so a saved value can never hide one of those.\n */\n saveValue(name: string, text: string): void {\n if (Object.prototype.hasOwnProperty.call(this.tokens, name)) {\n throw new StepFailure(\n 'definition_incomplete',\n `saved value \"${name}\" has the same name as a secret, variable or environment value`,\n );\n }\n this.saved.set(name, text);\n }\n\n /**\n * Returns the saved values, to include in the run result.\n */\n savedValues(): Record<string, string> {\n return Object.fromEntries(this.saved);\n }\n\n /**\n * Fills in a template field (one whose expand switch is on) in a single pass.\n *\n * What it does: replaces each {{name}} with, in this order, the value saved earlier in\n * this run (for names the test declares with `save_as`) or a built-in, variable, row,\n * secret or extracted value. A declared saved name that nothing saved yet, or a name\n * nothing defines, fails the step. `\\{{name}}` becomes the plain text `{{name}}`.\n * How: one `replace` over the field's own text. Text that a token puts in is never\n * scanned again, so a saved value or a row cell that itself holds `{{x}}` stays as it was\n * typed. This is the guard that stops a secret from reaching a check through a saved\n * value: a second pass would turn a saved `{{pw}}` into the password. In a regular\n * expression field the saved value is escaped, so it matches only itself.\n */\n expandTemplate(input: string, mode: FieldMode): string {\n if (!input || typeof input !== 'string') return input;\n return input.replace(\n /(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g,\n (match: string, escape: string | undefined, key: string) => {\n if (escape !== undefined) return match.slice(1);\n if (this.savedNames.has(key)) {\n const value = this.saved.get(key);\n if (value === undefined) {\n throw new StepFailure(\n 'definition_incomplete',\n `saved value \"${key}\" has not been saved by an earlier step in this run`,\n );\n }\n return mode === 'regex' ? escapeRegExp(value) : value;\n }\n const val = this.tokens[key];\n if (val === undefined) {\n const where = this.stepLabel === '' ? '' : ` in step \"${this.stepLabel}\"`;\n throw new StepFailure(\n 'definition_incomplete',\n `MISSING_VARIABLE: {{${key}}}${where} is not defined by the environment, a secret, an earlier step's extracted value or an earlier step's saved value; write \\\\{{${key}}} to use it as plain text`,\n );\n }\n return val;\n },\n );\n }\n\n /**\n * Returns the first secret named as {{name}} in a piece of text, or undefined.\n *\n * What it does: looks for an unescaped {{name}} that is a vault secret of this run or a\n * secret column of this run's row. How: one scan with the shared token pattern. Used before\n * a fill step saves its value: that text must not be saved, because the saved value would\n * carry the secret into a later check's expected text. Checking by name also catches short\n * secrets, which the by-value check (`holdsSecret`) skips on purpose.\n */\n secretNameIn(text: string): string | undefined {\n if (!text || typeof text !== 'string') return undefined;\n for (const match of text.matchAll(/(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g)) {\n const name = match[2] as string;\n if (match[1] === undefined && (this.vaultNames.has(name) || this.row.isSecretColumn(name))) {\n return name;\n }\n }\n return undefined;\n }\n\n /**\n * Tells the interpolator which step is running, so a missing {{token}}\n * can name the step in its message. The step loop calls it once per step.\n */\n enterStep(label: string): void {\n this.stepLabel = label;\n }\n\n /**\n * Prepares one check or value field. With `expand` off the text is used\n * as written (only built-ins, variables and secrets are filled in, and a\n * name nothing defines is left alone, because the field is not a template).\n * With it on, saved values and every other name are filled in by one pass\n * (`expandTemplate`), and any name still undefined fails the step.\n */\n interpolateField(input: string, expand: boolean, mode: FieldMode): string {\n this.refuseSecretColumns(input);\n if (!expand) return this.interpolate(input);\n return this.expandTemplate(input, mode);\n }\n\n /**\n * Prepares the expected text of a check or wait, and refuses one that would prove nothing.\n *\n * What it is: `interpolateField` for an expected value, plus one guard.\n * What it does: fills in the text the same way, then fails the step as `definition_incomplete`\n * when the text used at least one `{{name}}` and came out empty (or only spaces) while the\n * rule is `contains` or `regex`. Every page \"contains\" the empty text and the empty pattern\n * matches anything, so such a check would always pass and hide a real bug. Spaces count as\n * empty because the page-text check squeezes and trims its expected text before comparing,\n * so `{{a}} {{b}}` with both values empty would also become \"\".\n * Why: a test variable's default, an empty row cell or an empty environment variable can all\n * fill a token with \"\". The common case is a check bound to a data column after the data set\n * was deleted, when only the (often empty) default is left. An `exact` rule is left alone:\n * \"this text is empty\" is a real check. The message names the tokens, never the values.\n */\n interpolateExpected(input: string, expand: boolean, match: string): string {\n // The expected text with every value filled in; this is what the check compares.\n const filled = this.interpolateField(input, expand, match === 'regex' ? 'regex' : 'literal');\n if (filled.trim() !== '' || (match !== 'contains' && match !== 'regex')) return filled;\n // The unescaped tokens the text used; text without one was empty on purpose.\n const names = [...(input || '').matchAll(/(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g)]\n .filter((m) => m[1] === undefined)\n .map((m) => `{{${m[2] as string}}}`);\n if (names.length === 0) return filled;\n // \" in step \"<name>\"\" for the message, or nothing when no step is running.\n const where = this.stepLabel === '' ? '' : ` in step \"${this.stepLabel}\"`;\n throw new StepFailure(\n 'definition_incomplete',\n `the expected text ${names.join(' ')}${where} is empty after its values are filled in, so this \"${match}\" check would pass on any page; give the variable a default value, or give the data row a value`,\n );\n }\n\n /**\n * Fails the step when a check or wait field uses a secret column as {{name}}.\n * The expected text of a check is printed in its failure message, so a secret column\n * there would leak the value. An escaped `\\{{name}}` is plain text and is allowed.\n * The message names the column, never the value.\n */\n private refuseSecretColumns(input: string): void {\n if (!input || typeof input !== 'string') return;\n for (const match of input.matchAll(/(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g)) {\n if (match[1] === undefined && this.row.isSecretColumn(match[2] as string)) {\n throw new StepFailure(\n 'definition_incomplete',\n `the secret column \"${match[2] as string}\" cannot be used in a check's expected text`,\n );\n }\n }\n }\n\n /**\n * Like `interpolate`, but a {{name}} that is not a built-in, variable,\n * secret, extracted value or saved value fails the step as\n * `definition_incomplete` (the MISSING_VARIABLE rule).\n * It reads the table as it is right now, so a value an earlier step\n * extracted counts and one a later step will extract does not. Saved\n * names are not in the table; they are handled by `resolveSaved` first.\n * A name with a backslash in front (`\\{{name}}`) is never looked up and\n * never fails: the backslash is dropped and `{{name}}` stays as plain text.\n */\n interpolateStrict(input: string): string {\n if (!input || typeof input !== 'string') return input;\n return input.replace(\n /(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g,\n (match: string, escape: string | undefined, key: string) => {\n if (escape !== undefined) return match.slice(1);\n const val = this.tokens[key];\n if (val === undefined) {\n const where = this.stepLabel === '' ? '' : ` in step \"${this.stepLabel}\"`;\n throw new StepFailure(\n 'definition_incomplete',\n `MISSING_VARIABLE: {{${key}}}${where} is not defined by the environment, a secret, an earlier step's extracted value or an earlier step's saved value; write \\\\{{${key}}} to use it as plain text`,\n );\n }\n return val;\n },\n );\n }\n\n /**\n * Replaces {{name}} with a built-in, variable, secret or extracted value.\n * Unknown names are left as they are, so they stay visible in reports.\n * A name with a backslash in front (`\\{{name}}`) is kept as plain\n * `{{name}}` without the backslash, even when a value exists for it.\n */\n interpolate(input: string): string {\n if (!input || typeof input !== 'string') return input;\n return input.replace(\n /(\\\\)?\\{\\{([A-Za-z0-9_]+)\\}\\}/g,\n (match: string, escape: string | undefined, key: string) => {\n if (escape !== undefined) return match.slice(1);\n const val = this.tokens[key];\n return val !== undefined ? val : match;\n },\n );\n }\n}\n\n/**\n * Reads a value out of JSON using a simple path such as `$.data.items[0].id`.\n * A leading `$` and `.` are optional; `[0]` and `['key']` both work.\n * Returns undefined if any part of the path is missing, and the whole\n * object for an empty path.\n */\nexport function extractJSONPath(obj: unknown, rawPath: string): unknown {\n if (obj === null || obj === undefined) return undefined;\n // The path with the leading `$` and `.` removed.\n let p = rawPath.trim();\n if (p.startsWith('$')) {\n p = p.slice(1);\n }\n if (p.startsWith('.')) {\n p = p.slice(1);\n }\n if (!p) return obj;\n\n // The path rewritten so brackets become dots: `a[0].b` becomes `a.0.b`.\n const normalized = p.replace(/\\[['\"]?([^'\"\\]]+)['\"]?\\]/g, '.$1').replace(/^\\./, '');\n\n // The path split into its parts, for example ['a', '0', 'b'].\n const segments = normalized.split('.').filter((s) => s.length > 0);\n // The place we have reached while walking down the path.\n let curr: unknown = obj;\n for (const seg of segments) {\n if (curr === null || curr === undefined) {\n return undefined;\n }\n if (Array.isArray(curr)) {\n const idx = Number(seg);\n if (Number.isNaN(idx) || idx < 0 || idx >= curr.length) {\n return undefined;\n }\n curr = curr[idx];\n } else if (typeof curr === 'object') {\n curr = (curr as Record<string, unknown>)[seg];\n } else {\n return undefined;\n }\n }\n return curr;\n}\n\n/**\n * Turns a value found in JSON into text. Strings stay as they are, numbers\n * and booleans use String(), and anything else becomes JSON text.\n */\nexport function stringifyExtracted(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n return JSON.stringify(value);\n}\n\n/**\n * Returns the JSON type name of a value: 'null', 'array', 'string',\n * 'number', 'boolean' or 'object'. null and arrays get their own names\n * because JavaScript would call both 'object'.\n */\nfunction jsonTypeName(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n return Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Runs one check on a JSON body (from a response or a request).\n * Returns null if the check passes, or a short reason if it fails.\n * Checks: the field exists and is not null, has a given type, or its text\n * matches exactly / contains / a regex.\n */\nexport function bodyCheckFailure(body: unknown, check: RawBodyCheck): string | null {\n // The value at the check's JSON path, or undefined if missing.\n const found = extractJSONPath(body, check.json_path);\n if (found === undefined) {\n return `${check.json_path} not found`;\n }\n if (check.match === 'exists') {\n return found === null ? `${check.json_path} is null` : null;\n }\n if (check.match === 'type') {\n const actual = jsonTypeName(found);\n return actual === check.value\n ? null\n : `${check.json_path} expected type ${check.value}, got ${actual}`;\n }\n const expected: ExpectedValue = {\n match: check.match,\n value: check.value ?? '',\n expand_values: false,\n };\n const read = stringifyExtracted(found);\n try {\n return matchesExpected(read, expected)\n ? null\n : `${check.json_path} expected ${describeExpected(expected)}, got '${read.length > 100 ? `${read.slice(0, 100)}...` : read}'`;\n } catch (err: unknown) {\n return `${check.json_path} ${errorLine(err)}`;\n }\n}\n\n/**\n * Says which body a check reads: 'request' or 'response' (the default).\n */\nfunction sourceName(check: RawBodyCheck): string {\n return check.source === 'request' ? 'request' : 'response';\n}\n\n/**\n * Runs all body checks and returns the first failure, or null if all pass\n * (or there are none). Each body is parsed only once. A check on a body\n * that is missing or not JSON fails with a clear reason.\n */\nexport function bodyChecksFailure(\n bodies: { response: string; request: string | null },\n checks: RawBodyCheck[],\n): string | null {\n // Each body parsed as JSON once (undefined when it is not valid JSON).\n const parsed = new Map<string, unknown>();\n for (const check of checks) {\n const name = sourceName(check);\n const text = name === 'request' ? bodies.request : bodies.response;\n if (!parsed.has(name)) {\n try {\n parsed.set(name, JSON.parse(text ?? ''));\n } catch {\n parsed.set(name, undefined);\n }\n }\n const body = parsed.get(name);\n if (body === undefined) {\n return text === null ? 'request had no body' : `${name} body is not JSON`;\n }\n const failure = bodyCheckFailure(body, check);\n if (failure !== null) {\n return name === 'request' ? `request ${failure}` : failure;\n }\n }\n return null;\n}\n\n/**\n * Settings for the Executor: browser paths, sandbox choices and the list of enabled\n * browsers (all from BrowserSettings, read from the runner's .env), timeouts for steps and\n * settling, retries, look-alike search settings, overall run time, whether\n * localhost targets are allowed, an optional logger, and optional random\n * sources for generated values (tests pass fixed ones).\n */\nexport interface ExecutorOptions extends BrowserSettings {\n stepTimeoutMs: number;\n settleTimeoutMs: number;\n settleQuietMs: number;\n /** Extra attempts for a failed step whose failure_policy is retry_if_safe and that is idempotent. */\n stepRetries: number;\n /** Captures similar elements when a step's locators fail. */\n nearMatch: NearMatchOptions;\n runTimeoutMs: number;\n allowLoopback?: boolean;\n /** When true (customer-run runner local mode), allows RFC 1918 private subnets and loopback while strictly blocking cloud metadata. */\n allowPrivateNetworks?: boolean;\n /**\n * Finds the addresses of a host name for the private-address check. Left out, the\n * system resolver is used; tests pass a fake so no network is touched.\n */\n resolveHost?: HostResolver;\n /** Receives screenshot capture failures; without it they are dropped. */\n log?: Logger;\n /** Clock and random source for generated values; tests inject fixed ones. */\n generatedValues?: GeneratedValuesOptions;\n /**\n * Downloads the bytes of a picked fixture for a run (the dashboard client's `fixture`).\n * Required: the runner cannot start without a way to read fixtures.\n */\n fetchFixture: (runId: string, fixtureId: string) => Promise<Buffer>;\n}\n\n/**\n * One option a select step wants: its value, and the label that was\n * recorded next to it when known (used as a backup).\n */\nexport interface OptionChoice {\n value: string;\n label: string | null;\n}\n\n/**\n * Works out which dropdown options a selectOption step wants.\n * If the step has its own value, that single value is used. If the value\n * is 'recorded', the saved values and labels from recording are used.\n * Non-text entries are skipped.\n */\nexport function selectOptionChoices(step: RawStep, textValue: string): OptionChoice[] {\n if (step.value?.source !== 'recorded') {\n return textValue ? [{ value: textValue, label: null }] : [];\n }\n // The option values saved when the test was recorded.\n const recorded = step.params?.values;\n if (!Array.isArray(recorded)) {\n return [];\n }\n // The option labels saved when the test was recorded.\n const labels = Array.isArray(step.params?.labels) ? step.params.labels : [];\n // The dropdown options this step wants.\n const choices: OptionChoice[] = [];\n recorded.forEach((value: unknown, i: number) => {\n if (typeof value !== 'string') {\n return;\n }\n const label: unknown = labels[i];\n choices.push({ value, label: typeof label === 'string' && label !== '' ? label : null });\n });\n return choices;\n}\n\n/**\n * Matches the wanted options against what the dropdown offers now.\n * If a recorded value is gone (ids can differ between environments) we\n * try its recorded label, but only when exactly one option has that\n * label, so we never guess. `missing` describes anything not resolved.\n */\nexport function resolveOptionChoices(\n wanted: OptionChoice[],\n available: Array<{ value: string; label: string }>,\n): { values: string[]; missing: string | null } {\n // Option values to select.\n const values: string[] = [];\n // Wanted values that could not be matched.\n const unresolved: string[] = [];\n for (const choice of wanted) {\n if (available.some((o) => o.value === choice.value || o.label === choice.value)) {\n values.push(choice.value);\n continue;\n }\n // Available options whose label equals the recorded label.\n const byLabel = choice.label === null ? [] : available.filter((o) => o.label === choice.label);\n if (byLabel.length === 1) {\n values.push(byLabel[0]!.value);\n continue;\n }\n unresolved.push(choice.value);\n }\n return {\n values,\n missing: unresolved.length > 0 ? describeMissingOptions(unresolved, available) : null,\n };\n}\n\n/**\n * What one locator strategy found on its last try: how many elements it\n * matched, or the error text if the locator itself was invalid.\n * `loose` is only set for a role locator that matched nothing exactly: it is\n * how many elements the looser backup name pattern matched (see\n * `fuzzyRoleExpression`). It is kept apart from `outcome` because the exact\n * count decides ambiguity and confidence; `loose` only makes the failure\n * message honest.\n */\nexport interface LocatorObservation {\n strategy: string;\n outcome: number | string;\n loose?: number;\n}\n\n/**\n * The names of the locator strategies a step can be resolved with.\n */\ntype StrategyName = NonNullable<StepResolution['resolved_strategy']>;\n\n/**\n * A backup for role locators whose recorded name does not match exactly.\n * It rewrites the name as a case-insensitive pattern and returns the new\n * expression, or null if the locator is not a role locator with a name.\n *\n * Two cases:\n * 1. Two or more capitalised words (for example \"New Funnel Builder\" when\n * the page has extra spacing or the words were joined): any spaces are\n * allowed between the words.\n * 2. Anything else, such as a single word like \"Edit\": only characters that\n * are not letters or digits are allowed before and after the name. This\n * covers an icon-font glyph that the page adds in front of the text (the\n * browser puts it in the accessible name), but never \"Edit Profile\" or\n * \"Editor\", so a different element cannot be picked by mistake.\n */\nexport function fuzzyRoleExpression(expression: string): string | null {\n // Splits the expression into an optional prefix, the role and the name.\n const prefixMatch = /^(.*>>\\s*)?role=([a-zA-Z]+)\\[name=\"([^\"]+)\"\\]$/.exec(expression);\n if (!prefixMatch) {\n return null;\n }\n const prefix = prefixMatch[1] ?? '';\n const role = prefixMatch[2]!;\n const name = prefixMatch[3]!;\n // The capitalised words in the recorded name.\n const words = name.match(/[A-Z][a-z]+/g);\n if (words && words.length >= 2) {\n return `${prefix}role=${role}[name=/${words.join('\\\\s+')}/i]`;\n }\n // The name written so every character is literal inside a /regex/ (the slash too).\n const literal = name.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\n return `${prefix}role=${role}[name=/^\\\\W*${literal}\\\\W*$/i]`;\n}\n\n/**\n * Matches URL paths that look like a sign-in page (login, signin, auth).\n */\nconst LOGIN_PATH = /\\/(login|log-in|signin|sign-in|auth)(\\/|$)/i;\n\n/**\n * Adds a hint to a failure message when it looks like a login problem\n * rather than a bug in the app: an HTTP 401/403 during the step, or the\n * page ending on a sign-in page the test did not start on.\n * Returns an empty text if neither applies.\n */\nexport function authHint(\n pageUrl: string,\n startUrl: string | undefined,\n stepFailedRequests: Array<{ url: string; status: number | null }>,\n): string {\n // The first request in the step that was refused with 401 or 403.\n const denied = stepFailedRequests.find((r) => r.status === 401 || r.status === 403);\n if (denied) {\n return ` [auth: HTTP ${denied.status} from ${denied.url}; the session may be missing or expired]`;\n }\n // Gets the path of a URL, or '' if it is missing or invalid.\n const pathOf = (url: string | undefined): string => {\n try {\n return url ? new URL(url).pathname : '';\n } catch {\n return '';\n }\n };\n // The path of the page the replay ended on.\n const landed = pathOf(pageUrl);\n if (LOGIN_PATH.test(landed) && !LOGIN_PATH.test(pathOf(startUrl))) {\n return ` [auth: replay landed on sign-in page ${landed}; the session may be missing or expired]`;\n }\n return '';\n}\n\n/**\n * What it is: the failure message for locators that disagree.\n * What it does: says which strategy won and what element it found, then each strategy that found\n * a different element, and ends with the way out. When a disagreeing strategy describes its element\n * exactly like the winner (for example two inputs that share one id), it also says that these are\n * two different elements that only look the same, and names the strategies, so a QA does not read\n * \"found X but found X\" as a bug in Locus.\n * How: compares each conflict's description with the winner's description as plain text. Kept short\n * and in plain words because a QA reads it straight in the run report.\n */\nexport function describeLocatorConflict(\n winnerStrategy: string | null,\n winnerElement: string,\n conflicts: LocatorConflict[],\n): string {\n const winner = winnerStrategy ?? 'first match';\n // One phrase per disagreeing strategy.\n const others = conflicts.map((c) => `${c.strategy} found ${c.found}`).join('; ');\n // The strategies whose element reads exactly like the winner's, yet is a different node.\n const lookAlike = conflicts.filter((c) => c.found === winnerElement).map((c) => c.strategy);\n const note =\n lookAlike.length > 0\n ? ` The ${winner} and ${lookAlike.join(' and ')} locators found two different elements that look identical (the page may repeat an id or a name).`\n : '';\n return (\n `Locators point at different elements: ${winner} found ${winnerElement}, ` +\n `but ${others}.${note} Fix or disable the wrong locator.`\n );\n}\n\n/**\n * Scores a locator from its last try: 1 if it matched exactly one\n * element, 1/n if it matched n elements, 0 if it matched none or failed.\n */\nexport function candidateScore(outcome: number | string): number {\n if (typeof outcome === 'string' || outcome === 0) {\n return 0;\n }\n return Math.round((1 / outcome) * 100) / 100;\n}\n\n/**\n * Says how sure we are that the right element was found.\n * After an exact match it is the share of locator strategies that found\n * exactly one element (so agreement between strategies means higher\n * confidence). A fuzzy name match is a fixed 0.5. Nothing found is 0.\n */\nexport function resolutionConfidence(\n observations: LocatorObservation[],\n resolvedBy: 'exact' | 'fuzzy' | null,\n): number {\n if (resolvedBy === null || observations.length === 0) {\n return 0;\n }\n if (resolvedBy === 'fuzzy') {\n return 0.5;\n }\n // How many strategies found exactly one element.\n const unique = observations.filter((o) => o.outcome === 1).length;\n return Math.round((unique / observations.length) * 100) / 100;\n}\n\n/**\n * Splits a position locator into its base expression and its position.\n * The \"Pick by position\" helper writes `<base> >> nth=<N>` (0 is first, -1 is\n * last, and so on, as Playwright reads it). Only a trailing `nth=` counts, so\n * an `nth=` in the middle of a chain is left alone. Returns null when the\n * expression does not end in a position, which is the normal case.\n */\nexport function splitPositionLocator(expression: string): { base: string; offset: number } | null {\n // The base is everything before the final ' >> nth=<integer>'.\n const found = /^([\\s\\S]+) >> nth=(-?\\d+)$/.exec(expression);\n if (found === null) {\n return null;\n }\n return { base: found[1]!, offset: Number(found[2]) };\n}\n\n/**\n * Describes what a position locator picked, given how many elements its base\n * matched. Playwright's offset is 0-based (and negative counts from the end);\n * the report speaks in people's terms, counted from 1. Returns null when the\n * offset falls outside the matched elements, because then nothing was picked.\n */\nexport function describePositionPick(offset: number, matched: number): PositionPick | null {\n // A negative offset counts from the end: -1 is the last element.\n const index = offset >= 0 ? offset + 1 : matched + offset + 1;\n if (matched < 1 || index < 1 || index > matched) {\n return null;\n }\n if (offset === -1) {\n return { position: 'last', index, matched };\n }\n if (offset === 0) {\n return { position: 'first', index, matched };\n }\n return { position: 'nth', index, matched };\n}\n\n/**\n * Writes the error message for an element that could not be pinned down,\n * listing for each strategy whether it found nothing, found too many\n * (ambiguous) or hit an error. This tells a person whether the element\n * is missing or just not specific enough.\n */\nexport function describeResolutionFailure(observations: LocatorObservation[]): string {\n // One short phrase per strategy.\n const parts = observations.map(({ strategy, outcome, loose }) => {\n if (typeof outcome === 'string') {\n return `${strategy}: error ${outcome}`;\n }\n if (outcome === 0 && loose !== undefined && loose > 1) {\n return `${strategy}: no exact match, ${loose} by loose name (ambiguous)`;\n }\n if (outcome === 0) {\n return `${strategy}: no match`;\n }\n return `${strategy}: ${outcome} matches (ambiguous)`;\n });\n return `Element could not be uniquely resolved (${parts.join('; ')})`;\n}\n\n/**\n * The most disabled steps we name in a 'maybe a precondition' hint.\n */\nconst MAX_DISABLED_STEPS_IN_HINT = 3;\n\n/**\n * Adds a hint when nothing matched and earlier steps are turned off:\n * a disabled step might be the one that opens the menu, tab or dialog\n * the element lives in. It only speaks up when every locator found zero\n * elements; a locator that matched several, or errored, is a different\n * problem. Names the nearest disabled steps first.\n */\nexport function describeDisabledPreconditions(\n observations: LocatorObservation[],\n priorSteps: Array<{ name?: string; enabled?: boolean }>,\n): string {\n if (observations.length === 0 || !observations.every((o) => o.outcome === 0)) {\n return '';\n }\n // Descriptions of the disabled earlier steps, nearest first.\n const disabled: string[] = [];\n for (let i = priorSteps.length - 1; i >= 0 && disabled.length < MAX_DISABLED_STEPS_IN_HINT; i--) {\n const prior = priorSteps[i]!;\n if (prior.enabled === false) {\n disabled.push(`step ${i + 1}${prior.name ? ` (${prior.name})` : ''}`);\n }\n }\n if (disabled.length === 0) {\n return '';\n }\n return `. Disabled earlier ${disabled.length === 1 ? 'step' : 'steps'} may be a precondition: ${disabled.join(', ')}`;\n}\n\n/**\n * Writes the error for dropdown options that do not exist, listing what\n * the dropdown does offer (at most 10, to keep the message readable).\n * Returns null if every wanted option exists.\n */\nexport function describeMissingOptions(\n wanted: string[],\n available: Array<{ value: string; label: string }>,\n): string | null {\n // The wanted options that the dropdown does not offer.\n const missing = wanted.filter((w) => !available.some((o) => o.value === w || o.label === w));\n if (missing.length === 0) {\n return null;\n }\n // The offered options we will print, as \"value\" (label).\n const shown = available.slice(0, 10).map((o) => `\"${o.value}\" (${o.label})`);\n if (available.length > shown.length) {\n shown.push(`\u2026 ${available.length - shown.length} more`);\n }\n // The offered options joined into one piece of text.\n const offered = shown.length > 0 ? shown.join(', ') : 'none';\n return `selectOption option not found: ${missing.map((m) => `\"${m}\"`).join(', ')}; available: ${offered}`;\n}\n\n/**\n * Policy options controlling private network and loopback allowance.\n *\n * What it is: configuration for isPrivateOrBlockedHost.\n * What it does: allows fine-grained policy selection between hosted and customer-run local replay.\n * How it works: in local mode, allowPrivateNetworks allows RFC 1918 and loopback while strictly\n * blocking cloud metadata endpoints (169.254.169.254).\n */\nexport interface HostSecurityPolicy {\n allowLoopback?: boolean | undefined;\n allowPrivateNetworks?: boolean | undefined;\n}\n\n/**\n * Decides if one IPv4 address, given as its four numbers, is a place the\n * runner must not visit. It is a small helper for `isPrivateOrBlockedHost`.\n * It blocks link-local (169.254.x) and unspecified 0.x always.\n * In hosted mode, private networks (10.x, 172.16-31.x, 192.168.x) and CGNAT\n * (100.64.0.0/10) are blocked. In customer local mode (allowPrivateNetworks),\n * private networks and CGNAT are allowed. Loopback (127.x) is allowed when\n * allowLoopback is on.\n */\nfunction isBlockedIPv4(\n o1: number,\n o2: number,\n allowLoopback: boolean,\n allowPrivateNetworks: boolean = false,\n): boolean {\n if (o1 === 127) return !allowLoopback;\n if (o1 === 10) return !allowPrivateNetworks;\n if (o1 === 172 && o2 >= 16 && o2 <= 31) return !allowPrivateNetworks;\n if (o1 === 192 && o2 === 168) return !allowPrivateNetworks;\n if (o1 === 169 && o2 === 254) return true;\n if (o1 === 100 && o2 >= 64 && o2 <= 127) return !allowPrivateNetworks;\n if (o1 === 0) return true;\n return false;\n}\n\n/**\n * How many host names the private-address check remembers during one run.\n * A run talks to a handful of hosts; this only stops a hostile page from\n * growing the memory by requesting endless made-up names.\n */\nconst HOST_GUARD_MAX_ENTRIES = 256;\n\n/**\n * Safety check: is this host somewhere the runner must not visit?\n * It blocks cloud metadata addresses (169.254.169.254, metadata.google.internal,\n * link-local fe80::/10), private networks (10.x, 172.16-31.x, 192.168.x),\n * carrier-grade NAT (100.64.0.0/10), and unspecified addresses.\n *\n * In hosted mode (the default), private ranges and loopback are blocked\n * (loopback may be allowed in dev). In customer-run local mode\n * (allowPrivateNetworks: true), RFC 1918 subnets and loopback addresses\n * are allowed since it is the customer's own network, but cloud metadata\n * endpoints remain strictly blocked to protect the customer's credentials.\n */\nexport function isPrivateOrBlockedHost(\n host: string,\n policy: boolean | HostSecurityPolicy = false,\n): boolean {\n const allowLoopback =\n typeof policy === 'boolean'\n ? policy\n : Boolean(policy.allowLoopback || policy.allowPrivateNetworks);\n const allowPrivateNetworks =\n typeof policy === 'object' && policy !== null ? Boolean(policy.allowPrivateNetworks) : false;\n\n // The host in lower case without extra spaces.\n const trimmed = host.toLowerCase().trim();\n // The host without the square brackets URL puts around IPv6 text.\n const unbracketed =\n trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed;\n // The host without a single trailing dot, so `localhost.` equals `localhost`.\n const h = unbracketed.endsWith('.') ? unbracketed.slice(0, -1) : unbracketed;\n if (\n h === '169.254.169.254' ||\n h === 'metadata.google.internal' ||\n h === 'metadata' ||\n h === 'instance-data'\n ) {\n return true;\n }\n // Pattern for a plain IPv4 address like 10.0.0.1.\n const ipv4Regex = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/;\n // The four number parts of an IPv4 address, if the host is one.\n const match = h.match(ipv4Regex);\n if (match) {\n return isBlockedIPv4(Number(match[1]), Number(match[2]), allowLoopback, allowPrivateNetworks);\n }\n if (h.includes(':')) {\n // IPv4 wrapped in IPv6, written with dots (::ffff:10.0.0.1).\n const mappedDotted = h.match(/^::ffff:(\\d{1,3})\\.(\\d{1,3})\\.\\d{1,3}\\.\\d{1,3}$/);\n if (mappedDotted) {\n return isBlockedIPv4(\n Number(mappedDotted[1]),\n Number(mappedDotted[2]),\n allowLoopback,\n allowPrivateNetworks,\n );\n }\n // IPv4 wrapped in IPv6, written in hex (::ffff:a00:1), as URL outputs it.\n const mappedHex = h.match(/^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);\n if (mappedHex) {\n // The first hex group holds the first two IPv4 numbers. If it is\n // somehow missing we block, because refusing is the safe answer.\n const highText = mappedHex[1];\n if (highText === undefined) return true;\n const high = parseInt(highText, 16);\n return isBlockedIPv4(high >> 8, high & 0xff, allowLoopback, allowPrivateNetworks);\n }\n if (h === '::1') return !allowLoopback;\n if (h === '::') return true;\n // fe80::/10 (fe80 to febf) link-local is always blocked (cloud metadata risk).\n if (/^fe[89ab][0-9a-f]:/.test(h)) return true;\n // fc00::/7 (fc and fd) unique-local is allowed when private networks are permitted.\n if (/^f[cd][0-9a-f]{2}:/.test(h)) return !allowPrivateNetworks;\n return false;\n }\n if (!allowLoopback && (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local'))) {\n return true;\n }\n return false;\n}\n\n/**\n * A rule that rewrites one field of a request body before the request\n * leaves the browser: which requests it applies to, which field, and the\n * value to put there.\n */\nexport interface RawOverride {\n override_id: string;\n request_match: { method: string; url_pattern: string };\n field_path: string;\n value: { source: string; static_value?: string; secret_ref?: string };\n}\n\n/**\n * Splits a JSON pointer such as '/a/b~1c' into its parts ['a', 'b/c'].\n * ('~1' stands for '/' and '~0' for '~'.) Returns null if the text is not\n * a pointer, and an empty list for the empty pointer.\n */\nexport function parsePointer(path: string): string[] | null {\n if (path === '') {\n return [];\n }\n if (!path.startsWith('/')) {\n return null;\n }\n return path\n .slice(1)\n .split('/')\n .map((seg) => seg.replace(/~1/g, '/').replace(/~0/g, '~'));\n}\n\n/**\n * Writes a value into a parsed JSON body at the given path.\n * If the field currently holds a boolean or number, the new text is\n * converted to match, so the body keeps the same types. If the field does\n * not exist it returns false and changes nothing: an override must never\n * invent new fields.\n */\nexport function setPointer(root: unknown, segments: string[], raw: string): boolean {\n if (segments.length === 0) {\n return false;\n }\n // The place in the body we have walked to.\n let node: unknown = root;\n for (const seg of segments.slice(0, -1)) {\n if (node === null || typeof node !== 'object') {\n return false;\n }\n node = (node as Record<string, unknown>)[seg];\n }\n if (node === null || typeof node !== 'object') {\n return false;\n }\n // The object that contains the final field.\n const holder = node as Record<string, unknown>;\n // The name of the final field.\n const key = segments[segments.length - 1]!;\n if (!(key in holder)) {\n return false;\n }\n // The field's current value, used to decide what type to write.\n const current = holder[key];\n if (typeof current === 'boolean' && (raw === 'true' || raw === 'false')) {\n holder[key] = raw === 'true';\n } else if (typeof current === 'number' && raw.trim() !== '' && Number.isFinite(Number(raw))) {\n holder[key] = Number(raw);\n } else {\n holder[key] = raw;\n }\n return true;\n}\n\n/**\n * Changes one field in a request body and returns the new body.\n * JSON bodies use a JSON pointer; form bodies (key=value) use the field\n * name. Returns null if the body type is not supported, the body cannot\n * be read, or the field is not there.\n */\nexport function rewriteBody(\n body: string,\n contentType: string,\n fieldPath: string,\n raw: string,\n): string | null {\n // The field path split into parts.\n const segments = parsePointer(fieldPath);\n if (/json/i.test(contentType)) {\n // The request body as parsed JSON.\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n return segments !== null && setPointer(parsed, segments, raw) ? JSON.stringify(parsed) : null;\n }\n if (/x-www-form-urlencoded/i.test(contentType)) {\n const key = segments !== null && segments.length === 1 ? segments[0]! : fieldPath;\n // The form body as key/value pairs.\n const params = new URLSearchParams(body);\n if (!params.has(key)) {\n return null;\n }\n params.set(key, raw);\n return params.toString();\n }\n return null;\n}\n\n/**\n * Reduces a recorded URL pattern to just its path and query, so the\n * override still matches when the test runs against a different site\n * (staging vs production).\n */\nexport function overrideUrlNeedle(pattern: string): string {\n // The pattern without a leading '**/'.\n const bare = pattern.startsWith('**/') ? pattern.slice(3) : pattern;\n if (bare.startsWith('http://') || bare.startsWith('https://')) {\n try {\n const u = new URL(bare);\n return `${u.pathname}${u.search}`;\n } catch {\n return bare;\n }\n }\n return bare;\n}\n\n/**\n * The element a check should read when it is not the step's own element.\n */\nexport interface RawCheckTarget {\n locators: Array<{ strategy: string; expression: string }>;\n}\n\n/**\n * One assertion on a step: what kind it is, how long to wait, and what to\n * check (a text rule, a request to look for, a status range, response\n * body checks, or another element).\n */\nexport interface RawAssertion {\n assertion_id?: string;\n kind?: string;\n timeout_ms: number;\n expected?: ExpectedValue | null;\n request_match?: {\n method?: string;\n url_pattern?: string;\n } | null;\n status_range?: {\n min?: number;\n max?: number;\n } | null;\n body_checks?: RawBodyCheck[];\n target?: RawCheckTarget | null;\n /** The attribute `assertAttribute` reads, for example `href`. */\n attribute_name?: string | null;\n /** How many matches `assertCount` wants. */\n count_check?: RawCountCheck | null;\n}\n\n/**\n * The rule an `assertCount` assertion applies to the number of elements\n * a selector matches: exactly N, at least N, or at most N. N may be zero.\n */\nexport interface RawCountCheck {\n op: 'equals' | 'at_least' | 'at_most';\n value: number;\n}\n\n/**\n * Says whether a number of matches satisfies a count rule.\n * Does it with a plain switch on the three allowed operators, so a rule\n * the contract does not list is a type error here rather than a silent\n * pass. Zero is an ordinary number: \"equals 0\" passes when nothing matches.\n */\nexport function countHolds(check: RawCountCheck, found: number): boolean {\n switch (check.op) {\n case 'equals':\n return found === check.value;\n case 'at_least':\n return found >= check.value;\n case 'at_most':\n return found <= check.value;\n }\n}\n\n/**\n * Writes a count rule as short text for reports, for example\n * `at least 3 matches`. Used as the \"expected\" side of the outcome.\n */\nexport function describeCount(check: RawCountCheck): string {\n const words = { equals: 'exactly', at_least: 'at least', at_most: 'at most' }[check.op];\n return `${words} ${check.value} ${check.value === 1 ? 'match' : 'matches'}`;\n}\n\n/**\n * Tells a temporary browser hiccup (the page navigated while we were\n * counting) from a selector the browser cannot understand. Only the\n * second is the test author's mistake. Looks for the wording the\n * browser uses for lost pages and treats every other error as a bad\n * selector, because a count call has no other way to fail.\n */\nexport function isTransientPageError(message: string): boolean {\n return /context was destroyed|navigat|target closed|has been closed/i.test(message);\n}\n\n/**\n * One requirement on a JSON body (used by assertRequest): which body,\n * which field, and the rule it must satisfy.\n */\nexport interface RawBodyCheck {\n source: 'response' | 'request';\n json_path: string;\n match: 'exact' | 'contains' | 'regex' | 'exists' | 'type';\n value: string | null;\n /** When true, `{{name}}` saved by an earlier step is replaced in `value`. */\n expand_values: boolean;\n}\n\n/**\n * A condition to wait for after a step's action, with its time limit.\n */\nexport interface RawWait {\n wait_id: string;\n kind: string;\n timeout_ms: number;\n expected?: ExpectedValue | null;\n target?: RawCheckTarget | null;\n}\n\n/**\n * A rule for copying a value out of a response into a variable for later\n * steps: from the JSON body, the raw body or a header. It can be tied to\n * a specific recorded request.\n */\nexport interface ExtractVariableRule {\n variable_name: string;\n /** True when the QA marked the value \"Export this value\". */\n export?: boolean;\n source: 'response_body_json' | 'response_body' | 'response_header';\n json_path?: string;\n header_name?: string;\n /** The recorded request the rule was authored against; when set, only its response is read. */\n source_request?: { method: string; url: string };\n}\n\n/**\n * Picks which responses an extract rule may read.\n * A rule tied to a request only reads responses to that same request\n * (same method and path, preferring an exact path+query match), so an\n * unrelated call in the same time window cannot supply the value. Older\n * rules without a link read every candidate.\n */\nexport function responsesForRule<T extends { method: string; url: string }>(\n rule: ExtractVariableRule,\n candidates: readonly T[],\n): T[] {\n // The request the rule was tied to, if any.\n const link = rule.source_request;\n if (!link) return [...candidates];\n // Breaks a URL into path and path+query.\n const split = (raw: string): { path: string; full: string } => {\n try {\n const u = new URL(raw, 'http://x');\n return { path: u.pathname, full: u.pathname + u.search };\n } catch {\n return { path: raw, full: raw };\n }\n };\n // The path and query we are looking for.\n const want = split(link.url);\n // Responses to the same method and path.\n const sameCall = candidates.filter(\n (r) => r.method.toUpperCase() === link.method.toUpperCase() && split(r.url).path === want.path,\n );\n // The ones that also match the query string.\n const exact = sameCall.filter((r) => split(r.url).full === want.full);\n return exact.length > 0 ? exact : sameCall;\n}\n\n/**\n * Reads the value an extract rule points at, from the responses it may read.\n *\n * What it is: the one place that knows how to pull a value out of a response for a rule.\n * What it does: looks at the rule's allowed responses from the newest to the oldest and returns\n * the first value it finds: a header for a header rule, or the JSON path of the body for a body\n * rule. A body that is not JSON, or a path that finds nothing, is skipped. Returns undefined when\n * no response gives a value.\n * How: the same loop the step used inline before exports existed, moved here so the passed-step\n * path and the failed-step export path read values exactly the same way.\n */\nexport async function readExtractedValue(\n rule: ExtractVariableRule,\n candidates: ReadonlyArray<{\n method: string;\n url: string;\n headers: Record<string, string>;\n bodyPromise: Promise<string>;\n }>,\n): Promise<string | undefined> {\n // Responses this rule is allowed to read.\n const ruleResponses = responsesForRule(rule, candidates);\n if (rule.source === 'response_header' && rule.header_name) {\n // Header name in lower case (Playwright lower-cases header names).\n const targetHeader = rule.header_name.toLowerCase();\n for (let rIdx = ruleResponses.length - 1; rIdx >= 0; rIdx--) {\n const headerVal = ruleResponses[rIdx]!.headers[targetHeader];\n if (headerVal !== undefined && headerVal !== null) {\n return headerVal;\n }\n }\n return undefined;\n }\n if (rule.source === 'response_body_json' || (rule.source as string) === 'response_body') {\n for (let rIdx = ruleResponses.length - 1; rIdx >= 0; rIdx--) {\n try {\n // The matched response's body.\n const bodyText = await ruleResponses[rIdx]!.bodyPromise;\n if (bodyText) {\n const jsonBody: unknown = JSON.parse(bodyText);\n const extracted = extractJSONPath(jsonBody, rule.json_path || '$');\n if (extracted !== undefined && extracted !== null) {\n return stringifyExtracted(extracted);\n }\n }\n } catch {\n // ignore non-json response body\n }\n }\n }\n return undefined;\n}\n\n/**\n * Works out how to answer a step's alert/confirm/prompt dialogs.\n * An accepted prompt may be answered with a secret, a variable or a fixed\n * text (placeholders filled in). Missing secrets or variables become an\n * empty answer instead of crashing.\n */\nfunction resolveDialogExpectations(\n step: RawStep,\n bundle: RunBundle,\n interpolator: VariableInterpolator,\n): DialogExpectation[] {\n return (step.dialogs ?? []).map((d) => {\n // The answer being built for one dialog.\n const expectation: DialogExpectation = { dialog_type: d.dialog_type, action: d.action };\n const v = d.prompt_value;\n if (d.action === 'accept' && v) {\n if (v.source === 'secret' && v.secret_ref) {\n expectation.prompt_text = bundle.secrets[v.secret_ref] ?? '';\n } else if (v.source === 'variable' && v.variable_name) {\n const vars = (bundle.definition.variables || []) as Array<{ name: string; value: string }>;\n expectation.prompt_text =\n interpolator.rowValueFor(v.variable_name) ??\n vars.find((x) => x.name === v.variable_name)?.value ??\n '';\n } else if (typeof v.static_value === 'string') {\n expectation.prompt_text = interpolator.interpolateStrict(v.static_value);\n }\n }\n return expectation;\n });\n}\n\n/**\n * One recorded dialog answer: its type, accept or dismiss, and what to\n * type if it is a prompt.\n */\nexport interface RawDialogResponse {\n dialog_type: 'alert' | 'confirm' | 'prompt';\n action: 'accept' | 'dismiss';\n prompt_value?: {\n source?: string;\n secret_ref?: string;\n static_value?: string;\n variable_name?: string;\n } | null;\n message?: string;\n}\n\n/**\n * One saved way to find an element (strategy and expression), plus what\n * the recording saw of it, which the look-alike search uses later.\n */\nexport interface RawLocator {\n strategy: string;\n expression: string;\n tag?: string;\n role?: string | null;\n accessible_name?: string | null;\n text?: string | null;\n attributes?: Record<string, string>;\n}\n\n/**\n * One step of a test as saved in the definition: its action, element\n * locators and overrides, the value to use, waits, assertions, dialogs,\n * variables to extract, and what to do if it fails.\n */\nexport interface RawStep {\n step_id?: string;\n id?: string;\n name?: string;\n action?: string;\n /** The page (tab or popup) the step runs on: 0 is the first page. Absent: the page the run is on. */\n page?: number;\n enabled?: boolean;\n key?: string;\n payload_overrides?: RawOverride[];\n extract_variables?: ExtractVariableRule[];\n dialogs?: RawDialogResponse[];\n value?: {\n source?: string;\n secret_ref?: string;\n static_value?: string;\n expand_values?: boolean;\n variable_name?: string;\n kind?: string;\n text?: string;\n };\n /** Fill steps only: the name the typed text is saved under for later fields. */\n save_as?: string;\n /** True when the saved name is also marked \"Export this value\" (needs `save_as`). */\n export_saved?: boolean;\n params?: Record<string, unknown>;\n target?: {\n locators?: RawLocator[];\n /** Selectors of the iframes holding the element, outermost first. Absent or empty: top page. */\n frame_path?: string[];\n /** What was recorded about the element's identity and neighbours; null when none. */\n verification?: Verification | null;\n overrides?: {\n order?: Array<{ strategy: string; expression: string }>;\n disabled?: Array<{ ref: { strategy: string; expression: string }; reason: string }>;\n custom_locator?: { strategy: string; expression: string; note?: string };\n acknowledged?: boolean;\n acknowledgment_reason?: string;\n };\n };\n waits?: RawWait[];\n assertions?: RawAssertion[];\n failure_policy?: FailurePolicy;\n idempotent?: boolean;\n}\n\n/**\n * What the run does when a step fails: stop, pause, skip the step, or\n * retry (only when safe).\n */\nexport type FailurePolicy = 'stop' | 'pause' | 'skip' | 'retry_if_safe';\n\n/**\n * How many tries a step gets. Only a step that is both 'retry if safe'\n * and idempotent (safe to repeat) is retried; any other step runs once so\n * we never repeat something with side effects.\n */\nexport function stepAttempts(step: RawStep, stepRetries: number): number {\n return step.failure_policy === 'retry_if_safe' && step.idempotent === true ? 1 + stepRetries : 1;\n}\n\n/**\n * How the runner found a step's element: which strategy worked, whether\n * a backup was used, which failed, the candidates and a confidence\n * score, and (on failure) look-alike elements.\n */\nexport interface StepResolution {\n resolved_strategy: 'semantic' | 'stable_attribute' | 'relational' | 'css' | 'xpath' | null;\n fallback_used: boolean;\n failed_strategies: Array<'semantic' | 'stable_attribute' | 'relational' | 'css' | 'xpath'>;\n candidates: Array<{\n description: string;\n score: number;\n signals: Record<string, number>;\n }>;\n confidence: number | null;\n /**\n * Set when the element was found through a position locator (`... >> nth=N`):\n * which position was taken and how many elements matched before it. Null when\n * the step did not resolve that way or the count could not be taken.\n */\n position_pick: PositionPick | null;\n /** Only on a failed locator step; absent when capture did not run. */\n near_matches?: NearMatch[];\n /** What the check before the action found; empty when nothing needs saying. */\n target_checks?: TargetCheck[];\n}\n\n/**\n * What a position locator picked: \"first of 12\" is\n * { position: 'first', index: 1, matched: 12 }.\n */\nexport interface PositionPick {\n position: 'first' | 'last' | 'nth';\n /** The position taken, counted from 1. */\n index: number;\n /** How many elements matched before the position was applied. */\n matched: number;\n}\n\n/**\n * The result of one wait or assertion: its id, kind, pass or fail, and\n * what was expected and seen.\n */\nexport interface Outcome {\n id: string;\n kind: string;\n passed: boolean;\n expected: string | null;\n actual: string | null;\n}\n\n/**\n * A network response the page received during the step, kept so\n * assertions and variable extraction can look at it later.\n */\ninterface ObservedResponse {\n method: string;\n url: string;\n status: number;\n headers: Record<string, string>;\n bodyPromise: Promise<string>;\n /** What the page sent (the request's post data), or null for a request without a body. */\n requestBody: string | null;\n}\n\n/**\n * Live access to what the page did during the current step (responses and\n * console errors), read by request and console assertions.\n */\ninterface StepEvidence {\n responses: () => ObservedResponse[];\n consoleErrors: () => string[];\n}\n\n/**\n * Steps that are themselves a check (waitFor...). We do not wait for the\n * network to settle after them.\n */\nconst CONDITION_ACTIONS = new Set([\n 'waitForVisible',\n 'waitForHidden',\n 'waitForText',\n 'waitForUrl',\n 'assertVisible',\n 'assertHidden',\n 'assertText',\n 'assertValue',\n 'assertUrl',\n 'assertRequest',\n 'assertNoConsoleErrors',\n]);\n\n/**\n * Reads a text setting from a step's params (for example the Target URL\n * or Key field in the editor). Returns it trimmed, or '' if it is missing\n * or not text.\n */\nexport function stringParam(step: RawStep, name: string): string {\n // The new value to write (from a secret or static text).\n const raw = step.params?.[name];\n return typeof raw === 'string' ? raw.trim() : '';\n}\n\n/**\n * Moves an absolute URL onto the run's chosen site. Keeps the path, query\n * and hash but swaps the origin for the base override (so the same test\n * can run against staging or production). Relative URLs and runs without\n * an override are returned unchanged.\n */\nexport function rewriteToBase(url: string, baseOverride: string | undefined): string {\n if (!baseOverride || !(url.startsWith('http://') || url.startsWith('https://'))) {\n return url;\n }\n try {\n // The step's saved target element.\n const target = new URL(url);\n return `${baseOverride.replace(/\\/+$/, '')}${target.pathname}${target.search}${target.hash}`;\n } catch {\n return url;\n }\n}\n\n/**\n * Turns a URL written in the editor (full, or just a path like /worlds)\n * into a full URL, using the recorded start URL as the base.\n */\nexport function resolveStepUrl(url: string, startUrl: string | undefined): string {\n if (!startUrl) {\n return url;\n }\n try {\n return new URL(url, startUrl).href;\n } catch {\n return url;\n }\n}\n\n/**\n * Works out which page the run must open first: the custom URL of the\n * first enabled navigate step if it has one, otherwise the start URL.\n *\n * What it is: the initial page address for the test run.\n * What it does: inspects the steps in order, finds the first enabled step,\n * and if it is a navigate step, returns its target URL resolved against the\n * test's start URL. Otherwise, it falls back to the test's start URL.\n * How it does it: when an interpolator is supplied, any {{variable}} or {{BASE_URL}}\n * placeholders in the custom URL or start URL are expanded strictly first.\n * Resolving variables before WHATWG URL resolution is critical: otherwise,\n * a leading {{BASE_URL}} is treated as a relative path segment and percent-encoded\n * into %7B%7BBASE_URL%7D%7D, breaking navigation and SPA routing.\n */\nexport function initialUrl(\n steps: RawStep[],\n startUrl: string | undefined,\n interpolator?: VariableInterpolator,\n): string | undefined {\n // Interpolate the fallback start URL if an interpolator is available.\n const resolvedStartUrl = startUrl && interpolator ? interpolator.interpolate(startUrl) : startUrl;\n // The first step that is switched on.\n const first = steps.find((st) => st.enabled !== false);\n // That step's custom URL, if it is a navigate step.\n let custom = first?.action === 'navigate' ? stringParam(first, 'url') : '';\n if (custom && interpolator) {\n custom = interpolator.interpolateStrict(custom);\n }\n return custom ? resolveStepUrl(custom, resolvedStartUrl) : resolvedStartUrl;\n}\n\n/**\n * Reads an 'expected' rule from untrusted step params. Returns null\n * unless it has a valid match mode and a text value.\n */\nfunction readExpected(raw: unknown): ExpectedValue | null {\n if (typeof raw !== 'object' || raw === null) {\n return null;\n }\n const { match, value, expand_values: expand } = raw as Record<string, unknown>;\n if (\n (match === 'exact' || match === 'contains' || match === 'regex') &&\n typeof value === 'string'\n ) {\n return { match, value, expand_values: expand === true };\n }\n return null;\n}\n\n/**\n * Builds the assertion that a check step (assertText, assertUrl,\n * assertRequest...) stands for, from its editor params. assertUrl is\n * always a 'contains' check on the (base-rewritten) URL. assertRequest\n * uses the request and status-range params.\n */\nexport function stepCheckAssertion(\n step: RawStep,\n stepId: string,\n action: string,\n timeoutMs: number,\n baseOverride: string | undefined,\n): RawAssertion {\n // The text rule for this check, if any.\n let expected = readExpected(step.params?.expected);\n if (action === 'assertUrl') {\n const url = stringParam(step, 'url');\n expected = url\n ? {\n match: 'contains',\n value: rewriteToBase(url, baseOverride),\n expand_values: expected?.expand_values === true,\n }\n : null;\n }\n const match = step.params?.request_match as RawAssertion['request_match'];\n // The allowed status range for assertRequest, if set.\n const range = step.params?.status_range as RawAssertion['status_range'];\n return {\n assertion_id: `${stepId}-${action}`,\n kind: action,\n timeout_ms: timeoutMs,\n expected,\n request_match: typeof match === 'object' ? match : null,\n status_range: typeof range === 'object' ? range : null,\n };\n}\n\n/**\n * Returns the step's own timeout from the editor's Timeout field, or the\n * run's default when the field is missing or not a positive number.\n */\nexport function stepTimeoutParam(step: RawStep, fallbackMs: number): number {\n const raw = step.params?.timeout_ms;\n return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : fallbackMs;\n}\n\n/**\n * CSS selector for dialogs currently open on the page (ARIA dialogs and\n * native <dialog open>). Used to detect a modal blocking the page.\n */\nconst OPEN_DIALOG_SELECTOR =\n '[role=\"dialog\"]:visible, [role=\"alertdialog\"]:visible, dialog[open]:visible';\n\n/**\n * CSS selector for visible loading indicators (aria-busy, progress bars).\n * Used to explain a failure as 'the page was still loading'.\n */\nconst LOADING_INDICATOR_SELECTOR = '[aria-busy=\"true\"]:visible, [role=\"progressbar\"]:visible';\n\n/**\n * A condition ready to check: either a probe function to poll, or the\n * reason it cannot be checked for this step.\n */\ntype PreparedCondition =\n | { expected: string; probe: () => Promise<ConditionProbe> }\n | { expected: string; unavailable: string };\n\n/**\n * Whether a payload override was actually applied to a request.\n */\nexport interface OverrideOutcome {\n override_id: string;\n applied: boolean;\n}\n\n/**\n * Extra evidence collected during a step: console errors and warnings,\n * page errors, and requests that failed.\n */\nexport interface StepDiagnostics {\n console: Array<{ level: 'error' | 'warning'; text: string }>;\n page_errors: string[];\n failed_requests: Array<{\n method: string;\n url: string;\n status: number | null;\n error_text: string | null;\n }>;\n}\n\n/**\n * Who a failure points at: the app (app_regression), the locators\n * (not found / ambiguous / in conflict with each other), a target that was found but is not the\n * recorded element (target_mismatch), a target that exists but is hidden\n * (target_hidden), the test (definition_incomplete), the\n * environment, a missing login, or the runner itself (timeout / error).\n */\nexport type FailureClass =\n | 'app_regression'\n | 'locator_not_found'\n | 'locator_ambiguous'\n | 'locator_conflict'\n | 'target_mismatch'\n | 'target_hidden'\n | 'definition_incomplete'\n | 'env_unreachable'\n | 'precondition_auth'\n | 'runner_timeout'\n | 'runner_error';\n\n/**\n * An error that already knows its failure class where it is raised, so\n * it does not need to be guessed later.\n */\nexport class StepFailure extends Error {\n /**\n * Saves the failure class (so reports can say who is to blame) and the\n * human-readable message.\n */\n constructor(\n readonly failureClass: FailureClass,\n message: string,\n ) {\n super(message);\n this.name = 'StepFailure';\n }\n}\n\n/**\n * Decides the failure class of an error caught around a step.\n * Known failures keep their class. A timeout on an element the app left\n * hidden or disabled counts as the app's fault; any other timeout is the\n * runner's.\n */\nexport function classifyError(err: unknown, elementState: string): FailureClass {\n if (err instanceof StepFailure) {\n return err.failureClass;\n }\n if (err instanceof errors.TimeoutError) {\n return elementState === '' ? 'runner_timeout' : 'app_regression';\n }\n return 'runner_error';\n}\n\n/**\n * Steps that act on the page with the mouse. When one of these times out\n * because its target is hidden, the likely cause is a menu that only opens\n * while its trigger is hovered, not a broken app.\n */\nconst POINTER_ACTIONS = new Set(['click', 'dblclick', 'rightClick', 'hover']);\n\n/**\n * Steps that cannot do anything without a target element. If one has no\n * target (or every locator of it is switched off), the run must fail\n * instead of quietly passing a step that did nothing.\n */\nconst TARGET_REQUIRED_ACTIONS = new Set([\n 'click',\n 'dblclick',\n 'rightClick',\n 'hover',\n 'dragTo',\n 'fill',\n 'clear',\n 'selectOption',\n 'setInputFiles',\n 'download',\n 'check',\n 'uncheck',\n 'submit',\n]);\n\n/**\n * The note `describeElementState` adds when an element is on the page but\n * not visible. Kept in one place so the check below matches the writer.\n */\nconst HIDDEN_NOTE = ' [element state: hidden]';\n\n/**\n * Turns an `app_regression` verdict into `target_hidden` when a mouse step\n * timed out on an element that exists but is hidden.\n *\n * Why: before this, a click on a hover-only menu item was blamed on the\n * app. The element is there; it just was never shown, which is usually a\n * missing hover step in the test. Disabled elements and every other\n * failure class keep their verdict.\n *\n * How: it only changes the answer when all three hold: the class is\n * `app_regression`, the element note says hidden, and the action is a\n * mouse action.\n */\nexport function refineHiddenFailure(\n failureClass: FailureClass,\n elementState: string,\n action: string,\n): FailureClass {\n if (\n failureClass === 'app_regression' &&\n elementState === HIDDEN_NOTE &&\n POINTER_ACTIONS.has(action)\n ) {\n return 'target_hidden';\n }\n return failureClass;\n}\n\n/**\n * Message added to a `target_hidden` step error so the person reading the\n * report knows the likely fix. It says \"if\" because a hidden target can\n * also be a closed accordion or a tab that is not open.\n */\nconst TARGET_HIDDEN_HINT =\n ' Target is hidden. If a menu opens on hover, add a hover step on its trigger before this step.';\n\n/**\n * The mouse button names Playwright accepts, keyed by the number the\n * browser reports (`MouseEvent.button`) and the recorder saves.\n */\nconst MOUSE_BUTTONS: Record<number, 'left' | 'middle' | 'right'> = {\n 0: 'left',\n 1: 'middle',\n 2: 'right',\n};\n\n/** The modifier key names the recorder writes and Playwright understands. */\nconst MODIFIER_KEYS = new Set(['Alt', 'Control', 'Meta', 'Shift']);\n\n/**\n * Reads the modifier keys (Control, Shift...) a recorded step carries.\n *\n * Why: the recorder saves them, but replay used to drop them, so a\n * Ctrl-click ran as a plain click. A name we do not know fails the step\n * instead of being ignored, because ignoring it changes what the test does.\n *\n * How: takes `params.modifiers`, which must be a list of known names, and\n * returns it without repeats. Missing means none.\n */\nexport function stepModifiers(step: RawStep): Array<'Alt' | 'Control' | 'Meta' | 'Shift'> {\n const raw = step.params?.modifiers;\n if (raw === undefined || raw === null) {\n return [];\n }\n if (!Array.isArray(raw)) {\n throw new StepFailure('definition_incomplete', 'modifiers must be a list of key names');\n }\n const names: Array<'Alt' | 'Control' | 'Meta' | 'Shift'> = [];\n for (const name of raw) {\n if (typeof name !== 'string' || !MODIFIER_KEYS.has(name)) {\n throw new StepFailure(\n 'definition_incomplete',\n `unknown modifier key ${JSON.stringify(name)}; use Alt, Control, Meta or Shift`,\n );\n }\n if (!names.includes(name as 'Alt')) {\n names.push(name as 'Alt' | 'Control' | 'Meta' | 'Shift');\n }\n }\n return names;\n}\n\n/**\n * Builds the click options a recorded mouse step asks for: which button\n * and which modifier keys were held. Plain left clicks come back with no\n * extra options, so they behave exactly as before.\n *\n * How: maps the recorded button number (0, 1, 2) to Playwright's name and\n * reads the modifiers with `stepModifiers`. An unknown button fails the\n * step. `forceButton` is used by `rightClick`, which always means right.\n */\nexport function pointerOptions(\n step: RawStep,\n forceButton?: 'right',\n): { button?: 'middle' | 'right'; modifiers?: Array<'Alt' | 'Control' | 'Meta' | 'Shift'> } {\n const out: {\n button?: 'middle' | 'right';\n modifiers?: Array<'Alt' | 'Control' | 'Meta' | 'Shift'>;\n } = {};\n const rawButton = step.params?.button;\n let button: 'left' | 'middle' | 'right' = 'left';\n if (forceButton !== undefined) {\n button = forceButton;\n } else if (rawButton !== undefined && rawButton !== null) {\n const named = typeof rawButton === 'number' ? MOUSE_BUTTONS[rawButton] : undefined;\n if (named === undefined) {\n throw new StepFailure(\n 'definition_incomplete',\n `unknown mouse button ${JSON.stringify(rawButton)}; use 0, 1 or 2`,\n );\n }\n button = named;\n }\n if (button !== 'left') {\n out.button = button;\n }\n const modifiers = stepModifiers(step);\n if (modifiers.length > 0) {\n out.modifiers = modifiers;\n }\n return out;\n}\n\n/**\n * Reads the frame path of a step target: the selectors of the iframes that\n * hold the element, outermost first. A target in the top page has none.\n *\n * What it does: returns the list, or an empty list when the target has no\n * frame path. Anything that is not a short list of non-empty strings fails\n * the step as `definition_incomplete`, so a damaged path cannot quietly send\n * the step to the top page.\n *\n * How: checks the type of the value and of each entry, and the contract's\n * limit of four nested frames.\n */\nexport function framePathOf(target: { frame_path?: unknown }): string[] {\n const raw = target.frame_path;\n if (raw === undefined || raw === null) {\n return [];\n }\n if (\n !Array.isArray(raw) ||\n raw.length > 4 ||\n raw.some((entry) => typeof entry !== 'string' || entry === '')\n ) {\n throw new StepFailure(\n 'definition_incomplete',\n 'the target frame_path must be a list of up to 4 non-empty iframe selectors',\n );\n }\n return raw as string[];\n}\n\n/**\n * Gives the place a step's locators are searched in: the page itself, or\n * the iframe the target lives in.\n *\n * What it does: with no frame path it returns the page; otherwise it walks\n * into each iframe in order and returns the innermost one.\n *\n * How: Playwright's `frameLocator` follows an iframe element by selector, and\n * `.locator(...)` on the result searches inside that frame only. Both the\n * page and a frame locator offer `.locator`, so the callers do not care which\n * they hold.\n */\nexport function frameScope(page: Page, framePath: string[]): Page | FrameLocator {\n let scope: Page | FrameLocator = page;\n for (const selector of framePath) {\n scope = scope.frameLocator(selector);\n }\n return scope;\n}\n\n/**\n * Words a failure message can use to say which frame was being searched.\n * Empty for the top page, so existing messages do not change.\n */\nexport function frameNote(framePath: string[]): string {\n return framePath.length === 0 ? '' : ` [inside frame ${framePath.join(' > ')}]`;\n}\n\n/**\n * The most pages (tabs and popups) one run keeps track of, the first one included.\n * The contract allows a step `page` of 0 to 9, which is this many pages.\n */\nconst MAX_PAGES = 10;\n\n/**\n * Reads which page a step runs on.\n *\n * What it does: returns the page number the step asks for (0 is the page the run opened, 1 is the\n * first tab or popup a step opened, and so on), or null when the step does not say, which means\n * \"stay on the page the run is on\".\n *\n * How: accepts only a whole number from 0 to 9. Anything else fails the step as\n * `definition_incomplete`, so a damaged value cannot quietly run the step on the wrong page.\n */\nexport function pageIndexOf(step: { page?: unknown }): number | null {\n const raw = step.page;\n if (raw === undefined || raw === null) {\n return null;\n }\n if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 0 || raw >= MAX_PAGES) {\n throw new StepFailure(\n 'definition_incomplete',\n `a step page must be a whole number from 0 to ${MAX_PAGES - 1} (got ${JSON.stringify(raw)})`,\n );\n }\n return raw;\n}\n\n/**\n * Waits for the page with the given number to exist, and returns it.\n *\n * What it does: a popup opens a moment after the click that caused it, so a step that runs on page 1\n * may start before page 1 exists. This waits up to the step's time limit. A page that opened and was\n * closed again is reported as closed, not as missing.\n *\n * How: checks the list of pages the run has seen every 50 ms. Both failures are `app_regression`,\n * because the application did not open (or kept open) the page the test expects.\n */\nexport async function waitForPage(pages: Page[], index: number, timeoutMs: number): Promise<Page> {\n const deadline = Date.now() + timeoutMs;\n while (pages.length <= index && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n const found = pages[index];\n if (found === undefined) {\n throw new StepFailure(\n 'app_regression',\n `page ${index} did not open within ${timeoutMs} ms (the run has ${pages.length} page${pages.length === 1 ? '' : 's'})`,\n );\n }\n if (found.isClosed()) {\n throw new StepFailure('app_regression', `page ${index} is closed`);\n }\n return found;\n}\n\n/**\n * Finds the page to carry on with after the current one has closed.\n *\n * What it does: a popup often closes itself (a login window after it signs in), so the next step\n * must go back to a page that is still open. It picks the nearest earlier page that is open.\n *\n * How: walks the list backwards from the closed page. Page 0 is never closed by the runner, but if\n * everything is closed the step fails instead of guessing.\n */\nexport function openPageBefore(pages: Page[], closed: Page): Page {\n for (let i = pages.indexOf(closed) - 1; i >= 0; i--) {\n const candidate = pages[i];\n if (candidate !== undefined && !candidate.isClosed()) {\n return candidate;\n }\n }\n throw new StepFailure('app_regression', 'every page of the run is closed');\n}\n\n/**\n * Finds the element a drag is dropped on.\n *\n * What it does: reads the drop target's locator set from the step's params (`params.to`) and returns\n * the first locator that matches exactly one element, in the iframe the set names, if any. A missing\n * or empty set fails the step as `definition_incomplete`; an element that never appears fails it as\n * `locator_not_found` and names the locators tried.\n *\n * How: tries each locator in order and retries until the step's time limit, because the drop zone may\n * still be drawing. The drop target has no fuzzy matching or near-match help: it is a plain lookup.\n */\nexport async function resolveDropTarget(\n page: Page,\n step: RawStep,\n timeoutMs: number,\n): Promise<ResolvedDropTarget> {\n const to = step.params?.to as\n | {\n locators?: Array<{ strategy?: unknown; expression?: unknown }>;\n frame_path?: unknown;\n verification?: Verification | null;\n }\n | undefined;\n const entries = (to?.locators ?? [])\n .filter((l): l is { strategy?: unknown; expression: string } => {\n return typeof l.expression === 'string' && l.expression !== '';\n })\n .map((l) => ({\n strategy: typeof l.strategy === 'string' ? l.strategy : '',\n expression: l.expression,\n }));\n if (to === undefined || entries.length === 0) {\n throw new StepFailure('definition_incomplete', 'a dragTo step needs a drop target (params.to)');\n }\n const framePath = framePathOf(to);\n const scope = frameScope(page, framePath);\n const deadline = Date.now() + timeoutMs;\n const seen: string[] = [];\n do {\n seen.length = 0;\n for (const entry of entries) {\n try {\n const candidate = scope.locator(entry.expression);\n const count = await candidate.count();\n if (count === 1) {\n return {\n locator: candidate,\n winner: entry,\n verification: to.verification ?? null,\n framePath,\n };\n }\n seen.push(`${entry.expression}: ${count} match${count === 1 ? '' : 'es'}`);\n } catch (err: unknown) {\n seen.push(`${entry.expression}: ${errorLine(err)}`);\n }\n }\n await new Promise((resolve) => setTimeout(resolve, 100));\n } while (Date.now() < deadline);\n throw new StepFailure(\n 'locator_not_found',\n `drop target not found (${seen.join('; ')})${frameNote(framePath)}`,\n );\n}\n\n/**\n * The drop zone resolveDropTarget found, with what the target check needs: the locator that won, the\n * recorded verification facts (null when none) and the iframe path.\n */\nexport interface ResolvedDropTarget {\n locator: Locator;\n winner: { strategy: string; expression: string };\n verification: Verification | null;\n framePath: string[];\n}\n\n/**\n * Checks that the element replay found is the element that was recorded, and returns the warnings.\n *\n * What it does: looks at the found element once, then applies the rules of target-verification.ts: a\n * more trusted locator that matched several elements needs a second independent family to agree, then\n * the identity facts and, for a position winner, the neighbour facts are compared. A failure throws\n * `locator_ambiguous` or `target_mismatch` before any action runs.\n * How: one in-page read through the locator engine, then pure comparisons. The same function serves\n * the main target and the dragTo drop zone so both obey one rule.\n */\nasync function verifyFoundTarget(input: {\n locator: Locator;\n engineBundle: string;\n recorded: Verification | null;\n winner: { strategy: string; expression: string };\n agreeing: ReadonlyArray<{ strategy: string; expression: string }>;\n ambiguousAboveWinner: boolean;\n framePath: string[];\n}): Promise<TargetCheck[]> {\n const inspection = await inspectFoundElement(input.locator, input.engineBundle, [\n input.winner,\n ...input.agreeing,\n ]);\n const [winnerFamily, ...agreeingFamilies] = inspection.families;\n if (\n ambiguousBlocksWinner({\n ambiguousAboveWinner: input.ambiguousAboveWinner,\n winnerFamily: winnerFamily!,\n agreeingFamilies,\n })\n ) {\n throw new StepFailure(\n 'locator_ambiguous',\n 'A more trusted locator matched several elements and no independent locator confirms this one.' +\n frameNote(input.framePath),\n );\n }\n const verdict = verifyTarget({\n recorded: input.recorded,\n found: inspection.found,\n winnerFamily: winnerFamily!,\n });\n if (!verdict.ok) {\n throw new StepFailure('target_mismatch', verdict.message + frameNote(input.framePath));\n }\n return verdict.checks;\n}\n\n/**\n * What a download step expects of the file: its name and how to compare it.\n * This is the shape of the `download` step's params in the test definition.\n */\nexport interface DownloadExpectation {\n fileName: string;\n match: 'exact' | 'contains';\n}\n\n/**\n * Reads and checks the params of a download step.\n *\n * What it does: returns the wanted file name and the match rule. A download\n * step with no file name or an unknown rule fails the run as\n * `definition_incomplete`, because without a name the step would pass on any\n * download at all (a check that checks nothing).\n *\n * How: looks at `params.file_name` (a non-empty string) and `params.match`\n * ('exact' or 'contains') and throws a StepFailure that names the problem.\n */\nexport function downloadExpectation(step: RawStep): DownloadExpectation {\n const fileName = step.params?.file_name;\n const match = step.params?.match;\n if (typeof fileName !== 'string' || fileName === '') {\n throw new StepFailure(\n 'definition_incomplete',\n 'a download step needs the expected file name (params.file_name)',\n );\n }\n if (match !== 'exact' && match !== 'contains') {\n throw new StepFailure(\n 'definition_incomplete',\n `a download step needs a match rule of exact or contains (got ${JSON.stringify(match)})`,\n );\n }\n return { fileName, match };\n}\n\n/**\n * Compares the name the browser gave a downloaded file with the wanted name.\n *\n * What it does: returns null when the name is acceptable, otherwise a plain\n * sentence saying what was expected and what arrived.\n *\n * How: 'exact' needs the same text; 'contains' needs the wanted text to be\n * somewhere inside the name. Case matters, as it does on most servers.\n */\nexport function downloadNameProblem(actual: string, expected: DownloadExpectation): string | null {\n const ok =\n expected.match === 'exact' ? actual === expected.fileName : actual.includes(expected.fileName);\n if (ok) {\n return null;\n }\n return `downloaded file is named \"${actual}\", expected a name that is ${expected.match === 'exact' ? 'exactly' : 'containing'} \"${expected.fileName}\"`;\n}\n\n/**\n * Clicks a target, waits for the browser to start a download, and checks the\n * saved file.\n *\n * What it does: passes only when a download starts, finishes without error,\n * has the wanted name and is not empty. Nothing is stored; the file lives in\n * the browser's temporary folder and is removed when the run's context ends.\n *\n * How: it starts waiting for the `download` event before the click (so a fast\n * download cannot be missed) and runs both together. When no download starts\n * in time the step fails as `app_regression` with a message saying so, rather\n * than the generic timeout text. The file size is read from the saved file.\n */\nexport async function runDownload(\n page: Page,\n target: Locator,\n expected: DownloadExpectation,\n timeoutMs: number,\n pointer: ReturnType<typeof pointerOptions>,\n): Promise<void> {\n let download: Download;\n try {\n const results = await Promise.all([\n page.waitForEvent('download', { timeout: timeoutMs }),\n target.click({ timeout: timeoutMs, ...pointer }),\n ]);\n download = results[0];\n } catch (err) {\n if (err instanceof Error && err.message.includes('waiting for event \"download\"')) {\n throw new StepFailure(\n 'app_regression',\n `no download started within ${timeoutMs} ms of the click`,\n );\n }\n throw err;\n }\n const failure = await download.failure();\n if (failure !== null) {\n throw new StepFailure('app_regression', `the download failed: ${failure}`);\n }\n const nameProblem = downloadNameProblem(download.suggestedFilename(), expected);\n if (nameProblem !== null) {\n throw new StepFailure('app_regression', nameProblem);\n }\n const savedPath = await download.path();\n const size = fs.statSync(savedPath).size;\n if (size === 0) {\n throw new StepFailure('app_regression', 'the downloaded file is empty (0 bytes)');\n }\n}\n\n/**\n * Builds the key chord to press, for example `Control+k`.\n *\n * Why: the recorder saves the key and the held modifiers separately.\n * Pressing only the key would turn Ctrl+K into a plain `k`.\n *\n * How: puts the modifiers in front of the key with `+`. A modifier that is\n * the key itself is dropped, because pressing Control alone is recorded\n * as key `Control` with modifier `Control`, and `Control+Control` is not a\n * valid chord.\n */\nexport function keyChord(key: string, modifiers: readonly string[]): string {\n const held = modifiers.filter((name) => name !== key);\n return [...held, key].join('+');\n}\n\n/**\n * The result of one step: pass/fail status, how long it took and where\n * the time went, how the element was found, wait and assertion outcomes,\n * overrides, diagnostics, the error and its class, and any artifacts.\n */\nexport interface StepResult {\n step_id: string;\n status: 'passed' | 'failed' | 'blocked' | 'skipped';\n duration_ms: number;\n timings: StepTimings;\n resolution: StepResolution | null;\n waits: Outcome[];\n assertions: Outcome[];\n overrides: OverrideOutcome[];\n diagnostics: StepDiagnostics;\n error: string | null;\n failure_class: FailureClass | null;\n /** For an upload step: where each file came from, in file order. Absent for other steps. */\n file_sources?: FileSource[];\n /**\n * For an upload step: the fixture (id and name at replay time) behind each file, or null for a\n * placeholder, in the same order as file_sources. Absent for other steps.\n */\n file_fixtures?: Array<FileFixture | null>;\n artifacts: Array<{ kind: 'screenshot' | 'trace'; object_key: string }>;\n}\n\n/**\n * Where an uploaded file came from: a fixture from the site's library, or a placeholder the\n * runner generated because the step had no fixture picked.\n */\nexport type FileSource = 'fixture' | 'placeholder';\n\n/**\n * Which library fixture an uploaded file came from: its id and the name it had when the run\n * read it. The name is stored in the result so the report still reads right after a later delete.\n */\nexport interface FileFixture {\n fixture_id: string;\n name: string;\n}\n\n/**\n * The files an upload step will put into its input, with the source of each one in the same order.\n * fixtures runs parallel to sources: the fixture behind a file, or null for a placeholder.\n */\ninterface UploadPlan {\n files: PlaceholderFile[];\n sources: FileSource[];\n fixtures: Array<FileFixture | null>;\n}\n\n/**\n * The final result of a whole run, in the shape the run-result contract\n * defines. It includes every step result and any values the run\n * extracted, generated or saved.\n */\nexport interface RunResult {\n schema_version: '1';\n run_id: string;\n test_case_id: string;\n def_version: number;\n status: 'passed' | 'failed' | 'blocked' | 'interrupted' | 'cancelled';\n /** The browser that ran the steps ('chromium' or 'firefox'). */\n browser: BrowserName;\n started_at: string;\n finished_at: string;\n steps: StepResult[];\n storage_state?: Record<string, unknown>;\n extracted_variables?: Record<string, string>;\n generated_values?: Record<string, string>;\n saved_values?: Record<string, string>;\n /** Values the test marked \"Export this value\" that this run may hand out, by name. */\n exports: Record<string, string>;\n /** Flagged values kept back, with the reason and never the value. */\n exports_withheld: ExportWithheld[];\n}\n\n/**\n * Replays one test run in a real browser (Playwright).\n * Given a RunBundle, `execute` launches the browser the run names, goes through each step\n * (find the element, perform the action, wait, check conditions), collects\n * evidence, uploads artifacts and returns a RunResult.\n */\nexport class Executor {\n /**\n * Works out the files an upload step puts into its file input.\n * A file with no fixture picked becomes a placeholder of the recorded name and type. A\n * picked fixture the bundle says is deleted or missing fails the step as an incomplete\n * test, and is never covered by a placeholder. A live one is downloaded and its digest\n * checked, and any download or digest problem fails the step as a runner error.\n */\n private async uploadFiles(bundle: RunBundle, step: RawStep): Promise<UploadPlan> {\n const entries = Array.isArray(step.params?.files) ? (step.params.files as unknown[]) : [];\n if (entries.length === 0) {\n throw new StepFailure('definition_incomplete', 'setInputFiles has no files to upload');\n }\n const files: PlaceholderFile[] = [];\n const sources: FileSource[] = [];\n const fixtures: Array<FileFixture | null> = [];\n for (const entry of entries) {\n const file = (entry ?? {}) as Record<string, unknown>;\n const name = typeof file.name === 'string' ? file.name : 'upload';\n const mimeType = typeof file.type === 'string' ? file.type : 'application/octet-stream';\n if (typeof file.fixture_id !== 'string') {\n files.push(placeholderFile(name, mimeType));\n sources.push('placeholder');\n fixtures.push(null);\n continue;\n }\n files.push(await this.fixtureFile(bundle, file.fixture_id, name));\n sources.push('fixture');\n fixtures.push({\n fixture_id: file.fixture_id,\n name: bundle.fixtures?.[file.fixture_id]?.name ?? name,\n });\n }\n return { files, sources, fixtures };\n }\n\n /**\n * Loads one picked fixture as an upload file, or fails the step saying why not.\n * The upload keeps the library name of the fixture, since that is the file the QA chose.\n */\n private async fixtureFile(\n bundle: RunBundle,\n fixtureId: string,\n recordedName: string,\n ): Promise<PlaceholderFile> {\n const info = bundle.fixtures?.[fixtureId];\n if (!info || info.missing) {\n throw new StepFailure(\n 'definition_incomplete',\n `Fixture ${fixtureId} no longer exists; pick another fixture for this step`,\n );\n }\n if (info.deleted_at) {\n throw new StepFailure(\n 'definition_incomplete',\n `Fixture \"${info.name}\" was deleted on ${info.deleted_at}; pick another fixture for this step`,\n );\n }\n let bytes: Buffer;\n try {\n bytes = await this.options.fetchFixture(bundle.run_id, fixtureId);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new StepFailure('runner_error', `Fixture \"${info.name}\" could not be read: ${reason}`);\n }\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (digest !== info.sha256) {\n throw new StepFailure(\n 'runner_error',\n `Fixture \"${info.name}\" was replaced after this run started; run the test again`,\n );\n }\n return { name: info.name || recordedName, mimeType: info.content_type, buffer: bytes };\n }\n\n /**\n * Remembers condition results that failed because the test itself is\n * incomplete (no target or no expected value), so they are reported as a\n * test problem rather than an app problem.\n */\n private readonly authoringGaps = new WeakSet<Outcome>();\n\n /**\n * Keeps the executor settings.\n */\n constructor(private readonly options: ExecutorOptions) {}\n\n /**\n * Runs a whole test and returns its result.\n * Sets up the value helpers and a temporary folder, launches the browser,\n * runs the steps in order (applying each step's failure policy), uploads\n * the failure screenshot and the trace, always closes the browser and\n * cleans up. Anything unexpected is turned into a failed result instead\n * of being thrown.\n * `cancel` is optional. When it fires, the browser is closed straight away so a step in the\n * middle of waiting fails fast, no further step starts, and the screenshot and trace are not\n * uploaded. The caller then drops the returned result.\n */\n async execute(bundle: RunBundle, cancel?: AbortSignal): Promise<RunResult> {\n // When the run started (ISO time).\n const startedAt = new Date().toISOString();\n // Fills in {{placeholders}} for this run.\n const interpolator = new VariableInterpolator(bundle);\n // Makes the run's generated test data.\n const generatedValues = new GeneratedValues(\n this.options.generatedValues ?? systemGeneratedValues,\n );\n // A private temporary folder for this run's trace and screenshot.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `locus-run-${bundle.run_id}-`));\n // Where the browser trace is written before upload.\n const tracePath = path.join(tempDir, 'trace.zip');\n // Where the failure screenshot is written before upload.\n const screenshotPath = path.join(tempDir, 'screenshot.png');\n\n // The name of the browser that actually started; stays null until a launch succeeds.\n let ranBrowser: BrowserName | null = null;\n // The browser, once launched.\n let browser: Browser | null = null;\n // The browser context (like a fresh profile) for this run.\n let context: BrowserContext | null = null;\n // The tab the steps run in.\n let page: Page | null = null;\n\n // Results of the steps run so far.\n const stepsResult: StepResult[] = [];\n // The run's overall result; becomes failed or blocked on the first problem.\n let overallStatus: 'passed' | 'failed' | 'blocked' = 'passed';\n // The login state saved at the end of an auth-prerequisite run.\n let capturedStorageState: Record<string, unknown> | undefined;\n // Values copied from responses by extract rules, for the run result.\n const extractedVariables: Record<string, string> = {};\n // Values the test marked \"Export this value\". The collector is the one place that decides\n // which of them may leave the run (secret, length and total size checks).\n const exportCollector = new ExportCollector(\n bundle.export_limits,\n Object.values(bundle.secrets ?? {}),\n );\n\n // True once the failure screenshot has been uploaded.\n let screenshotUploaded = false;\n // Takes and uploads one screenshot at the first failure, while the page\n // still shows what went wrong. It does nothing if one was already taken\n // or no upload address was given. A failure to capture is only logged;\n // it must never change the run's result.\n // `target` is the step's element when one was found, or null. When given, the page is first\n // scrolled so that element is on screen: the picture stays the visible viewport (a full-page\n // capture was judged riskier), but it then shows the element the step was working on instead\n // of whatever part of the page happened to be at the top. A failed scroll is ignored.\n const captureFailureScreenshot = async (target: Locator | null): Promise<void> => {\n // Pre-signed address where the screenshot is uploaded.\n const uploadUrl = bundle.artifact_upload_urls.screenshot;\n if (screenshotUploaded || !page || !uploadUrl || cancel?.aborted) {\n return;\n }\n try {\n if (target) {\n try {\n await target.scrollIntoViewIfNeeded({ timeout: 1000 });\n } catch (scrollErr: unknown) {\n this.options.log?.warn('could not scroll to the failed element', {\n run_id: bundle.run_id,\n error: scrollErr instanceof Error ? scrollErr.message : String(scrollErr),\n });\n }\n }\n // Fields that hold a secret are drawn as dots so the picture never shows one.\n await hideSecretFields(page, Object.values(bundle.secrets ?? {}));\n await page.screenshot({ path: screenshotPath, fullPage: false });\n const res = await fetch(uploadUrl, {\n method: 'PUT',\n headers: { 'Content-Type': 'image/png' },\n body: fs.readFileSync(screenshotPath),\n });\n if (!res.ok) {\n throw new Error(`upload returned HTTP ${res.status}`);\n }\n screenshotUploaded = true;\n } catch (err: unknown) {\n this.options.log?.warn('failure screenshot not captured', {\n run_id: bundle.run_id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Tracks the run's total time limit and scales step timeouts.\n const budget = new RunBudget(this.options.runTimeoutMs, bundle.timeout_multiplier);\n try {\n if (\n !Number.isFinite(bundle.timeout_multiplier) ||\n bundle.timeout_multiplier < 1 ||\n bundle.timeout_multiplier > 5\n ) {\n throw new StepFailure(\n 'runner_error',\n `INVALID_BUNDLE: timeout_multiplier must be between 1 and 5, got ${String(bundle.timeout_multiplier)}`,\n );\n }\n // The browser the run asked for. A missing or unknown name is a broken bundle and is\n // refused here; a known name that this runner has not enabled or cannot start fails the\n // run with the browser's name in the message. There is never a fall back to Chromium.\n if (!isBrowserName(bundle.browser)) {\n throw new StepFailure(\n 'runner_error',\n `INVALID_BUNDLE: browser must be one of chromium, firefox, got ${JSON.stringify(bundle.browser)}`,\n );\n }\n try {\n browser = await launchBrowser(bundle.browser, this.options);\n } catch (launchErr: unknown) {\n if (launchErr instanceof BrowserUnavailableError) {\n throw new StepFailure('runner_error', launchErr.message);\n }\n throw launchErr;\n }\n ranBrowser = bundle.browser;\n // A cancel closes the browser now, so any step that is waiting throws at once instead of\n // running until its own timeout. The close error is logged, never thrown.\n const launched = browser;\n cancel?.addEventListener(\n 'abort',\n () => {\n launched.close().catch((closeErr: unknown) => {\n this.options.log?.warn('browser close after cancel failed', {\n runId: bundle.run_id,\n error: closeErr instanceof Error ? closeErr.message : String(closeErr),\n });\n });\n },\n { once: true },\n );\n // Browser profile settings: window size, extra headers and saved login.\n // Bad HTTPS certificates are refused unless the environment owner switched on\n // \"accept invalid certificates\" for this environment (self-signed staging\n // servers). Only an exact true counts, so a missing or odd value stays strict.\n const contextOpts: Parameters<typeof browser.newContext>[0] = {\n viewport: { width: 1280, height: 720 },\n ignoreHTTPSErrors: bundle.allow_invalid_tls === true,\n };\n if (bundle.headers && Object.keys(bundle.headers).length > 0) {\n contextOpts.extraHTTPHeaders = bundle.headers;\n }\n if (bundle.storage_state && Object.keys(bundle.storage_state).length > 0) {\n contextOpts.storageState = bundle.storage_state as unknown as NonNullable<\n NonNullable<Parameters<typeof browser.newContext>[0]>['storageState']\n >;\n }\n context = await browser.newContext(contextOpts);\n await context.addInitScript(REPLAY_MARKER_SCRIPT);\n // Hide the areas the site owner excluded from pictures, before any page script runs.\n await installScreenshotHide(context, bundle.screenshot_hide_selectors ?? []);\n if (bundle.headers && Object.keys(bundle.headers).length > 0) {\n await context.setExtraHTTPHeaders(bundle.headers);\n }\n\n // Record a trace (screenshots and page snapshots) so a person can replay\n // what happened afterwards.\n await context.tracing.start({ screenshots: true, snapshots: true });\n page = await context.newPage();\n // Waits for the page's network activity to calm down after each action.\n const settler = new NetworkSettler(\n page,\n budget.scaled(this.options.settleTimeoutMs),\n this.options.settleQuietMs,\n );\n\n // Evidence collected while the run goes on: console errors/warnings,\n // uncaught page errors and failed network requests. Each step reads the\n // slice added since it started.\n const consoleEntries: Array<{ level: 'error' | 'warning'; text: string }> = [];\n // Uncaught errors thrown by the page.\n const pageErrors: string[] = [];\n // Requests that failed or came back with HTTP 400 or higher.\n const failedRequests: Array<{\n method: string;\n url: string;\n status: number | null;\n error_text: string | null;\n }> = [];\n\n // Every page of the run, in the order it appeared: index 0 is the first page, the rest are\n // tabs and popups. A step's `page` number is an index into this list.\n const pages: Page[] = [page];\n // Answers native dialogs on every page, using each step's `dialogs` settings.\n const dialogResponder = new DialogResponder();\n // Every network response seen on any page, kept so assertions and extract rules can read their\n // status, headers and body later.\n const observedResponses: ObservedResponse[] = [];\n // One network-quiet watcher per page, made when the page first needs one.\n const settlers = new Map<Page, NetworkSettler>([[page, settler]]);\n // Gives the watcher of a page, making it on first use. A popup needs its own because the first\n // page's watcher only sees the first page's requests.\n const settlerOf = (target: Page): NetworkSettler => {\n const known = settlers.get(target);\n if (known !== undefined) {\n return known;\n }\n const made = new NetworkSettler(\n target,\n budget.scaled(this.options.settleTimeoutMs),\n this.options.settleQuietMs,\n );\n settlers.set(target, made);\n return made;\n };\n // Hooks the evidence listeners (console, dialogs, errors, requests, responses) onto one page, so\n // a popup is recorded exactly like the first page.\n const watchPage = (watched: Page): void => {\n watched.on('console', (msg: ConsoleMessage) => {\n const type = msg.type();\n if (type === 'error' || type === 'warning') {\n consoleEntries.push({ level: type, text: msg.text() });\n }\n });\n // Without a listener Playwright dismisses native dialogs, so a confirm()\n // guarding an action (e.g. delete) returns false and the action never\n // fires. This answers them using each step's `dialogs` settings.\n watched.on('dialog', (dialog) => {\n void dialogResponder.handle(dialog);\n });\n watched.on('pageerror', (err: Error) => {\n pageErrors.push(err.message || String(err));\n });\n watched.on('requestfailed', (req: Request) => {\n failedRequests.push({\n method: req.method(),\n url: req.url(),\n status: null,\n error_text: req.failure()?.errorText ?? 'request failed',\n });\n });\n // Every network response seen, kept so assertions and extract rules can\n // read their status, headers and body later.\n watched.on('response', (res) => {\n observedResponses.push({\n method: res.request().method(),\n url: res.url(),\n status: res.status(),\n headers: res.headers(),\n bodyPromise: res.text().catch(() => ''),\n requestBody: res.request().postData(),\n });\n if (res.status() >= 400) {\n failedRequests.push({\n method: res.request().method(),\n url: res.url(),\n status: res.status(),\n error_text: `HTTP ${res.status()}`,\n });\n }\n });\n };\n watchPage(page);\n // A tab or popup opened by the page joins the list and gets the same listeners. The block on\n // private addresses is applied to the whole context below, so a popup cannot bypass it.\n context.on('page', (opened: Page) => {\n if (pages.length < MAX_PAGES) {\n pages.push(opened);\n watchPage(opened);\n }\n });\n\n // Safety: block any request to cloud metadata or private/internal\n // addresses (SSRF protection), whatever the test or the page asks for.\n // The guard judges the host text, then resolves the name and judges\n // every address it points to. A failed lookup is refused (fail closed).\n // Chromium resolves the name again itself afterwards, so a name that\n // changes its answer between the two lookups (DNS rebinding) is not\n // stopped here; that needs egress control at the network level.\n const hostGuard = new HostGuard({\n resolve: this.options.resolveHost ?? systemResolver,\n isBlockedText: (h: string) =>\n isPrivateOrBlockedHost(h, {\n allowLoopback: this.options.allowLoopback,\n allowPrivateNetworks: this.options.allowPrivateNetworks,\n }),\n maxEntries: HOST_GUARD_MAX_ENTRIES,\n });\n await context.route('**/*', async (route: Route) => {\n const reqUrl = route.request().url();\n // The host of the request, or null when the URL cannot be parsed.\n let hostname: string | null = null;\n try {\n hostname = new URL(reqUrl).hostname;\n } catch {\n // A URL that cannot be parsed has no host to judge; let the browser handle it.\n }\n if (hostname !== null) {\n // The guard's answer for this host.\n const verdict = await hostGuard.check(hostname);\n if (verdict !== 'allowed') {\n return route.abort('blockedbyclient');\n }\n }\n return route.continue();\n });\n\n // The saved test: start URL, steps and variables.\n const definition = bundle.definition;\n // The steps, as loosely typed data from the saved test.\n const rawSteps: RawStep[] = (definition.steps as unknown as RawStep[]) || [];\n\n // The first page to open: the first enabled navigate step's custom URL\n // if it has one, otherwise the test's start URL. Tokens are expanded beforehand\n // so URLs starting with {{BASE_URL}} resolve cleanly instead of percent-encoding.\n const openingUrl = initialUrl(rawSteps, definition.start_url, interpolator);\n // Position of the first enabled step (used to skip the duplicate\n // navigate, since the run already opened that page).\n const firstEnabledIdx = rawSteps.findIndex((st) => st.enabled !== false);\n // The page we already opened before the first step, so a matching\n // navigate step does not load it twice.\n let preloadedUrl = '';\n if (openingUrl) {\n // The start URL after applying the environment's base URL and\n // placeholders. Checked against the SSRF rules before use.\n let startUrl = interpolator.interpolate(openingUrl);\n if (\n bundle.base_url_override &&\n (startUrl.startsWith('http://') || startUrl.startsWith('https://'))\n ) {\n try {\n const targetUrl = new URL(startUrl);\n const baseOverride = bundle.base_url_override.replace(/\\/+$/, '');\n startUrl = `${baseOverride}${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;\n } catch {\n // Ignore\n }\n }\n startUrl = interpolator.interpolate(startUrl);\n preloadedUrl = startUrl;\n // The start URL's host, or null when the URL cannot be parsed\n // (the load below then fails as 'environment unreachable').\n let startHost: string | null = null;\n try {\n startHost = new URL(startUrl).hostname;\n } catch {\n // Ignore: page.goto reports an unparsable URL.\n }\n if (startHost !== null) {\n // The guard's answer for the start host.\n const startVerdict = await hostGuard.check(startHost);\n if (startVerdict === 'private') {\n throw new StepFailure(\n 'runner_error',\n `Replay blocked: start URL hostname ${startHost} is private or disallowed`,\n );\n }\n if (startVerdict === 'unresolved') {\n throw new StepFailure(\n 'env_unreachable',\n `ENVIRONMENT_UNREACHABLE: start URL host ${startHost} could not be resolved, so it cannot be checked against private addresses`,\n );\n }\n }\n // The server's answer for the start page. A load failure or HTTP 5xx\n // stops the run as 'environment unreachable', not as an app failure.\n let startResponse: Response | null;\n try {\n startResponse = await page.goto(startUrl, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n waitUntil: 'domcontentloaded',\n });\n } catch (err: unknown) {\n throw new StepFailure(\n 'env_unreachable',\n `ENVIRONMENT_UNREACHABLE: start URL ${startUrl} did not load: ${errorLine(err)}`,\n );\n }\n if (startResponse !== null && startResponse.status() >= 500) {\n throw new StepFailure(\n 'env_unreachable',\n `ENVIRONMENT_UNAVAILABLE: start URL ${startUrl} returned HTTP ${startResponse.status()}`,\n );\n }\n await settlerOf(page).settle();\n }\n\n // Where in the failed-request list the current step's login evidence\n // begins. It spans everything since the previous step ended, so 401s\n // from the start page load count toward the first step.\n let authEvidenceFrom = 0;\n for (let i = 0; i < rawSteps.length; i++) {\n // The step being run.\n const step = rawSteps[i]!;\n if (cancel?.aborted) {\n // The run was cancelled: start no more steps. The consumer drops this result.\n break;\n }\n // The step's id, or a generated one like step-00000001.\n const stepId = step.step_id || step.id || `step-${String(i + 1).padStart(8, '0')}`;\n\n if (step.enabled === false) {\n stepsResult.push({\n step_id: stepId,\n status: 'skipped',\n duration_ms: 0,\n timings: { resolve_ms: 0, action_ms: 0, settle_ms: 0, conditions_ms: 0 },\n resolution: null,\n waits: [],\n assertions: [],\n overrides: [],\n diagnostics: { console: [], page_errors: [], failed_requests: [] },\n error: null,\n failure_class: null,\n artifacts: [],\n });\n continue;\n }\n\n // What the step does (click, fill, navigate...). Defaults to click.\n const action = step.action || 'click';\n // Lets a missing {{token}} message name this step.\n interpolator.enterStep(step.name || step.step_id || action);\n // When this step started, to compute its duration.\n const stepStartTime = Date.now();\n\n // How many console/page-error/failed-request entries existed before the\n // step, so we can report only what the step itself caused.\n const stepConsoleBefore = consoleEntries.length;\n const stepErrorsBefore = pageErrors.length;\n const stepFailedReqsBefore = failedRequests.length;\n\n // The step's outcome so far; starts passed and changes on failure.\n let stepStatus: 'passed' | 'failed' | 'blocked' = 'passed';\n // The error message if the step fails.\n let stepError: string | null = null;\n // Who the failure points at (app, locator, environment, runner...).\n let failureClass: FailureClass | null = null;\n // How the target element was found (strategy, confidence, backups).\n let resolution: StepResolution | null = null;\n // Where an upload step's files came from; stays null for every other step.\n let fileSources: FileSource[] | null = null;\n // The fixture behind each uploaded file (null for a placeholder), parallel to fileSources.\n let fileFixtures: Array<FileFixture | null> | null = null;\n // The Playwright locator for the step's element, once found.\n let targetLocator: Locator | null = null;\n // Results of the step's wait conditions.\n const waits: Outcome[] = [];\n // Results of the step's assertions.\n const assertions: Outcome[] = [];\n // Which payload overrides were actually applied.\n const overrides: OverrideOutcome[] = [];\n // Override routes live for this step only: removed once it ends, so\n // later steps are untouched.\n const stepRoutes: Array<{\n matches: (url: URL) => boolean;\n handler: (route: Route) => Promise<void>;\n }> = [];\n // Splits this step's time between finding, acting, settling and checking.\n const timer = new PhaseTimer();\n // A run past its deadline stops here, whatever the step's failure policy.\n const runExpired = budget.expired();\n if (runExpired) {\n stepStatus = 'failed';\n stepError = `RUN_TIMEOUT: the run exceeded its ${this.options.runTimeoutMs}ms limit before this step`;\n failureClass = 'runner_timeout';\n }\n // How many tries this step may have (0 if the run is already out of time).\n const maxAttempts = runExpired ? 0 : stepAttempts(step, this.options.stepRetries);\n // Which try we are on (1 is the first).\n let attempt = 0;\n\n while (attempt < maxAttempts && (attempt === 0 || !budget.expired())) {\n attempt++;\n if (attempt > 1) {\n timer.enter('settle_ms');\n await settlerOf(page).settle();\n }\n if (armsDialogs(action)) {\n dialogResponder.arm(\n resolveDialogExpectations(step, bundle, interpolator),\n step.name || action,\n );\n for (const note of dialogResponder.takeUnmet()) {\n consoleEntries.push({ level: 'warning', text: `Locus dialog: ${note}` });\n }\n }\n timer.enter('resolve_ms');\n stepStatus = 'passed';\n stepError = null;\n failureClass = null;\n resolution = null;\n targetLocator = null;\n waits.length = 0;\n assertions.length = 0;\n // Evidence for assertions and extraction is scoped to the current\n // attempt, so a retry is not judged by what the earlier try left behind.\n const attemptConsoleBefore = consoleEntries.length;\n // Page-error count at the start of this attempt.\n const attemptErrorsBefore = pageErrors.length;\n // Response count at the start of this attempt.\n const stepResponsesBefore = observedResponses.length;\n\n try {\n // 0. Pick the page the step runs on: the one it names, else the page the run is on. A\n // popup that closed itself since the last step sends the run back to an open page.\n const wantedPage = pageIndexOf(step);\n if (wantedPage !== null) {\n page = await waitForPage(pages, wantedPage, budget.limit(this.options.stepTimeoutMs));\n await page.bringToFront();\n } else if (page.isClosed()) {\n page = openPageBefore(pages, page);\n await page.bringToFront();\n }\n // 1. Payload overrides: rewrite one request-body field, in the browser,\n // before the request leaves. Routes stay for all attempts, so they are\n // registered once and report on attempt 1.\n if (attempt === 1 && Array.isArray(step.payload_overrides)) {\n for (const ovr of step.payload_overrides) {\n // Id of this override, for the report.\n const ovrId = ovr.override_id;\n const method = ovr.request_match.method.toUpperCase();\n // The part of the URL (path and query) that identifies the request.\n const needle = overrideUrlNeedle(\n interpolator.interpolateStrict(ovr.request_match.url_pattern),\n );\n const fieldPath = ovr.field_path;\n const raw =\n ovr.value.source === 'secret'\n ? (bundle.secrets[ovr.value.secret_ref ?? ''] ?? '')\n : interpolator.interpolateStrict(ovr.value.static_value ?? '');\n // Becomes applied=true when the field was really rewritten.\n const outcome: OverrideOutcome = { override_id: ovrId, applied: false };\n overrides.push(outcome);\n // True for requests this override applies to.\n const matches = (url: URL) => url.href.includes(needle);\n // Rewrites the first matching request of this step, then leaves every\n // other alone.\n const handler = async (route: Route): Promise<void> => {\n const request = route.request();\n const body = request.postData();\n if (\n outcome.applied ||\n body === null ||\n (method !== 'ANY' && request.method().toUpperCase() !== method)\n ) {\n return route.fallback();\n }\n const rewritten = rewriteBody(\n body,\n request.headers()['content-type'] ?? '',\n fieldPath,\n raw,\n );\n if (rewritten === null) {\n return route.fallback();\n }\n outcome.applied = true;\n return route.fallback({ postData: rewritten });\n };\n await page.route(matches, handler);\n stepRoutes.push({ matches, handler });\n }\n }\n\n // 2. The text the step will use (typed, selected, etc.).\n let textValue = '';\n // True only for static text whose switch (expand_values) is on: that text is a\n // template, so a {{name}} nothing defines must fail. All other text is used as typed.\n let textIsTemplate = false;\n // True when the text came from this run's data row. A row value is typed as it\n // is: it is not run through {{...}} again, so a cell holding `{{x}}` stays literal.\n let textIsRowValue = false;\n // Work out the text for this step, from the first source that applies:\n // a secret, a variable, a generated value, static text (which may hold\n // [[generated]] tokens and saved {{values}}) or plain text.\n if (step.value) {\n // The step's value settings.\n const valObj = step.value;\n if (valObj.source === 'secret' && valObj.secret_ref) {\n textValue = bundle.secrets[valObj.secret_ref] ?? '';\n } else if (valObj.source === 'variable' && valObj.variable_name) {\n const vars = (bundle.definition.variables || []) as Array<{\n name: string;\n value: string;\n }>;\n // The row's value for this name wins; the definition default is the fallback.\n const rowValue = interpolator.rowValueFor(valObj.variable_name);\n if (rowValue !== undefined) {\n textValue = rowValue;\n textIsRowValue = true;\n } else {\n textValue = vars.find((v) => v.name === valObj.variable_name)?.value ?? '';\n }\n } else if (valObj.source === 'generated') {\n if (action !== 'fill' || !isGeneratedKind(valObj.kind)) {\n throw new StepFailure(\n 'definition_incomplete',\n `a generated value needs a fill step and a known kind (got ${action}, ${String(valObj.kind)})`,\n );\n }\n // The field's recorded input type; it only matters for date kinds.\n const inputType = step.params?.input_type;\n try {\n textValue = generatedValues.valueFor(\n valObj.kind,\n typeof inputType === 'string' ? inputType : undefined,\n );\n } catch (err) {\n throw new StepFailure(\n 'definition_incomplete',\n err instanceof Error ? err.message : String(err),\n );\n }\n } else if (valObj.static_value !== undefined && valObj.static_value !== null) {\n textValue = String(valObj.static_value);\n if (valObj.expand_values === true) {\n textIsTemplate = true;\n if (textValue.includes('[[') && action !== 'fill') {\n throw new StepFailure(\n 'definition_incomplete',\n `a [[generated]] token in a value needs a fill step (got ${action})`,\n );\n }\n try {\n textValue = generatedValues.expand(textValue);\n } catch (err) {\n throw new StepFailure(\n 'definition_incomplete',\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n } else if (valObj.text) {\n textValue = valObj.text;\n }\n }\n\n // Fall back to a plain value in the step's params if nothing above\n // produced text.\n if (!textValue && step.params) {\n // The raw value from params (text, number or boolean).\n const paramVal = step.params.value;\n if (typeof paramVal === 'string') {\n textValue = paramVal;\n textIsRowValue = false;\n } else if (typeof paramVal === 'number' || typeof paramVal === 'boolean') {\n textValue = String(paramVal);\n textIsRowValue = false;\n }\n }\n\n // The step's text before its {{...}} pass. Kept so the save below can refuse text\n // that names a secret, even a short one the by-value check cannot see.\n const textTemplate = textValue;\n\n // Fill in {{BASE_URL}}, variables, saved values and secrets in the final text, in one\n // pass. Static text with the expand switch on must have every {{name}} defined.\n // A value that came from the data row is already final and is left as it is.\n if (!textIsRowValue) {\n textValue = textIsTemplate\n ? interpolator.expandTemplate(textValue, 'literal')\n : interpolator.interpolate(textValue);\n }\n\n // Remember what a fill step typed so later steps can reuse it. The saved text is the\n // final text the field receives, and later fields insert it without expanding it again.\n // Text that holds or names a secret is refused, so a secret can never be saved and\n // then printed in a later check's expected text.\n if (action === 'fill' && typeof step.save_as === 'string' && step.save_as !== '') {\n if (step.value?.source === 'secret') {\n throw new StepFailure(\n 'definition_incomplete',\n 'a secret value cannot be saved for later fields',\n );\n }\n if (\n step.value?.source === 'variable' &&\n typeof step.value.variable_name === 'string' &&\n interpolator.isRowSecretColumn(step.value.variable_name)\n ) {\n throw new StepFailure(\n 'definition_incomplete',\n `the value of the secret column \"${step.value.variable_name}\" cannot be saved for later fields`,\n );\n }\n // The secret this step's own text names as {{name}}, if any (never a value).\n const namedSecret = textIsRowValue\n ? undefined\n : interpolator.secretNameIn(textTemplate);\n if (namedSecret !== undefined) {\n throw new StepFailure(\n 'definition_incomplete',\n `the value uses the secret \"${namedSecret}\", so it cannot be saved for later fields`,\n );\n }\n if (holdsSecret(textValue, Object.values(bundle.secrets ?? {}))) {\n throw new StepFailure(\n 'definition_incomplete',\n 'the value holds a secret, so it cannot be saved for later fields',\n );\n }\n interpolator.saveValue(step.save_as, textValue);\n if (step.export_saved === true) {\n exportCollector.add(step.save_as, 'saved', textValue);\n }\n }\n\n // A recorded fill value the control plane could not resolve from\n // evidence must never replay as '' (it would silently type nothing).\n if (action === 'fill' && step.value?.source === 'recorded') {\n throw new StepFailure(\n 'definition_incomplete',\n 'RECORDED_VALUE_UNRESOLVED: the recorded value is unavailable (masked or missing evidence); set a static value, variable or secret on this step',\n );\n }\n\n // 3. Find the target element. Locators are tried in order, and a\n // result only counts when it matches exactly one element.\n if (step.target) {\n const target = step.target;\n // The iframes the element sits in (none for the top page).\n const framePath = framePathOf(target);\n const scope = frameScope(page, framePath);\n // A person's manual edits to the locators (order, disabled, custom).\n const overrides = target.overrides;\n // Locators the user switched off.\n const disabledRefs = overrides?.disabled?.map((d) => d.ref) || [];\n // True if this locator has been switched off.\n const isDisabled = (l: { strategy: string; expression: string }) =>\n disabledRefs.some(\n (r) => r && r.strategy === l.strategy && r.expression === l.expression,\n );\n\n // The locators we may use: the custom one first, then the recorded ones,\n // minus any disabled.\n const candidatePool: Array<{ strategy: string; expression: string }> = [];\n if (overrides?.custom_locator && !isDisabled(overrides.custom_locator)) {\n candidatePool.push({\n strategy: overrides.custom_locator.strategy,\n expression: overrides.custom_locator.expression,\n });\n }\n if (Array.isArray(target.locators)) {\n for (const loc of target.locators) {\n if (!isDisabled(loc)) {\n candidatePool.push(loc);\n }\n }\n }\n\n // The locators in the order we will try them: the user's chosen order\n // first, then any others.\n let activeLocators: Array<{ strategy: string; expression: string }> = [];\n if (Array.isArray(overrides?.order) && overrides.order.length > 0) {\n for (const ref of overrides.order) {\n const match = candidatePool.find(\n (c) => c.strategy === ref.strategy && c.expression === ref.expression,\n );\n if (match && !activeLocators.includes(match)) {\n activeLocators.push(match);\n }\n }\n for (const c of candidatePool) {\n if (!activeLocators.includes(c)) {\n activeLocators.push(c);\n }\n }\n } else {\n activeLocators = candidatePool;\n }\n\n if (activeLocators.length > 0) {\n // Strategies that did not find exactly one element.\n const failedStrategies: Array<\n 'semantic' | 'stable_attribute' | 'relational' | 'css' | 'xpath'\n > = [];\n // The strategy that finally found the element.\n let chosenStrategy:\n | 'semantic'\n | 'stable_attribute'\n | 'relational'\n | 'css'\n | 'xpath'\n | null = null;\n // True if the element was found by something other than the first locator.\n let fallbackUsed = false;\n // What each locator found on its last try (match count or error).\n const observations: LocatorObservation[] = activeLocators.map((l) => ({\n strategy: l.strategy,\n outcome: 0,\n }));\n\n // How the element was found: an exact locator, a fuzzy name match, or not at all.\n let resolvedBy: 'exact' | 'fuzzy' | null = null;\n // Position of the locator that worked (-1 if none).\n let chosenIdx = -1;\n\n // Keep trying until the step timeout, because the page may still be\n // drawing the element.\n const deadline = Date.now() + budget.limit(this.options.stepTimeoutMs);\n while (Date.now() <= deadline) {\n // This loop tries each locator in order.\n // It runs again and again until the step timeout, because the page may\n // still be drawing the element.\n // Exact expressions first: a fuzzy name match must never win over an exact locator.\n for (let locIdx = 0; locIdx < activeLocators.length; locIdx++) {\n const loc = activeLocators[locIdx]!;\n try {\n const pwLocator = scope.locator(loc.expression);\n const count = await pwLocator.count();\n observations[locIdx]!.outcome = count;\n if (count === 1) {\n targetLocator = pwLocator;\n chosenStrategy = loc.strategy as StrategyName;\n fallbackUsed = locIdx > 0;\n resolvedBy = 'exact';\n chosenIdx = locIdx;\n break;\n }\n } catch (err: unknown) {\n // Keep polling; the last selector error is reported if nothing resolves\n observations[locIdx]!.outcome = errorLine(err);\n }\n }\n\n // Backup: if no exact locator matched, try a looser match for role locators whose recorded name joined words together.\n // Resilient fallback for semantic/relational role selectors with concatenated or sub-text\n if (!targetLocator) {\n for (let locIdx = 0; locIdx < activeLocators.length; locIdx++) {\n const loc = activeLocators[locIdx]!;\n if (\n observations[locIdx]!.outcome !== 0 ||\n (loc.strategy !== 'semantic' && loc.strategy !== 'relational')\n ) {\n continue;\n }\n const fuzzyExpression = fuzzyRoleExpression(loc.expression);\n if (fuzzyExpression === null) {\n continue;\n }\n try {\n const fuzzyLoc = scope.locator(fuzzyExpression);\n const fuzzyCount = await fuzzyLoc.count();\n observations[locIdx]!.loose = fuzzyCount;\n if (fuzzyCount === 1) {\n targetLocator = fuzzyLoc;\n chosenStrategy = loc.strategy as StrategyName;\n fallbackUsed = true;\n resolvedBy = 'fuzzy';\n break;\n }\n } catch (err: unknown) {\n observations[locIdx]!.outcome = errorLine(err);\n }\n }\n }\n\n // Found it: stop polling. Otherwise wait a moment and try again.\n if (targetLocator) break;\n await page.waitForTimeout(100);\n }\n\n // Why: each strategy then has a match count, so the confidence score\n // reflects how many strategies agree.\n // Probe the locators behind the chosen one once so scores reflect every strategy.\n // Those that matched exactly one element are kept so the check below can\n // confirm they mean the same element as the winner. The probe uses `scope`\n // (the frame the step runs in), like the loop above; the old `page` probe\n // could not see inside a frame.\n const otherUnique: UniqueLocator[] = [];\n for (\n let locIdx = chosenIdx + 1;\n chosenIdx >= 0 && locIdx < activeLocators.length;\n locIdx++\n ) {\n try {\n const probe = scope.locator(activeLocators[locIdx]!.expression);\n const probeCount = await probe.count();\n observations[locIdx]!.outcome = probeCount;\n if (probeCount === 1) {\n otherUnique.push({\n strategy: activeLocators[locIdx]!.strategy,\n expression: activeLocators[locIdx]!.expression,\n locator: probe,\n });\n }\n } catch (err: unknown) {\n observations[locIdx]!.outcome = errorLine(err);\n }\n }\n\n // Locators (before or after the winner) that matched several elements. They are\n // kept so the check below can confirm the winner is one of those elements.\n const ambiguousLocators: UniqueLocator[] = [];\n if (chosenIdx >= 0) {\n activeLocators.forEach((loc, locIdx) => {\n const outcome = observations[locIdx]!.outcome;\n if (locIdx !== chosenIdx && typeof outcome === 'number' && outcome > 1) {\n ambiguousLocators.push({\n strategy: loc.strategy,\n expression: loc.expression,\n locator: scope.locator(loc.expression),\n });\n }\n });\n }\n\n // Record which strategies did not find exactly one element.\n activeLocators.forEach((loc, locIdx) => {\n if (observations[locIdx]!.outcome !== 1) {\n failedStrategies.push(loc.strategy as StrategyName);\n }\n });\n\n // Summary of how the element was found, for the run report.\n resolution = {\n resolved_strategy: chosenStrategy,\n fallback_used: fallbackUsed,\n failed_strategies: failedStrategies,\n candidates: activeLocators.map((c, locIdx) => {\n const outcome = observations[locIdx]!.outcome;\n return {\n description: `${c.strategy}: ${c.expression}`,\n score: candidateScore(outcome),\n signals: typeof outcome === 'number' ? { match_count: outcome } : {},\n };\n }),\n confidence: resolutionConfidence(observations, resolvedBy),\n position_pick: null,\n };\n\n // A position locator always reports one element once its position is\n // applied, so count the base expression on its own to say \"first of 12\".\n // A failed count only leaves the field null; it must not fail the step.\n if (chosenIdx >= 0 && resolvedBy === 'exact') {\n const split = splitPositionLocator(activeLocators[chosenIdx]!.expression);\n if (split !== null) {\n try {\n const matched = await scope.locator(split.base).count();\n resolution.position_pick = describePositionPick(split.offset, matched);\n } catch (err: unknown) {\n this.options.log?.warn('position count failed', { error: errorLine(err) });\n }\n }\n }\n\n // Nothing was found, so this step fails: as 'ambiguous' if some locator\n // matched several elements, otherwise as 'not found'.\n if (!targetLocator) {\n // Only the last attempt reports near matches; a capture failure changes nothing\n // Near matches are read from the top page only, so a frame target skips them.\n if (attempt >= maxAttempts && framePath.length === 0) {\n const recorded = recordedTargetOf(target.locators ?? []);\n if (recorded !== null) {\n resolution.near_matches = await captureNearMatches(\n page,\n recorded,\n this.options.nearMatch,\n );\n }\n }\n throw new StepFailure(\n observations.some((o) => typeof o.outcome === 'number' && o.outcome > 1)\n ? 'locator_ambiguous'\n : 'locator_not_found',\n describeResolutionFailure(observations) +\n frameNote(framePath) +\n describeDisabledPreconditions(observations, rawSteps.slice(0, i)),\n );\n }\n // The winning locator and every other locator that found one element must\n // mean the same element (or nested ones). Otherwise the step would click what\n // one strategy says while another says something else: fail loudly instead.\n // Fuzzy matches have no exact winner, so they are not compared.\n if (\n resolvedBy === 'exact' &&\n (otherUnique.length > 0 || ambiguousLocators.length > 0)\n ) {\n // Locators whose element is unrelated to the winner's: those that found one\n // other element, and those whose several elements do not include the winner.\n const conflicts = [\n ...(await findLocatorConflicts(targetLocator, otherUnique)),\n ...(await findAmbiguousConflicts(targetLocator, ambiguousLocators)),\n ];\n if (conflicts.length > 0) {\n throw new StepFailure(\n 'locator_conflict',\n describeLocatorConflict(\n chosenStrategy,\n await nameElement(targetLocator),\n conflicts,\n ) + frameNote(framePath),\n );\n }\n }\n // Is this the element that was recorded? Ambiguity above the winner needs a\n // second independent family; then the identity and neighbour facts are compared.\n // A loose (fuzzy) match is checked the same way, minus the ambiguity rule.\n if (resolvedBy !== null && chosenIdx >= 0) {\n try {\n resolution.target_checks = await verifyFoundTarget({\n locator: targetLocator,\n engineBundle: this.options.nearMatch.engineBundle,\n recorded: target.verification ?? null,\n winner: activeLocators[chosenIdx]!,\n agreeing: otherUnique,\n ambiguousAboveWinner:\n resolvedBy === 'exact' &&\n activeLocators.some((_, locIdx) => {\n const outcome = observations[locIdx]!.outcome;\n return locIdx < chosenIdx && typeof outcome === 'number' && outcome > 1;\n }),\n framePath,\n });\n // The recorded first choice failed and the role-and-name locator found it instead.\n if (\n resolution.fallback_used &&\n activeLocators[chosenIdx]!.strategy === 'semantic' &&\n !resolution.target_checks.includes('semantic_fallback')\n ) {\n resolution.target_checks.push('semantic_fallback');\n }\n } catch (err: unknown) {\n // On the last attempt a target_mismatch also reports what the page now has, so\n // a person can accept a repair or re-record. A capture failure changes nothing.\n if (\n err instanceof StepFailure &&\n err.failureClass === 'target_mismatch' &&\n attempt >= maxAttempts &&\n framePath.length === 0\n ) {\n const recorded = recordedTargetOf(target.locators ?? []);\n if (recorded !== null) {\n resolution.near_matches = await captureNearMatches(\n page,\n recorded,\n this.options.nearMatch,\n );\n }\n }\n throw err;\n }\n }\n // The step found its element by a fallback: describe it with fresh\n // locators so a person can refresh the stale ones. A capture failure\n // changes nothing.\n if (\n resolution.fallback_used &&\n resolution.failed_strategies.length > 0 &&\n framePath.length === 0\n ) {\n // The step found its element by a fallback: describe it with fresh locators so a\n // person can refresh the stale ones. A capture failure changes nothing.\n const recorded = recordedTargetOf(target.locators ?? []);\n if (recorded !== null) {\n resolution.near_matches = await captureResolvedMatch(\n page,\n targetLocator,\n recorded,\n this.options.nearMatch,\n );\n }\n }\n }\n }\n\n // A step that needs an element but has none (no target, or every locator\n // switched off) would otherwise skip its action and pass. Fail it.\n if (TARGET_REQUIRED_ACTIONS.has(action) && !targetLocator) {\n throw new StepFailure(\n 'definition_incomplete',\n `${action} needs a target element but this step has no usable locator`,\n );\n }\n\n // 4. Perform the step's action. The switch below does what the step\n // says (navigate, click, fill, ...) with timeouts capped by the run\n // budget.\n timer.enter('action_ms');\n // The page the action starts on, to tell a popup that closed itself from a real failure.\n const actionPage = page;\n try {\n switch (action) {\n case 'navigate': {\n // A URL typed into the step in the editor, if any.\n let customUrl = stringParam(step, 'url');\n if (customUrl) {\n customUrl = interpolator.interpolateStrict(customUrl);\n }\n // Start URL interpolated so relative paths resolve against the active environment.\n const resolvedStartUrl = definition.start_url\n ? interpolator.interpolate(definition.start_url)\n : definition.start_url;\n // The page to open: the custom URL, else the step text, else the\n // test's start URL.\n let url = customUrl\n ? resolveStepUrl(customUrl, resolvedStartUrl)\n : textValue || resolvedStartUrl;\n if (\n url &&\n bundle.base_url_override &&\n (url.startsWith('http://') || url.startsWith('https://'))\n ) {\n try {\n const targetUrl = new URL(url);\n const baseOverride = bundle.base_url_override.replace(/\\/+$/, '');\n url = `${baseOverride}${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;\n } catch {\n // URL does not start with an origin or is invalid, keep as is\n }\n }\n if (url) {\n url = interpolator.interpolateStrict(url);\n }\n // The opening navigate already loaded this page before the first step\n if (url && !(i === firstEnabledIdx && url === preloadedUrl)) {\n await page.goto(url, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n waitUntil: 'domcontentloaded',\n });\n }\n break;\n }\n case 'click': {\n if (targetLocator) {\n await targetLocator.click({\n timeout: budget.limit(this.options.stepTimeoutMs),\n ...pointerOptions(step),\n });\n }\n break;\n }\n case 'dblclick': {\n if (targetLocator) {\n await targetLocator.dblclick({\n timeout: budget.limit(this.options.stepTimeoutMs),\n ...pointerOptions(step),\n });\n }\n break;\n }\n case 'rightClick': {\n if (targetLocator) {\n await targetLocator.click({\n timeout: budget.limit(this.options.stepTimeoutMs),\n ...pointerOptions(step, 'right'),\n });\n }\n break;\n }\n case 'hover': {\n if (targetLocator) {\n const held = stepModifiers(step);\n await targetLocator.hover({\n timeout: budget.limit(this.options.stepTimeoutMs),\n ...(held.length > 0 ? { modifiers: held } : {}),\n });\n }\n break;\n }\n // Picks the target up and drops it on the element named in params.to.\n case 'dragTo': {\n if (targetLocator) {\n const limit = budget.limit(this.options.stepTimeoutMs);\n const dropOn = await resolveDropTarget(page, step, limit);\n // The drop zone is verified like any target: a wrong zone is a wrong action.\n const dropChecks = await verifyFoundTarget({\n locator: dropOn.locator,\n engineBundle: this.options.nearMatch.engineBundle,\n recorded: dropOn.verification,\n winner: dropOn.winner,\n agreeing: [],\n ambiguousAboveWinner: false,\n framePath: dropOn.framePath,\n });\n if (resolution !== null) {\n resolution.target_checks = Array.from(\n new Set([...(resolution.target_checks ?? []), ...dropChecks]),\n );\n }\n await targetLocator.dragTo(dropOn.locator, { timeout: limit });\n }\n break;\n }\n // Closes the page the step is on (a popup or tab) and goes back to an open earlier page.\n // The first page is never closed: closing it would end the run.\n case 'closePage': {\n if (pages.indexOf(page) <= 0) {\n throw new StepFailure(\n 'definition_incomplete',\n 'closePage needs a step page of 1 or more; the first page cannot be closed',\n );\n }\n const closing = page;\n await closing.close();\n page = openPageBefore(pages, closing);\n await page.bringToFront();\n break;\n }\n // Clicks the target, waits for the download it starts and checks the file.\n case 'download': {\n if (targetLocator) {\n await runDownload(\n page,\n targetLocator,\n downloadExpectation(step),\n budget.limit(this.options.stepTimeoutMs),\n pointerOptions(step),\n );\n }\n break;\n }\n // A pause for a person to look at the page. The runner has nothing to do.\n case 'manualCheckpoint': {\n break;\n }\n case 'fill': {\n if (targetLocator) {\n // A secret must never be drawn in plain text: the trace keeps screenshots.\n // The field is turned into dots first, then typed into.\n if (holdsSecret(textValue, Object.values(bundle.secrets ?? {}))) {\n await hideField(targetLocator);\n }\n await targetLocator.fill(textValue, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n case 'clear': {\n if (targetLocator) {\n await targetLocator.fill('', {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n case 'selectOption': {\n if (targetLocator) {\n const choices = selectOptionChoices(step, textValue);\n if (choices.length === 0) {\n throw new StepFailure(\n 'definition_incomplete',\n 'selectOption has no option values to select',\n );\n }\n // The wanted options matched against what the dropdown offers now.\n const optionValues = await this.waitForOptions(\n page,\n targetLocator,\n choices,\n budget.limit(this.options.stepTimeoutMs),\n );\n await targetLocator.selectOption(optionValues, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n case 'setInputFiles': {\n if (targetLocator) {\n const plan = await this.uploadFiles(bundle, step);\n await targetLocator.setInputFiles(plan.files, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n fileSources = plan.sources;\n fileFixtures = plan.fixtures;\n }\n break;\n }\n case 'check': {\n if (targetLocator) {\n await targetLocator.check({\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n case 'uncheck': {\n if (targetLocator) {\n await targetLocator.uncheck({\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n case 'pressKey': {\n // The key to press: from params, else the step's key, else Enter.\n const key =\n stringParam(step, 'key') || (typeof step.key === 'string' ? step.key : 'Enter');\n // The held keys (Control, Shift...) go in front: Ctrl+K must not become \"k\".\n const chord = keyChord(key, stepModifiers(step));\n if (targetLocator) {\n await targetLocator.press(chord, {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n } else {\n await page.keyboard.press(chord);\n }\n break;\n }\n case 'scroll': {\n if (targetLocator) {\n await targetLocator.scrollIntoViewIfNeeded({\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n } else {\n await page.mouse.wheel(0, 300);\n }\n break;\n }\n case 'submit': {\n if (targetLocator) {\n await targetLocator.press('Enter', {\n timeout: budget.limit(this.options.stepTimeoutMs),\n });\n }\n break;\n }\n // Wait actions: pause until the element is visible/hidden or the URL\n // matches, using the step's own timeout (or the default).\n case 'waitForVisible': {\n if (targetLocator) {\n await targetLocator.waitFor({\n state: 'visible',\n timeout: budget.limit(stepTimeoutParam(step, this.options.stepTimeoutMs)),\n });\n }\n break;\n }\n case 'waitForHidden': {\n if (targetLocator) {\n await targetLocator.waitFor({\n state: 'hidden',\n timeout: budget.limit(stepTimeoutParam(step, this.options.stepTimeoutMs)),\n });\n }\n break;\n }\n case 'waitForUrl': {\n // The URL to wait for, from params or the step text.\n const urlParam = stringParam(step, 'url') || textValue;\n if (urlParam) {\n const needle = interpolator.interpolateStrict(\n rewriteToBase(urlParam, bundle.base_url_override),\n );\n await page.waitForURL((current) => current.href.includes(needle), {\n timeout: budget.limit(stepTimeoutParam(step, this.options.stepTimeoutMs)),\n });\n }\n break;\n }\n // Text waits and all assertions share one path: build the assertion from\n // the step's settings, check it (retrying until its timeout), save the\n // result, and fail the step if it did not hold. An incomplete test is\n // reported as 'definition_incomplete', otherwise as an app failure.\n case 'waitForText':\n case 'assertVisible':\n case 'assertHidden':\n case 'assertText':\n case 'assertValue':\n case 'assertUrl':\n case 'assertRequest':\n case 'assertNoConsoleErrors': {\n // How long this check may keep retrying.\n const checkTimeout = budget.limit(\n stepTimeoutParam(step, this.options.stepTimeoutMs),\n );\n const outcome = await this.evaluateAssertion(\n page,\n targetLocator,\n stepCheckAssertion(\n step,\n stepId,\n action,\n checkTimeout,\n bundle.base_url_override,\n ),\n checkTimeout,\n interpolator,\n {\n responses: () => observedResponses,\n consoleErrors: () => [\n ...consoleEntries.filter((c) => c.level === 'error').map((c) => c.text),\n ...pageErrors,\n ],\n },\n );\n (action === 'waitForText' ? waits : assertions).push(outcome);\n if (!outcome.passed) {\n throw new StepFailure(\n this.authoringGaps.has(outcome) ? 'definition_incomplete' : 'app_regression',\n `${action} not met: expected ${outcome.expected}, got ${outcome.actual}`,\n );\n }\n break;\n }\n default:\n // An action the runner does not know must never pass as a no-op.\n throw new StepFailure(\n 'definition_incomplete',\n `unknown action ${JSON.stringify(action)}: the runner cannot replay it`,\n );\n }\n } catch (err: unknown) {\n // A click can close the popup it was made in (a login window closing itself). That is a\n // normal result, not a failure, so it is allowed for mouse steps on a later page.\n const closedItself =\n POINTER_ACTIONS.has(action) &&\n actionPage.isClosed() &&\n pages.indexOf(actionPage) > 0;\n if (!closedItself) {\n throw err;\n }\n page = openPageBefore(pages, actionPage);\n await page.bringToFront();\n }\n // A click that closed its own popup succeeds: carry on with the nearest open earlier page.\n if (page.isClosed() && pages.indexOf(page) > 0) {\n page = openPageBefore(pages, page);\n await page.bringToFront();\n }\n // After the action, wait for the page to go quiet so the next step sees\n // the updated page. Check-style actions skip this wait.\n timer.enter('settle_ms');\n if (!CONDITION_ACTIONS.has(action)) {\n await settlerOf(page).settle();\n }\n timer.enter('conditions_ms');\n\n // 5. Post-condition waits, then assertions, each retried within its own timeout\n for (const wait of step.waits ?? []) {\n // This wait's time limit, capped by what is left of the run.\n const waitTimeoutMs = budget.limit(wait.timeout_ms);\n const outcome = await this.evaluateWait(\n page,\n targetLocator,\n wait,\n waitTimeoutMs,\n interpolator,\n );\n waits.push(outcome);\n if (!outcome.passed) {\n stepStatus = 'failed';\n stepError = `Wait ${wait.kind} not met within ${waitTimeoutMs}ms: expected ${outcome.expected}, observed ${outcome.actual}`;\n failureClass = this.authoringGaps.has(outcome)\n ? 'definition_incomplete'\n : 'app_regression';\n break;\n }\n }\n // Assertions only run if every wait passed. Console and request\n // assertions look only at what this attempt caused.\n if (stepStatus === 'passed') {\n for (const ass of step.assertions ?? []) {\n const outcome = await this.evaluateAssertion(\n page,\n targetLocator,\n ass,\n budget.limit(ass.timeout_ms),\n interpolator,\n {\n responses: () => observedResponses.slice(stepResponsesBefore),\n consoleErrors: () => [\n ...consoleEntries\n .slice(attemptConsoleBefore)\n .filter((c) => c.level === 'error')\n .map((c) => c.text),\n ...pageErrors.slice(attemptErrorsBefore),\n ],\n },\n );\n assertions.push(outcome);\n if (!outcome.passed) {\n stepStatus = 'failed';\n stepError = `Assertion ${outcome.kind} failed: expected ${outcome.expected}, got ${outcome.actual}`;\n failureClass = this.authoringGaps.has(outcome)\n ? 'definition_incomplete'\n : 'app_regression';\n break;\n }\n }\n }\n\n // Evaluate extract_variables rules\n if (\n stepStatus === 'passed' &&\n Array.isArray(step.extract_variables) &&\n step.extract_variables.length > 0\n ) {\n // Responses seen during this step.\n const stepResponses = observedResponses.slice(stepResponsesBefore);\n // The responses extract rules may read.\n const candidateResponses =\n stepResponses.length > 0 ? stepResponses : observedResponses;\n\n for (const rule of step.extract_variables) {\n const value = await readExtractedValue(rule, candidateResponses);\n if (value !== undefined) {\n extractedVariables[rule.variable_name] = value;\n interpolator.setVariable(rule.variable_name, value);\n if (rule.export === true) {\n exportCollector.add(rule.variable_name, 'extracted', value);\n }\n }\n }\n }\n // Any error from the attempt ends up here. The step is marked failed, a\n // note about the element's state (hidden, disabled...) is added, and the\n // error is classified so the report says who is to blame.\n } catch (err: unknown) {\n stepStatus = 'failed';\n // A short note on why the element could not be used (hidden, disabled).\n const elementState = targetLocator\n ? await this.describeElementState(targetLocator)\n : '';\n failureClass = refineHiddenFailure(\n classifyError(err, elementState),\n elementState,\n action,\n );\n stepError = `${err instanceof Error ? err.message : String(err)}${elementState}${\n failureClass === 'target_hidden' ? TARGET_HIDDEN_HINT : ''\n }`;\n }\n // A step can fail after its request was answered (a later check fails), and the record\n // it created still exists. Values the test marked \"Export this value\" are kept in that\n // case. This writes to the export collector only: it does not fill extracted_variables\n // or the interpolator, so a failed step hands nothing to later steps or a pipeline.\n if (stepStatus !== 'passed' && Array.isArray(step.extract_variables)) {\n // Responses this attempt saw, or every response when the step saw none of its own.\n const attemptResponses = observedResponses.slice(stepResponsesBefore);\n const exportCandidates =\n attemptResponses.length > 0 ? attemptResponses : observedResponses;\n for (const rule of step.extract_variables) {\n if (rule.export !== true) {\n continue;\n }\n const value = await readExtractedValue(rule, exportCandidates);\n if (value !== undefined) {\n exportCollector.add(rule.variable_name, 'extracted', value);\n }\n }\n }\n // Book the time of this attempt. A passing attempt stops the retry loop.\n timer.flush();\n if (stepStatus === 'passed') {\n break;\n }\n }\n if (stepStatus !== 'passed' && attempt > 1) {\n stepError = `${stepError} (failed after ${attempt} attempts)`;\n }\n if (stepStatus !== 'passed') {\n // A login hint if the failure looks like a missing or expired session.\n const hint = authHint(\n page.url(),\n definition.start_url,\n failedRequests.slice(authEvidenceFrom),\n );\n if (hint !== '') {\n stepError = `${stepError}${hint}`;\n failureClass = 'precondition_auth';\n }\n }\n\n // Remove this step's override routes so later steps are not affected, and\n // build the step's evidence (only what happened during this step).\n for (const { matches, handler } of stepRoutes) {\n await page.unroute(matches, handler);\n }\n authEvidenceFrom = failedRequests.length;\n // How long the step took in total.\n const stepDuration = Date.now() - stepStartTime;\n // Console messages, page errors and failed requests from this step only.\n const stepDiagnostics: StepDiagnostics = {\n console: consoleEntries.slice(stepConsoleBefore),\n page_errors: pageErrors.slice(stepErrorsBefore),\n failed_requests: failedRequests.slice(stepFailedReqsBefore),\n };\n\n // Take the failure screenshot (once) and list the artifacts to report.\n if (stepStatus !== 'passed') {\n await captureFailureScreenshot(targetLocator);\n }\n // Files uploaded for this run that the report points to.\n const resultArtifacts: Array<{ kind: 'screenshot' | 'trace'; object_key: string }> = [];\n if (bundle.artifact_upload_urls.trace) {\n resultArtifacts.push({ kind: 'trace', object_key: `runs/${bundle.run_id}/trace.zip` });\n }\n if (screenshotUploaded) {\n resultArtifacts.push({\n kind: 'screenshot',\n object_key: `runs/${bundle.run_id}/screenshot.png`,\n });\n }\n\n // Record this step's result.\n stepsResult.push({\n step_id: stepId,\n status: stepStatus,\n duration_ms: stepDuration,\n timings: timer.timings,\n resolution,\n waits,\n assertions,\n overrides,\n diagnostics: stepDiagnostics,\n error: stepError,\n failure_class: failureClass,\n ...(fileSources ? { file_sources: fileSources } : {}),\n ...(fileFixtures ? { file_fixtures: fileFixtures } : {}),\n artifacts: resultArtifacts,\n });\n\n if (stepStatus !== 'passed') {\n overallStatus = 'failed';\n // skip: record the failure and carry on. stop and pause end the run (a headless replay\n // has nobody to resume a paused step).\n if (step.failure_policy === 'skip' && !runExpired) {\n continue;\n }\n // Mark remaining steps as skipped\n for (let rem = i + 1; rem < rawSteps.length; rem++) {\n const nextStep = rawSteps[rem]!;\n const nextId =\n nextStep.step_id || nextStep.id || `step-${String(rem + 1).padStart(8, '0')}`;\n stepsResult.push({\n step_id: nextId,\n status: 'skipped',\n duration_ms: 0,\n timings: { resolve_ms: 0, action_ms: 0, settle_ms: 0, conditions_ms: 0 },\n resolution: null,\n waits: [],\n assertions: [],\n overrides: [],\n diagnostics: { console: [], page_errors: [], failed_requests: [] },\n error: null,\n failure_class: null,\n artifacts: [],\n });\n }\n break;\n }\n }\n\n // Capture storage state if auth prerequisite\n if (bundle.is_auth_prerequisite && context && overallStatus === 'passed') {\n try {\n capturedStorageState = (await context.storageState()) as Record<string, unknown>;\n } catch {\n // ignore capture error\n }\n }\n // A problem outside any step (bad bundle, browser failed to start, start\n // URL unreachable) blocks the whole run. If no step has been recorded\n // yet, add one so the report still shows the reason.\n } catch (err: unknown) {\n overallStatus = 'blocked';\n await captureFailureScreenshot(null);\n if (stepsResult.length === 0) {\n stepsResult.push({\n step_id: 'step-00000001',\n status: 'blocked',\n duration_ms: 0,\n timings: { resolve_ms: 0, action_ms: 0, settle_ms: 0, conditions_ms: 0 },\n resolution: null,\n waits: [],\n assertions: [],\n overrides: [],\n diagnostics: { console: [], page_errors: [], failed_requests: [] },\n error: err instanceof Error ? err.message : String(err),\n failure_class: classifyError(err, ''),\n artifacts: screenshotUploaded\n ? [{ kind: 'screenshot', object_key: `runs/${bundle.run_id}/screenshot.png` }]\n : [],\n });\n }\n // Always clean up, even after errors: save and upload the trace, close the\n // browser and delete the temporary folder. Failures here are ignored\n // because they must not change the test result.\n } finally {\n if (context) {\n try {\n await context.tracing.stop({ path: tracePath });\n if (fs.existsSync(tracePath) && bundle.artifact_upload_urls.trace && !cancel?.aborted) {\n // Playwright writes typed values into the trace in plain text, so every secret\n // value is masked first. If masking fails the trace is NOT uploaded.\n let masked = true;\n try {\n maskSecretsInTrace(tracePath, Object.values(bundle.secrets ?? {}));\n } catch (maskErr) {\n masked = false;\n this.options.log?.warn('trace not uploaded: masking secrets failed', {\n error: maskErr instanceof Error ? maskErr.message : String(maskErr),\n });\n }\n if (masked) {\n const traceBytes = fs.readFileSync(tracePath);\n await fetch(bundle.artifact_upload_urls.trace, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/zip' },\n body: traceBytes,\n });\n }\n }\n } catch {\n // ignore trace save error\n }\n }\n if (browser) {\n try {\n await browser.close();\n } catch {\n // ignore browser close error\n }\n }\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch {\n // ignore cleanup error\n }\n }\n\n // When the run finished (ISO time).\n const finishedAt = new Date().toISOString();\n return {\n schema_version: '1',\n run_id: bundle.run_id,\n test_case_id: bundle.test_case_id,\n def_version: bundle.def_version,\n status: overallStatus,\n // The engine that actually ran. If no browser started, the name the run asked for (a\n // bundle with no valid name was already refused above; 'chromium' only fills the field).\n browser: ranBrowser ?? (isBrowserName(bundle.browser) ? bundle.browser : 'chromium'),\n started_at: startedAt,\n finished_at: finishedAt,\n steps: stepsResult,\n ...(capturedStorageState ? { storage_state: capturedStorageState } : {}),\n ...(Object.keys(extractedVariables).length > 0\n ? { extracted_variables: extractedVariables }\n : {}),\n ...(Object.keys(generatedValues.used()).length > 0\n ? { generated_values: generatedValues.used() }\n : {}),\n ...(Object.keys(interpolator.savedValues()).length > 0\n ? { saved_values: interpolator.savedValues() }\n : {}),\n // Always present, empty when nothing was exported.\n ...exportCollector.outcome(),\n };\n }\n\n /**\n * Turns a wait/assertion kind (visible, hidden, text, URL, dialog...)\n * into something we can check: a `probe` function that reads the page and\n * says pass/fail, or a reason it cannot be checked (no target element, no\n * expected value written by the author).\n * The small helpers inside (needsTarget, needsExpected...) each build one\n * shape of probe so the big switch at the end stays short.\n */\n private prepareCondition(\n page: Page,\n target: Locator | null,\n ownTarget: RawCheckTarget | null | undefined,\n kind: string,\n expected: ExpectedValue | null,\n attributeName: string | null,\n ): PreparedCondition {\n // The last locator error, so 'element not found' can say why.\n let selectorError = '';\n // Finds the element the check reads: the one it names itself (first\n // locator that matches) or else the step's own target. Null if neither.\n const resolveElement: (() => Promise<Locator | null>) | null = ownTarget\n ? async () => {\n for (const ref of ownTarget.locators) {\n try {\n const candidate = page.locator(ref.expression);\n if ((await candidate.count()) > 0) {\n return candidate.first();\n }\n } catch (err: unknown) {\n selectorError = errorLine(err);\n }\n }\n return null;\n }\n : target === null\n ? null\n : () => Promise.resolve(target);\n // Text used when the element is missing.\n const noElement = (): string =>\n selectorError === '' ? 'element not found' : `element not found (${selectorError})`;\n // For checks that need an element. `absentPasses` is for 'hidden'\n // checks, where a missing element counts as success.\n const needsTarget = (\n expectedText: string,\n probe: (el: Locator) => Promise<ConditionProbe>,\n absentPasses = false,\n ): PreparedCondition =>\n resolveElement === null\n ? { expected: expectedText, unavailable: 'step has no resolved target element' }\n : {\n expected: expectedText,\n probe: async () => {\n const el = await resolveElement();\n if (el === null) {\n return { passed: absentPasses, actual: absentPasses ? 'hidden' : noElement() };\n }\n return probe(el);\n },\n };\n // For checks that compare page-level text/URL against the author's\n // expected rule.\n const needsExpected = (\n read: () => Promise<string>,\n against: ExpectedValue | null = expected,\n ): PreparedCondition => {\n if (against === null) {\n return { expected: 'an expected value', unavailable: 'no expected value authored' };\n }\n return {\n expected: describeExpected(against),\n probe: async () => {\n const actual = await read();\n return { passed: matchesExpected(actual, against), actual };\n },\n };\n };\n // For checks that compare an element's text/value against the rule.\n const needsElementExpected = (\n subject: string,\n read: (el: Locator) => Promise<string>,\n ): PreparedCondition => {\n if (expected === null) {\n return { expected: 'an expected value', unavailable: 'no expected value authored' };\n }\n return needsTarget(describeExpected(expected), async (el) => {\n const actual = await read(el);\n return { passed: matchesExpected(actual, expected), actual };\n });\n };\n\n switch (kind) {\n case 'waitForVisible':\n case 'assertVisible':\n return needsTarget('visible', async (el) => {\n const visible = await el.isVisible();\n return { passed: visible, actual: visible ? 'visible' : 'hidden' };\n });\n case 'waitForHidden':\n case 'assertHidden':\n return needsTarget(\n 'hidden',\n async (el) => {\n const hidden = await el.isHidden();\n return { passed: hidden, actual: hidden ? 'hidden' : 'visible' };\n },\n true,\n );\n case 'waitForEnabled':\n case 'waitForDisabled': {\n // True for waitForEnabled, false for waitForDisabled.\n const wantEnabled = kind === 'waitForEnabled';\n return needsTarget(wantEnabled ? 'enabled' : 'disabled', async (el) => {\n const enabled = await el.isEnabled({ timeout: 100 });\n return { passed: enabled === wantEnabled, actual: enabled ? 'enabled' : 'disabled' };\n });\n }\n case 'waitForText':\n case 'assertText':\n return needsElementExpected('element text', async (el) => (await el.textContent()) ?? '');\n case 'waitForPageText':\n case 'assertPageText': {\n // Rendered text of the whole page, whitespace collapsed on both sides so\n // a toast's \"text \u00D7\" matches however the page breaks its lines.\n const collapsed: ExpectedValue | null =\n expected === null || expected.match === 'regex'\n ? expected\n : { ...expected, value: collapseWhitespace(expected.value) };\n return needsExpected(\n async () => collapseWhitespace(await page.locator('body').innerText({ timeout: 100 })),\n collapsed,\n );\n }\n case 'assertValue':\n return needsElementExpected('element value', (el) => el.inputValue({ timeout: 100 }));\n case 'waitForUrl':\n case 'assertUrl':\n return needsExpected(() => Promise.resolve(page.url()));\n case 'assertTitle':\n // The browser tab title, read fresh on every poll because single-page\n // apps often change it a moment after the click.\n return needsExpected(() => page.title());\n case 'assertChecked':\n case 'assertUnchecked': {\n // True for assertChecked, false for assertUnchecked.\n const wantChecked = kind === 'assertChecked';\n return needsTarget(wantChecked ? 'checked' : 'unchecked', async (el) => {\n let checked: boolean;\n try {\n checked = await el.isChecked({ timeout: 100 });\n } catch (err: unknown) {\n // The browser only answers \"checked?\" for checkboxes, radios and\n // aria-checked controls. Anything else is a wrong target, which no\n // amount of waiting fixes, so say so at once.\n const line = errorLine(err);\n if (/not a checkbox/i.test(line)) {\n return {\n passed: false,\n authoringGap: true,\n actual: 'element is not a checkbox, radio button or aria-checked control',\n };\n }\n throw err;\n }\n return { passed: checked === wantChecked, actual: checked ? 'checked' : 'unchecked' };\n });\n }\n case 'assertAttribute': {\n // Without a name there is nothing to read; the test is unfinished.\n if (attributeName === null || attributeName === '') {\n return { expected: 'an attribute name', unavailable: 'no attribute name authored' };\n }\n const name = attributeName;\n if (expected === null) {\n return { expected: 'an expected value', unavailable: 'no expected value authored' };\n }\n return needsTarget(`attribute ${name} ${describeExpected(expected)}`, async (el) => {\n // The attribute as written in the page's HTML (not the live property).\n // null means it is not there at all, which is different from \"\".\n const actual = await el.getAttribute(name, { timeout: 100 });\n if (actual === null) {\n return { passed: false, actual: `attribute ${name} is not set` };\n }\n return {\n passed: matchesExpected(actual, expected),\n actual: actual === '' ? `attribute ${name} is empty` : actual,\n };\n });\n }\n case 'waitForDialogOpen':\n case 'waitForDialogClosed': {\n // True for 'dialog open', false for 'dialog closed'.\n const wantOpen = kind === 'waitForDialogOpen';\n return {\n expected: wantOpen ? 'a dialog open' : 'no dialog open',\n probe: async () => {\n const open = await page.locator(OPEN_DIALOG_SELECTOR).count();\n return { passed: wantOpen ? open > 0 : open === 0, actual: `${open} dialog(s) open` };\n },\n };\n }\n case 'waitForLoadingGone':\n return {\n expected: 'no loading indicator',\n probe: async () => {\n const busy = await page.locator(LOADING_INDICATOR_SELECTOR).count();\n return { passed: busy === 0, actual: `${busy} loading indicator(s) visible` };\n },\n };\n default:\n return { expected: kind, unavailable: `unsupported condition kind ${kind}` };\n }\n }\n\n /**\n * Checks a prepared condition by polling it until it passes or the time\n * runs out, and returns the result as a run outcome. A condition that\n * cannot be evaluated fails right away and is marked as a test-authoring\n * problem.\n */\n private async runCondition(\n page: Page,\n id: string,\n kind: string,\n timeoutMs: number,\n condition: PreparedCondition,\n ): Promise<Outcome> {\n if ('unavailable' in condition) {\n return this.authoringGap({\n id,\n kind,\n passed: false,\n expected: condition.expected,\n actual: condition.unavailable,\n });\n }\n // The last observation from the polling.\n const result = await pollCondition(page, timeoutMs, condition.probe);\n const outcome = {\n id,\n kind,\n passed: result.passed,\n expected: condition.expected,\n actual: result.actual,\n };\n // A probe can say the test itself is wrong; keep that apart from app failures.\n return result.authoringGap === true ? this.authoringGap(outcome) : outcome;\n }\n\n /**\n * Notes that this outcome failed because the test is incomplete (not\n * because the app is wrong), and returns it unchanged.\n */\n private authoringGap(outcome: Outcome): Outcome {\n this.authoringGaps.add(outcome);\n return outcome;\n }\n\n /**\n * Checks a step's wait condition. Fills in placeholders in the expected\n * text, prepares the condition, then polls it.\n */\n private async evaluateWait(\n page: Page,\n target: Locator | null,\n wait: RawWait,\n timeoutMs: number,\n interpolator: VariableInterpolator,\n ): Promise<Outcome> {\n const expected = wait.expected\n ? {\n match: wait.expected.match,\n value: interpolator.interpolateExpected(\n wait.expected.value,\n wait.expected.expand_values,\n wait.expected.match,\n ),\n expand_values: wait.expected.expand_values,\n }\n : null;\n const condition = this.prepareCondition(page, target, wait.target, wait.kind, expected, null);\n return this.runCondition(page, wait.wait_id, wait.kind, timeoutMs, condition);\n }\n\n /**\n * Checks one assertion, retrying until it holds or its timeout passes.\n * Request assertions and 'no console errors' have their own paths; every\n * other kind goes through prepareCondition.\n */\n private async evaluateAssertion(\n page: Page,\n target: Locator | null,\n ass: RawAssertion,\n timeoutMs: number,\n interpolator: VariableInterpolator,\n evidence: StepEvidence,\n ): Promise<Outcome> {\n // The assertion's id, or a time-based one if missing.\n const id = ass.assertion_id || `ass-${Date.now()}`;\n // The assertion kind; defaults to 'assertVisible'.\n const kind = ass.kind || 'assertVisible';\n const expected = ass.expected\n ? {\n match: ass.expected.match,\n value: interpolator.interpolateExpected(\n ass.expected.value,\n ass.expected.expand_values,\n ass.expected.match,\n ),\n expand_values: ass.expected.expand_values,\n }\n : null;\n if (kind === 'assertRequest') {\n return this.evaluateRequestAssertion(\n page,\n id,\n ass,\n timeoutMs,\n expected,\n interpolator,\n evidence,\n );\n }\n if (kind === 'assertNoConsoleErrors') {\n // Console and page errors seen so far.\n const errors = evidence.consoleErrors();\n return {\n id,\n kind,\n passed: errors.length === 0,\n expected: 'no console errors',\n actual:\n errors.length === 0\n ? 'no console errors'\n : `${errors.length} console error(s), first: ${errors[0]!.slice(0, 200)}`,\n };\n }\n if (kind === 'assertCount') {\n return this.runCondition(\n page,\n id,\n kind,\n timeoutMs,\n this.prepareCountCondition(page, ass.target, ass.count_check),\n );\n }\n const condition = this.prepareCondition(\n page,\n target,\n ass.target,\n kind,\n expected,\n ass.attribute_name ?? null,\n );\n return this.runCondition(page, id, kind, timeoutMs, condition);\n }\n\n /**\n * Builds the check for `assertCount`: how many elements the author's\n * selector matches right now, compared with the rule they wrote.\n * It has its own path (not `prepareCondition`) because every other\n * element check wants exactly one element and calls \"none found\" a\n * failure, while for a count zero is a perfectly good answer.\n * Only the first locator is used: several locators on a normal target\n * are fallbacks for one element, and mixing them would add up counts\n * of different things. A selector the browser cannot parse is reported\n * as a test-authoring problem straight away.\n */\n private prepareCountCondition(\n page: Page,\n ownTarget: RawCheckTarget | null | undefined,\n rule: RawCountCheck | null | undefined,\n ): PreparedCondition {\n const expression = ownTarget?.locators[0]?.expression;\n if (expression === undefined || expression === '') {\n return { expected: 'a selector to count', unavailable: 'no selector authored' };\n }\n if (rule === null || rule === undefined) {\n return { expected: 'a count rule', unavailable: 'no count rule authored' };\n }\n return {\n expected: describeCount(rule),\n probe: async () => {\n let found: number;\n try {\n found = await page.locator(expression).count();\n } catch (err: unknown) {\n const line = errorLine(err);\n if (isTransientPageError(line)) {\n throw err;\n }\n return { passed: false, authoringGap: true, actual: `invalid selector: ${line}` };\n }\n return {\n passed: countHolds(rule, found),\n actual: `${found} ${found === 1 ? 'match' : 'matches'}`,\n };\n },\n };\n }\n\n /**\n * Checks that the page made a matching network request and that its\n * answer is acceptable. Steps: find responses that match the method and\n * URL pattern; keep those in the allowed status range (default 200-299);\n * then check the response body text and any field checks. Reports a clear\n * reason for the first problem: no request, wrong status, body mismatch\n * or a failed field check.\n */\n private async evaluateRequestAssertion(\n page: Page,\n id: string,\n ass: RawAssertion,\n timeoutMs: number,\n expected: ExpectedValue | null,\n interpolator: VariableInterpolator,\n evidence: StepEvidence,\n ): Promise<Outcome> {\n const kind = 'assertRequest';\n if (!ass.request_match?.method || !ass.request_match.url_pattern) {\n return this.authoringGap({\n id,\n kind,\n passed: false,\n expected: 'a request match',\n actual: 'no request_match authored',\n });\n }\n const method = ass.request_match.method.toUpperCase();\n // The URL part to look for (placeholders filled in).\n const pattern = interpolator.interpolateStrict(ass.request_match.url_pattern);\n // Lowest accepted HTTP status (default 200).\n const minStatus = typeof ass.status_range?.min === 'number' ? ass.status_range.min : 200;\n // Highest accepted HTTP status (default 299).\n const maxStatus = typeof ass.status_range?.max === 'number' ? ass.status_range.max : 299;\n // True if a response is for the wanted method and URL.\n const isMatch = (r: ObservedResponse) =>\n (method === 'ANY' || r.method.toUpperCase() === method) &&\n (pattern === '*' || r.url.includes(pattern.startsWith('**/') ? pattern.slice(3) : pattern));\n\n // The field checks with their expected values filled in.\n const checks: RawBodyCheck[] = (ass.body_checks ?? []).map((c) =>\n c.match === 'exact' || c.match === 'contains' || c.match === 'regex'\n ? {\n ...c,\n value: interpolator.interpolateExpected(c.value ?? '', c.expand_values, c.match),\n }\n : c,\n );\n // True if a response status is in the allowed range.\n const inRange = (r: ObservedResponse) => r.status >= minStatus && r.status <= maxStatus;\n // True if the response body meets the expected text rule and every\n // field check. A response satisfies the assertion only if its body does.\n const satisfiesBody = async (r: ObservedResponse): Promise<boolean> => {\n const text = await r.bodyPromise;\n try {\n if (expected !== null && !matchesExpected(text, expected)) {\n return false;\n }\n } catch {\n return false;\n }\n return bodyChecksFailure({ response: text, request: r.requestBody }, checks) === null;\n };\n\n // The response we judge. With field checks an endpoint called more than\n // once may answer differently each time, so the assertion holds when\n // any matching in-range response satisfies it; failures report the\n // first in-range response (else the first match).\n let matched: ObservedResponse | undefined;\n await pollCondition(page, timeoutMs, async () => {\n const candidates = evidence.responses().filter(isMatch);\n if (checks.length === 0) {\n matched = candidates[0];\n return { passed: matched !== undefined, actual: null };\n }\n let satisfying: ObservedResponse | undefined;\n for (const candidate of candidates.filter(inRange)) {\n if (await satisfiesBody(candidate)) {\n satisfying = candidate;\n break;\n }\n }\n matched = satisfying ?? candidates.find(inRange) ?? candidates[0];\n return { passed: satisfying !== undefined, actual: null };\n });\n if (matched === undefined) {\n // All responses seen, listed in the error when none matched.\n const seen = evidence.responses();\n return {\n id,\n kind,\n passed: false,\n expected: `${method} ${pattern} (${minStatus}-${maxStatus})`,\n actual:\n seen.length > 0\n ? `Observed ${seen.length} other requests (${seen.map((r) => `${r.method} ${r.url}`).join(', ')})`\n : 'No network requests observed',\n };\n }\n if (matched.status < minStatus || matched.status > maxStatus) {\n return {\n id,\n kind,\n passed: false,\n expected: `HTTP status ${minStatus}-${maxStatus}`,\n actual: `HTTP status ${matched.status}`,\n };\n }\n if (expected === null && checks.length === 0) {\n return {\n id,\n kind,\n passed: true,\n expected: `HTTP ${minStatus}-${maxStatus}`,\n actual: `HTTP ${matched.status}`,\n };\n }\n const bodyText = await matched.bodyPromise;\n if (expected !== null) {\n // Whether the body matches the expected text rule.\n let bodyMatched: boolean;\n try {\n bodyMatched = matchesExpected(bodyText, expected);\n } catch (err: unknown) {\n return {\n id,\n kind,\n passed: false,\n expected: `Response body ${describeExpected(expected)}`,\n actual: `error: ${errorLine(err)}`,\n };\n }\n if (!bodyMatched) {\n return {\n id,\n kind,\n passed: false,\n expected: `Response body ${describeExpected(expected)}`,\n actual: `Response body (${bodyText.slice(0, 100)}) did not match`,\n };\n }\n }\n // The first failed field check, or null.\n const fieldFailure = bodyChecksFailure(\n { response: bodyText, request: matched.requestBody },\n checks,\n );\n if (fieldFailure !== null) {\n return {\n id,\n kind,\n passed: false,\n expected: `${checks.length} field ${checks.length === 1 ? 'check' : 'checks'}`,\n actual: fieldFailure,\n };\n }\n return {\n id,\n kind,\n passed: true,\n expected:\n checks.length > 0\n ? `${checks.length} field ${checks.length === 1 ? 'check' : 'checks'}`\n : `Response body ${describeExpected(expected as ExpectedValue)}`,\n actual: checks.length > 0 ? 'All field checks passed' : 'Response body matched',\n };\n }\n\n /**\n * Waits until the dropdown offers every wanted option, then returns the\n * values to select. Dropdowns are often filled by a network call, so we\n * keep checking until the timeout. On timeout it fails with the list of\n * options that are available.\n */\n private async waitForOptions(\n page: Page,\n select: Locator,\n wanted: OptionChoice[],\n timeoutMs: number,\n ): Promise<string[]> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n // The options the dropdown offers right now (value and label).\n const available = await select.evaluate((el) => {\n const opts = (el as unknown as { options?: ArrayLike<{ value: string; label: string }> })\n .options;\n return opts ? Array.from(opts, (o) => ({ value: o.value, label: o.label })) : [];\n });\n // The wanted options matched against the available ones.\n const resolved = resolveOptionChoices(wanted, available);\n if (resolved.missing === null) {\n return resolved.values;\n }\n if (Date.now() > deadline) {\n throw new StepFailure('app_regression', resolved.missing);\n }\n await page.waitForTimeout(100);\n }\n }\n\n /**\n * Explains why a found element could not be used: it is hidden or\n * disabled. Adds a short note to the error message. If the element cannot\n * be checked (for example the page closed) it says so instead.\n */\n private async describeElementState(target: Locator): Promise<string> {\n try {\n if (!(await target.isVisible())) {\n return ' [element state: hidden]';\n }\n if (!(await target.isEnabled({ timeout: 1000 }))) {\n return ' [element state: disabled]';\n }\n return '';\n } catch (err: unknown) {\n // First line of the probing error.\n const reason = (err instanceof Error ? err.message : String(err)).split('\\n')[0] ?? '';\n return ` [element state unavailable: ${reason}]`;\n }\n }\n}\n", "import fs from 'node:fs';\nimport { chromium, firefox } from 'playwright';\nimport type { Browser } from 'playwright';\n\n/**\n * What it is: the list of browsers a run may ask for, as plain words.\n * What it does: gives the rest of the runner one fixed set of allowed names.\n * How: a read-only list. The same two words appear in the run result contract, the\n * environment setting and the run drawer, so a typo anywhere is refused.\n */\nexport const BROWSER_NAMES = ['chromium', 'firefox'] as const;\n\n/**\n * What it is: one allowed browser name ('chromium' or 'firefox').\n * What it does: the type of the `browser` field on a run bundle and a run result.\n * How: taken from BROWSER_NAMES so the list and the type cannot drift apart.\n */\nexport type BrowserName = (typeof BROWSER_NAMES)[number];\n\n/**\n * What it is: true when a piece of text is one of the allowed browser names.\n * What it does: lets the runner check a name that came from outside (a bundle or a\n * setting) before using it.\n * How: looks the text up in BROWSER_NAMES.\n */\nexport function isBrowserName(value: unknown): value is BrowserName {\n return typeof value === 'string' && (BROWSER_NAMES as readonly string[]).includes(value);\n}\n\n/**\n * What it is: the settings that decide how each browser is started.\n * What it does: holds, per browser, the program path (empty means \"use the copy\n * Playwright installed\") and the sandbox choice, plus which browsers this runner may\n * run at all.\n * How: filled from the runner's .env file by config.ts. Nothing here is a default:\n * every value is read from configuration, and no path is written in code.\n */\nexport interface BrowserSettings {\n chromiumPath: string;\n chromiumSandbox: boolean;\n firefoxPath: string;\n firefoxSandbox: boolean;\n enabledBrowsers: readonly BrowserName[];\n}\n\n/**\n * What it is: the error raised when a run asks for a browser this runner cannot start.\n * What it does: carries the browser's name so the run result can say which one failed.\n * How: thrown by launchBrowser; the executor turns it into a runner_error step failure.\n */\nexport class BrowserUnavailableError extends Error {\n constructor(\n readonly browser: string,\n detail: string,\n ) {\n super(`BROWSER_UNAVAILABLE: ${browser}: ${detail}`);\n this.name = 'BrowserUnavailableError';\n }\n}\n\n/**\n * What it is: the name of the environment variable that switches Firefox's sandbox off.\n * What it does: lets the runner remove it when the sandbox must be on.\n * Why: a stray copy of this variable in a container image would silently turn the\n * sandbox off even when the runner asked for it on.\n */\nconst FIREFOX_SANDBOX_KILL_SWITCH = 'MOZ_DISABLE_CONTENT_SANDBOX';\n\n/**\n * What it is: Firefox's own sandbox strength setting for web pages.\n * What it does: 4 is Firefox's normal strong setting; 0 is off.\n * Why: set explicitly in both directions so the runner's .env decides, not whatever\n * the Firefox build or a profile file happens to say.\n */\nconst FIREFOX_SANDBOX_ON_LEVEL = 4;\nconst FIREFOX_SANDBOX_OFF_LEVEL = 0;\n\n/**\n * What it is: the display variables that are kept away from both browsers.\n * Why: headless Chromium (159, Playwright 1.65) waits on a display that is advertised but does\n * not answer, as WSLg's sometimes does: it stops painting frames, so every click waits forever\n * for the element to be \"stable\". Firefox does not hang but starts about six times slower.\n * A headless runner never needs a display, so neither browser ever sees these two.\n */\nconst HIDDEN_DISPLAY_KEYS = ['DISPLAY', 'WAYLAND_DISPLAY'];\n\n/**\n * What it is: the environment Chromium is started with.\n * What it does: copies the runner's environment without the display variables.\n * How: builds a new object, so the runner's own environment is never changed and the\n * services around it (which do not read these variables) are unaffected.\n */\nexport function chromiumEnvironment(): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined || HIDDEN_DISPLAY_KEYS.includes(key)) {\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n\n/**\n * What it is: the environment Firefox is started with.\n * What it does: copies the runner's environment without the display variables; when the\n * sandbox is on it also removes the variable that would switch the sandbox off.\n * How: builds a new object so the runner's own environment is never changed.\n */\nexport function firefoxEnvironment(sandbox: boolean): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) {\n continue;\n }\n if (HIDDEN_DISPLAY_KEYS.includes(key) || (sandbox && key === FIREFOX_SANDBOX_KILL_SWITCH)) {\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n\n/**\n * What it is: the preferences Firefox is started with for the sandbox choice.\n * What it does: returns the one preference that sets the web-page sandbox level.\n * How: level 4 when the sandbox is on, level 0 when it was switched off on purpose.\n */\nexport function firefoxSandboxPrefs(sandbox: boolean): Record<string, number> {\n return {\n 'security.sandbox.content.level': sandbox\n ? FIREFOX_SANDBOX_ON_LEVEL\n : FIREFOX_SANDBOX_OFF_LEVEL,\n };\n}\n\n/**\n * What it is: the one place where a browser program is started.\n * What it does: checks the named browser is allowed on this runner, then starts it with\n * only the options that engine understands (Chromium gets its sandbox flag and shared\n * memory flag; Firefox gets its sandbox preference and cleaned environment).\n * How: a switch on the name. A browser that is not enabled, or that fails to start,\n * raises BrowserUnavailableError; there is never a quiet fall back to another browser.\n */\nexport async function launchBrowser(\n name: BrowserName,\n settings: BrowserSettings,\n): Promise<Browser> {\n if (!settings.enabledBrowsers.includes(name)) {\n throw new BrowserUnavailableError(name, 'not enabled on this runner');\n }\n try {\n if (name === 'firefox') {\n return await firefox.launch({\n headless: true,\n ...(settings.firefoxPath.trim() !== '' ? { executablePath: settings.firefoxPath } : {}),\n firefoxUserPrefs: firefoxSandboxPrefs(settings.firefoxSandbox),\n env: firefoxEnvironment(settings.firefoxSandbox),\n });\n }\n return await chromium.launch({\n headless: true,\n chromiumSandbox: settings.chromiumSandbox,\n args: ['--disable-dev-shm-usage'],\n env: chromiumEnvironment(),\n ...(settings.chromiumPath.trim() !== '' ? { executablePath: settings.chromiumPath } : {}),\n });\n } catch (error) {\n throw new BrowserUnavailableError(\n name,\n error instanceof Error ? (error.message.split('\\n')[0] ?? error.message) : String(error),\n );\n }\n}\n\n/**\n * What it is: a reader for the \"Seccomp\" line of a process status file.\n * What it does: returns 2 when the process has a syscall filter installed (that is how\n * a sandboxed Firefox web-content process looks), 0 or 1 otherwise, or null when the\n * line is missing.\n * How: finds the line starting with \"Seccomp:\" in the text of /proc/<pid>/status.\n */\nexport function parseSeccompMode(statusText: string): number | null {\n const match = /^Seccomp:\\s+(\\d+)\\s*$/m.exec(statusText);\n const digits = match?.[1];\n return digits === undefined ? null : Number.parseInt(digits, 10);\n}\n\n/**\n * What it is: a test for \"is this process one of Firefox's web-page processes\".\n * What it does: true for a command line that starts a content process of type \"tab\".\n * How: Firefox starts those with \"-contentproc ... tab\" as the last word. The words in\n * /proc/<pid>/cmdline are separated by NUL bytes when the process was started directly,\n * and by spaces when Firefox forked it from its \"fork server\" (Firefox 159, shipped with\n * Playwright 1.65, does this). Both are split, because reading only the NUL form found no\n * web-page process at all on the newer Firefox and the start-up sandbox check then refused\n * to start the runner.\n */\nexport function isFirefoxContentProcess(cmdline: string): boolean {\n const words = cmdline.split(/[\\0\\s]+/).filter((word) => word !== '');\n return words.includes('-contentproc') && words[words.length - 1] === 'tab';\n}\n\n/**\n * What it is: the list of process ids on this machine that are Firefox web-page processes.\n * What it does: scans /proc and keeps the ids whose command line says content process.\n * How: reads each numeric folder's cmdline file; a process that disappears while being\n * read is simply skipped (that is normal, not an error).\n */\nexport function listFirefoxContentProcesses(): number[] {\n const found: number[] = [];\n for (const entry of fs.readdirSync('/proc')) {\n if (!/^\\d+$/.test(entry)) {\n continue;\n }\n let cmdline: string;\n try {\n cmdline = fs.readFileSync(`/proc/${entry}/cmdline`, 'utf8');\n } catch {\n // The process ended between listing and reading; skip it.\n continue;\n }\n if (isFirefoxContentProcess(cmdline)) {\n found.push(Number.parseInt(entry, 10));\n }\n }\n return found;\n}\n\n/**\n * What it is: a reader for the sandbox state of one process.\n * What it does: returns that process's Seccomp mode, or null when it cannot be read.\n * How: reads /proc/<pid>/status and parses it.\n */\nexport function readSeccompMode(pid: number): number | null {\n try {\n return parseSeccompMode(fs.readFileSync(`/proc/${pid}/status`, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * What it is: how many times the start-up sandbox check reads the web-page processes.\n * What it does: with SANDBOX_CHECK_INTERVAL_MS it sets the longest wait (20 x 250 ms,\n * about 5 seconds) before a process without a syscall filter counts as a failure.\n * How: a plain number used by the loop in assertFirefoxSandboxed. Too small and a busy\n * machine causes false alarms; the wait only ends early when every process is sandboxed.\n */\nconst SANDBOX_CHECK_ATTEMPTS = 20;\n\n/**\n * What it is: the pause, in milliseconds, between two reads of the sandbox state.\n * What it does: spaces out the retries of the start-up sandbox check.\n * How: awaited with setTimeout between loop rounds in assertFirefoxSandboxed.\n */\nconst SANDBOX_CHECK_INTERVAL_MS = 250;\n\n/**\n * What it is: the start-up safety check for Firefox's sandbox.\n * What it does: when LOCUS_RUNNER_FIREFOX_SANDBOX is true, starts Firefox once with the\n * real settings, opens a page, and reads the state of the new web-page processes. If\n * none are found, or any one has no syscall filter, it throws so the runner refuses to\n * start (by design: fail closed).\n * How: remembers the web-page processes that existed before, launches Firefox through\n * launchBrowser, and looks at the ones that appeared. Only Linux exposes /proc, so on\n * another system a true setting is refused with a clear message. When the setting is\n * false nothing is checked here (the choice was made on purpose and is logged by the\n * caller). Run it before the runner accepts work, so no other Firefox is starting.\n */\nexport async function assertFirefoxSandboxed(settings: BrowserSettings): Promise<void> {\n if (!settings.enabledBrowsers.includes('firefox') || !settings.firefoxSandbox) {\n return;\n }\n if (process.platform !== 'linux') {\n throw new BrowserUnavailableError(\n 'firefox',\n 'LOCUS_RUNNER_FIREFOX_SANDBOX=true cannot be verified on this operating system (needs /proc)',\n );\n }\n const before = new Set(listFirefoxContentProcesses());\n const browser = await launchBrowser('firefox', settings);\n try {\n const page = await browser.newPage();\n await page.goto('about:blank');\n // Give Firefox a moment to finish starting its web-page process.\n await page.evaluate(() => 1);\n // A web-page process can exist a little before its syscall filter is installed, and\n // a busy machine stretches that gap. So read the state again every\n // SANDBOX_CHECK_INTERVAL_MS until every new process shows the filter, and give up\n // (fail closed) only when SANDBOX_CHECK_ATTEMPTS reads in a row did not get there.\n let fresh: number[] = [];\n let unsandboxed: number[] = [];\n for (let attempt = 0; attempt < SANDBOX_CHECK_ATTEMPTS; attempt += 1) {\n fresh = listFirefoxContentProcesses().filter((pid) => !before.has(pid));\n unsandboxed = fresh.filter((pid) => readSeccompMode(pid) !== 2);\n if (fresh.length > 0 && unsandboxed.length === 0) {\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, SANDBOX_CHECK_INTERVAL_MS));\n }\n if (fresh.length === 0) {\n throw new BrowserUnavailableError(\n 'firefox',\n 'sandbox check found no web-page process to inspect',\n );\n }\n if (unsandboxed.length > 0) {\n throw new BrowserUnavailableError(\n 'firefox',\n `sandbox is set to true but web-page processes ${unsandboxed.join(',')} have no syscall filter`,\n );\n }\n } finally {\n await browser.close();\n }\n}\n", "import type { BundleRow } from './dashboard-client.js';\n\n/**\n * RowValues is the data-driven row of one run, ready to be looked up by column name.\n *\n * What it is: a small read-only table built once at the start of a run from the bundle's\n * `row` and `secrets`.\n * What it does: answers \"what is the value of column X for this run's row?\" for both\n * places that need it: the {{name}} interpolator and the fill step whose value source is\n * \"variable\". It also says which columns are secret columns.\n * How: text columns come straight from `row.values`. A secret column holds the NAME of a\n * vault secret in `row.secret_columns`; the value itself is read from `bundle.secrets`\n * under that name. Because that value lives in `bundle.secrets`, the existing masking\n * (screen, trace, field hiding) already covers it with no new code. A cell value is only\n * ever returned as text; nothing here expands `{{...}}` inside it.\n */\nexport class RowValues {\n /**\n * Text column values by column name. Empty when the run has no row.\n */\n private readonly text: Map<string, string>;\n /**\n * Resolved secret column values by column name. Empty when the run has no row.\n * These are real secret values: never log them or put them in a step result.\n */\n private readonly secret: Map<string, string>;\n\n /**\n * Builds the table from the claimed row and the bundle's secrets.\n * A run without a row (`null` or missing) gives an empty table. A secret column whose\n * vault name is not in `secrets` fails the run start with an error that names the\n * column and the secret name (never a value), because typing an empty string into a\n * login field would hide the real cause.\n */\n constructor(row: BundleRow | null | undefined, secrets: Record<string, string>) {\n this.text = new Map<string, string>();\n this.secret = new Map<string, string>();\n if (row === null || row === undefined) {\n return;\n }\n for (const [column, value] of Object.entries(row.values ?? {})) {\n this.text.set(column, value);\n }\n for (const [column, secretName] of Object.entries(row.secret_columns ?? {})) {\n if (!Object.prototype.hasOwnProperty.call(secrets, secretName)) {\n throw new Error(\n `row secret column \"${column}\" needs secret \"${secretName}\", which the claim did not deliver`,\n );\n }\n this.secret.set(column, secrets[secretName] as string);\n }\n }\n\n /**\n * Returns the value of a column, or undefined when the row has no such column.\n * Secret columns are checked first, then text columns.\n */\n valueFor(column: string): string | undefined {\n const secretValue = this.secret.get(column);\n if (secretValue !== undefined) {\n return secretValue;\n }\n return this.text.get(column);\n }\n\n /**\n * Tells whether a column is a secret column of this run's row.\n * Used to refuse secret columns in a check's expected text and in `save_as`.\n */\n isSecretColumn(column: string): boolean {\n return this.secret.has(column);\n }\n\n /**\n * Returns every column value as a plain object, text columns first, then secret columns,\n * ready to be spread into the interpolator's token table. Built through a Map so a\n * strange column name cannot touch the object prototype.\n */\n asTokens(): Record<string, string> {\n return Object.fromEntries([...this.text, ...this.secret]);\n }\n}\n", "/**\n * The file a replay uploads when an upload step has no fixture picked.\n * A placeholder keeps the recorded name and type, so the page sees the kind of file it\n * expects. It never has the recorded size, because the real bytes were never captured.\n */\nexport interface PlaceholderFile {\n name: string;\n mimeType: string;\n buffer: Buffer;\n}\n\n/**\n * A table of tiny, valid files by content type (a 1x1 image, a one page PDF, a few text\n * lines). A page that decodes or checks the file then still accepts it. Stored as base64\n * or plain text so the file bytes are easy to read and review.\n */\nconst KNOWN_BODIES: Record<string, Buffer> = {\n 'image/png': Buffer.from(\n 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',\n 'base64',\n ),\n 'image/jpeg': Buffer.from(\n '/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=',\n 'base64',\n ),\n 'image/gif': Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'),\n 'application/pdf': Buffer.from(\n '%PDF-1.1\\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\\n' +\n '2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\\n' +\n '3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 72 72]>>endobj\\n' +\n 'trailer<</Root 1 0 R>>\\n%%EOF\\n',\n 'latin1',\n ),\n 'text/plain': Buffer.from('Locus placeholder file\\n', 'utf8'),\n 'text/csv': Buffer.from('column\\nvalue\\n', 'utf8'),\n 'application/json': Buffer.from('{\"placeholder\":true}\\n', 'utf8'),\n};\n\n/**\n * Size, in bytes, of the filler used for any content type that has no table entry.\n */\nconst FILLER_BYTES = 1024;\n\n/**\n * Builds the placeholder for one recorded file.\n * It keeps the recorded name and type, and takes the bytes from the table above for a known\n * type, or 1 KB of zero bytes for any other type. It hands back a copy so a caller can never\n * change the shared table.\n */\nexport function placeholderFile(name: string, mimeType: string): PlaceholderFile {\n const known = KNOWN_BODIES[mimeType];\n return {\n name,\n mimeType,\n buffer: known ? Buffer.from(known) : Buffer.alloc(FILLER_BYTES),\n };\n}\n", "import type { Locator } from 'playwright';\n\n/**\n * One locator that matched exactly one element, kept so its element can be\n * compared with the winner's element.\n */\nexport interface UniqueLocator {\n strategy: string;\n expression: string;\n locator: Locator;\n}\n\n/**\n * One disagreement: a locator whose single element is not the winner's\n * element and not an ancestor or descendant of it.\n */\nexport interface LocatorConflict {\n strategy: string;\n /** Short readable name of the element this locator found. */\n found: string;\n}\n\n/**\n * How long to wait for an element handle. The element was counted a moment\n * ago, so this only covers it vanishing; a short wait keeps the step fast.\n */\nconst HANDLE_TIMEOUT_MS = 500;\n\n/**\n * The few properties of a page node that the two browser-side functions\n * below read. The project compiles without browser typings, so this small\n * shape stands in for `Element`.\n */\ninterface PageNode {\n parentNode: PageNode | null;\n host?: PageNode;\n id: string;\n tagName: string;\n textContent: string | null;\n}\n\n/**\n * Browser-side test: are two elements the same, or is one inside the other?\n * It climbs from each element through its parents (and through shadow roots\n * to their host) looking for the other. This is why an id on a button and\n * text on the span inside it count as agreeing. Playwright sends this\n * function's source to the page, so it must not use anything outside it.\n */\nfunction relatedInPage(a: PageNode, b: PageNode): boolean {\n const inside = (node: PageNode, wanted: PageNode): boolean => {\n for (let c: PageNode | undefined | null = node; c; c = c.parentNode || c.host) {\n if (c === wanted) return true;\n }\n return false;\n };\n return inside(a, b) || inside(b, a);\n}\n\n/**\n * Browser-side short name for an element, such as `button#save \"Save\"`:\n * tag, id, and the first 30 characters of its text. Only used in messages.\n * Like the function above, it is sent to the page as source text.\n */\nfunction nameInPage(el: PageNode): string {\n const text = (el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 30);\n return el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (text ? ' \"' + text + '\"' : '');\n}\n\n/**\n * Compares the winning locator's element with the element of every other\n * locator that also matched exactly one element, and reports the ones that\n * point somewhere unrelated.\n *\n * How: for each other locator it takes element handles for both and asks the\n * page whether they are the same or nested. Only locators that already\n * matched one element are passed in, so zero matches, errors and ambiguous\n * results never get here. If a handle cannot be taken (the element changed\n * or vanished) that locator is skipped, because \"could not compare\" is not\n * proof of a conflict. Cost is bounded: one handle and one tiny page call\n * per extra locator, and no polling.\n */\nexport async function findLocatorConflicts(\n winner: Locator,\n others: UniqueLocator[],\n): Promise<LocatorConflict[]> {\n if (others.length === 0) return [];\n // The winner's element, or null when it can no longer be taken.\n const winnerHandle = await winner.elementHandle({ timeout: HANDLE_TIMEOUT_MS }).catch(() => null);\n if (winnerHandle === null) return [];\n // Locators whose element is unrelated to the winner's.\n const conflicts: LocatorConflict[] = [];\n try {\n for (const other of others) {\n // The other locator's element, or null when it can no longer be taken.\n const handle = await other.locator\n .elementHandle({ timeout: HANDLE_TIMEOUT_MS })\n .catch(() => null);\n if (handle === null) continue;\n try {\n // True when the two elements are the same or nested.\n const related = await winnerHandle.evaluate(relatedInPage, handle).catch(() => true);\n if (!related) {\n // The readable name of the unrelated element.\n const found = await handle.evaluate(nameInPage).catch(() => 'an element');\n conflicts.push({ strategy: other.strategy, found });\n }\n } finally {\n await handle.dispose();\n }\n }\n } finally {\n await winnerHandle.dispose();\n }\n return conflicts;\n}\n\n/**\n * The most elements of one ambiguous locator that are compared with the winner.\n * A locator that matches more than this is too broad to say anything about the\n * winner, and the cap keeps the check cheap.\n */\nconst AMBIGUOUS_COMPARE_LIMIT = 25;\n\n/**\n * Reports the locators that matched several elements, none of which is the winner's element.\n *\n * What it is: the second half of the agreement check. A locator that matches several elements\n * is not a winner, but it still says \"the target is one of these\". If the winner is not among\n * them (and not nested with any of them), that locator points somewhere else, which is the\n * same kind of disagreement as two unique locators finding different elements.\n *\n * How: for each such locator it takes up to AMBIGUOUS_COMPARE_LIMIT element handles and asks the\n * page whether any is the same as, or nested with, the winner's element. A locator with more\n * matches than the limit, or one whose handles cannot be taken, is skipped, because \"could not\n * compare\" is not proof of a conflict. It never fails the step by itself.\n */\nexport async function findAmbiguousConflicts(\n winner: Locator,\n ambiguous: UniqueLocator[],\n): Promise<LocatorConflict[]> {\n if (ambiguous.length === 0) return [];\n // The winner's element, or null when it can no longer be taken.\n const winnerHandle = await winner.elementHandle({ timeout: HANDLE_TIMEOUT_MS }).catch(() => null);\n if (winnerHandle === null) return [];\n // Locators whose several elements all sit away from the winner's.\n const conflicts: LocatorConflict[] = [];\n try {\n for (const other of ambiguous) {\n // Every element this locator matched, or null when they cannot be taken.\n const handles = await other.locator.elementHandles().catch(() => null);\n if (handles === null || handles.length > AMBIGUOUS_COMPARE_LIMIT) {\n await Promise.all((handles ?? []).map((h) => h.dispose()));\n continue;\n }\n try {\n // True when at least one of the elements is the winner or nested with it.\n let includesWinner = false;\n for (const handle of handles) {\n if (await winnerHandle.evaluate(relatedInPage, handle).catch(() => true)) {\n includesWinner = true;\n break;\n }\n }\n if (!includesWinner) {\n conflicts.push({\n strategy: other.strategy,\n found: `${handles.length} other elements and not this one`,\n });\n }\n } finally {\n await Promise.all(handles.map((h) => h.dispose()));\n }\n }\n } finally {\n await winnerHandle.dispose();\n }\n return conflicts;\n}\n\n/**\n * Names the winner's element for the message, with the same short format\n * used for the conflicting ones. Falls back to \"an element\" if the page\n * cannot be asked.\n */\nexport async function nameElement(locator: Locator): Promise<string> {\n // The element, or null when it can no longer be taken.\n const handle = await locator.elementHandle({ timeout: HANDLE_TIMEOUT_MS }).catch(() => null);\n if (handle === null) return 'an element';\n try {\n return await handle.evaluate(nameInPage).catch(() => 'an element');\n } finally {\n await handle.dispose();\n }\n}\n", "import { lookup } from 'node:dns/promises';\n\n/**\n * Finds every IP address a host name points to. The guard takes this as an\n * input so tests can pass a fake and never touch the network.\n */\nexport type HostResolver = (hostname: string) => Promise<string[]>;\n\n/**\n * The real resolver: asks the operating system for all A and AAAA records\n * of a name (the same resolver family Chromium's own lookups use) and\n * returns just the address text.\n */\nexport const systemResolver: HostResolver = async (hostname: string): Promise<string[]> => {\n // Every address record the system returned for the name.\n const records = await lookup(hostname, { all: true });\n return records.map((r) => r.address);\n};\n\n/**\n * The answer for one host: `allowed` (every address is fine), `private`\n * (the name or at least one address is a place the runner must not visit),\n * or `unresolved` (the lookup failed or returned nothing).\n */\nexport type HostVerdict = 'allowed' | 'private' | 'unresolved';\n\n/**\n * Inputs for `HostGuard`. `isBlockedText` is the existing rule that judges\n * a host or IP as text (`isPrivateOrBlockedHost`); it is passed in so the\n * IP rules live in one place only.\n */\nexport interface HostGuardConfig {\n resolve: HostResolver;\n isBlockedText: (host: string) => boolean;\n /** Most host names remembered for the run; the oldest is dropped past it. */\n maxEntries: number;\n}\n\n/**\n * Checks that a host name does not point at a private address.\n *\n * What it does: judges the name as text first, then (for names that are\n * not IP literals) resolves it and judges EVERY returned address with the\n * same text rule, blocking if any one is private. The verdict is\n * remembered per name for the life of the guard (one run), in a bounded\n * list, so a page with hundreds of requests to one host does one lookup.\n *\n * Fail-closed choice: if the lookup fails, the verdict is `unresolved` and\n * the caller must refuse the request. Allowing it would let an attacker\n * make a lookup fail here and succeed later in the browser. Failures are\n * not remembered, so a one-off glitch does not block the host all run.\n *\n * Honest limit: Chromium resolves the name again by itself after this\n * check. A name that gives a public answer here and a private one a moment\n * later (DNS rebinding) is NOT stopped by this class; that needs egress\n * control at the network level.\n */\nexport class HostGuard {\n // Looks up the addresses of a name (real or fake).\n private readonly resolve: HostResolver;\n // The text rule for a host or IP.\n private readonly isBlockedText: (host: string) => boolean;\n // Size limit of the memory below.\n private readonly maxEntries: number;\n // Verdicts (as pending or finished answers) by lower-case host name.\n // A Map keeps insertion order, which gives the \"drop oldest\" rule.\n private readonly verdicts = new Map<string, Promise<HostVerdict>>();\n\n /**\n * Builds the guard and checks its inputs, because there are no code\n * defaults for config (Mandate 1).\n */\n constructor(config: HostGuardConfig) {\n if (!Number.isInteger(config.maxEntries) || config.maxEntries < 1) {\n throw new Error('HostGuard maxEntries must be a positive integer');\n }\n this.resolve = config.resolve;\n this.isBlockedText = config.isBlockedText;\n this.maxEntries = config.maxEntries;\n }\n\n /**\n * Gives the verdict for a host name as `new URL(...).hostname` writes it.\n * It reuses a remembered or in-flight answer when there is one, so two\n * requests at once to one host share a single lookup.\n */\n check(hostname: string): Promise<HostVerdict> {\n // The cache key: lower case, no trailing dot.\n const key = hostname.toLowerCase().replace(/\\.$/, '');\n // An earlier answer for this name, if any.\n const known = this.verdicts.get(key);\n if (known !== undefined) return known;\n // The new answer, started now and stored right away.\n const pending = this.decide(hostname);\n this.verdicts.set(key, pending);\n if (this.verdicts.size > this.maxEntries) {\n // The oldest name in the memory.\n const oldest = this.verdicts.keys().next();\n if (!oldest.done) this.verdicts.delete(oldest.value);\n }\n // Do not keep failures, so the next request tries the lookup again.\n void pending.then((v) => {\n if (v === 'unresolved') this.verdicts.delete(key);\n });\n return pending;\n }\n\n /**\n * Works out the verdict without using the memory: text rule on the name,\n * skip the lookup for IP literals, then judge every resolved address.\n */\n private async decide(hostname: string): Promise<HostVerdict> {\n if (this.isBlockedText(hostname)) return 'private';\n // URLs such as data: and about:blank have no host, so there is nothing to look up.\n if (hostname === '') return 'allowed';\n // The name without IPv6 brackets or a trailing dot, to spot IP literals.\n const bare = hostname.replace(/^\\[|\\]$/g, '').replace(/\\.$/, '');\n if (isIpLiteral(bare)) return 'allowed';\n // The addresses the name points to.\n let addresses: string[];\n try {\n addresses = await this.resolve(bare);\n } catch {\n return 'unresolved';\n }\n if (addresses.length === 0) return 'unresolved';\n for (const address of addresses) {\n // The address without an IPv6 zone suffix such as `%eth0`.\n const clean = address.split('%')[0] ?? address;\n if (this.isBlockedText(clean)) return 'private';\n }\n return 'allowed';\n }\n}\n\n/**\n * Tells if a host text is already an IP address (dotted IPv4, or anything\n * with a colon, which only IPv6 can have in a host name). Such hosts need\n * no lookup because the text rule already judges them fully.\n */\nfunction isIpLiteral(host: string): boolean {\n return /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host) || host.includes(':');\n}\n", "import fs from 'node:fs';\nimport zlib from 'node:zlib';\n\n/**\n * TRACE_MASK is the fixed text that replaces every secret value found inside a trace.\n *\n * What it does: it is written over each secret (in every encoding we look for).\n * How: a plain constant, so tests and readers of a masked trace see the same marker.\n */\nexport const TRACE_MASK = '***';\n\n/**\n * MIN_SECRET_LENGTH is the shortest secret value we agree to mask.\n *\n * Why: replacing a 1 or 2 character value (for example \"1\" or \"ab\") would also\n * rewrite unrelated text all over the trace and make it unreadable. The risk\n * we accept: a secret shorter than 4 characters stays visible in the trace.\n */\nexport const MIN_SECRET_LENGTH = 4;\n\n/** One file inside the zip: its name and its unpacked bytes. */\ninterface ZipEntry {\n name: string;\n data: Buffer;\n}\n\n/**\n * secretForms turns the secret values into every spelling we look for.\n *\n * What it does: for each usable secret it returns the raw text, the JSON-escaped\n * text (how it appears inside trace.trace lines), the URL-encoded text (how it\n * appears in network URLs and form bodies) and the base64 text (how it appears\n * in basic-auth headers when the value is encoded on its own). Values shorter\n * than MIN_SECRET_LENGTH are skipped. The longest forms come first so a\n * longer secret that contains a shorter one is masked as a whole.\n * How: builds a set to drop duplicates, then sorts by length.\n */\nfunction secretForms(secrets: string[]): Buffer[] {\n const forms = new Set<string>();\n for (const value of secrets) {\n if (value.length < MIN_SECRET_LENGTH) {\n continue;\n }\n forms.add(value);\n forms.add(JSON.stringify(value).slice(1, -1));\n forms.add(encodeURIComponent(value));\n forms.add(Buffer.from(value, 'utf8').toString('base64'));\n }\n return [...forms]\n .filter((form) => form.length >= MIN_SECRET_LENGTH)\n .sort((a, b) => b.length - a.length)\n .map((form) => Buffer.from(form, 'utf8'));\n}\n\n/**\n * replaceBytes replaces every occurrence of `needle` in `data` with `mask`.\n *\n * What it does: returns a new buffer, or the same buffer when nothing matched.\n * How: works on raw bytes (not text) so images and other binary entries are\n * never damaged by a text conversion; a real match inside them is practically\n * impossible, and no match means the bytes stay exactly as they were.\n */\nfunction replaceBytes(data: Buffer, needle: Buffer, mask: Buffer): Buffer {\n let at = data.indexOf(needle);\n if (at < 0) {\n return data;\n }\n const parts: Buffer[] = [];\n let from = 0;\n while (at >= 0) {\n parts.push(data.subarray(from, at), mask);\n from = at + needle.length;\n at = data.indexOf(needle, from);\n }\n parts.push(data.subarray(from));\n return Buffer.concat(parts);\n}\n\n/**\n * readZip unpacks a zip file held in memory.\n *\n * What it does: returns every file entry (name and bytes); folder entries are\n * dropped. Supports stored and deflated entries, which is all Playwright writes.\n * How: finds the end-of-directory record at the back of the file, walks the\n * central directory, then reads each entry from its local header. Throws on\n * anything it does not understand (zip64, encryption), so the caller can fail closed.\n */\nexport function readZip(zip: Buffer): ZipEntry[] {\n let eocd = -1;\n for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 65535); i--) {\n if (zip.readUInt32LE(i) === 0x06054b50) {\n eocd = i;\n break;\n }\n }\n if (eocd < 0) {\n throw new Error('not a zip file: end record not found');\n }\n const count = zip.readUInt16LE(eocd + 10);\n let pos = zip.readUInt32LE(eocd + 16);\n if (count === 0xffff || pos === 0xffffffff) {\n throw new Error('zip64 archives are not supported');\n }\n const entries: ZipEntry[] = [];\n for (let n = 0; n < count; n++) {\n if (zip.readUInt32LE(pos) !== 0x02014b50) {\n throw new Error('bad zip central directory');\n }\n const flags = zip.readUInt16LE(pos + 8);\n const method = zip.readUInt16LE(pos + 10);\n const compressedSize = zip.readUInt32LE(pos + 20);\n const nameLen = zip.readUInt16LE(pos + 28);\n const extraLen = zip.readUInt16LE(pos + 30);\n const commentLen = zip.readUInt16LE(pos + 32);\n const localAt = zip.readUInt32LE(pos + 42);\n const name = zip.toString('utf8', pos + 46, pos + 46 + nameLen);\n pos += 46 + nameLen + extraLen + commentLen;\n if ((flags & 1) !== 0) {\n throw new Error('encrypted zip entries are not supported');\n }\n if (name.endsWith('/')) {\n continue;\n }\n if (zip.readUInt32LE(localAt) !== 0x04034b50) {\n throw new Error('bad zip local header');\n }\n const start = localAt + 30 + zip.readUInt16LE(localAt + 26) + zip.readUInt16LE(localAt + 28);\n const raw = zip.subarray(start, start + compressedSize);\n if (method === 0) {\n entries.push({ name, data: Buffer.from(raw) });\n } else if (method === 8) {\n entries.push({ name, data: zlib.inflateRawSync(raw) });\n } else {\n throw new Error(`unsupported zip compression method ${method}`);\n }\n }\n return entries;\n}\n\n/**\n * writeZip packs entries into a new zip held in memory.\n *\n * What it does: returns a valid zip with every entry deflated.\n * How: writes a local header and data per entry, then the central directory\n * and the end record. The checksum comes from zlib.crc32. No zip64: a trace\n * beyond 4 GB would throw on the size fields, and the caller then fails closed.\n */\nexport function writeZip(entries: ZipEntry[]): Buffer {\n const chunks: Buffer[] = [];\n const central: Buffer[] = [];\n let offset = 0;\n for (const entry of entries) {\n const name = Buffer.from(entry.name, 'utf8');\n const packed = zlib.deflateRawSync(entry.data);\n const crc = zlib.crc32(entry.data);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0);\n local.writeUInt16LE(20, 4);\n local.writeUInt16LE(0x0800, 6);\n local.writeUInt16LE(8, 8);\n local.writeUInt32LE(crc, 14);\n local.writeUInt32LE(packed.length, 18);\n local.writeUInt32LE(entry.data.length, 22);\n local.writeUInt16LE(name.length, 26);\n chunks.push(local, name, packed);\n const head = Buffer.alloc(46);\n head.writeUInt32LE(0x02014b50, 0);\n head.writeUInt16LE(20, 4);\n head.writeUInt16LE(20, 6);\n head.writeUInt16LE(0x0800, 8);\n head.writeUInt16LE(8, 10);\n head.writeUInt32LE(crc, 16);\n head.writeUInt32LE(packed.length, 20);\n head.writeUInt32LE(entry.data.length, 24);\n head.writeUInt16LE(name.length, 28);\n head.writeUInt32LE(offset, 42);\n central.push(head, name);\n offset += local.length + name.length + packed.length;\n }\n const centralBytes = Buffer.concat(central);\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0);\n end.writeUInt16LE(entries.length, 8);\n end.writeUInt16LE(entries.length, 10);\n end.writeUInt32LE(centralBytes.length, 12);\n end.writeUInt32LE(offset, 16);\n return Buffer.concat([...chunks, centralBytes, end]);\n}\n\n/**\n * maskSecretsInZip replaces secret values inside a zip held in memory.\n *\n * What it does: unpacks the zip, replaces every secret (plain, JSON-escaped,\n * URL-encoded and base64 forms) with TRACE_MASK in every entry, and packs it\n * again. Secrets shorter than MIN_SECRET_LENGTH are left alone.\n * How: byte-level search and replace per entry, then writeZip.\n *\n * Limits, said plainly: this does NOT make a trace safe on its own.\n * - Screenshots in the trace are images; a value typed into a plain-text field\n * is visible in them (a password field shows dots, a text field shows the text).\n * - Only the values passed in are masked. Other sensitive data (environment\n * variables that are not secrets, extracted values, page content) stays.\n * - A secret split across spellings we do not try (HTML entities) can survive.\n */\nexport function maskSecretsInZip(zip: Buffer, secrets: string[]): Buffer {\n const forms = secretForms(secrets);\n const mask = Buffer.from(TRACE_MASK, 'utf8');\n const entries = readZip(zip).map((entry) => ({\n name: entry.name,\n data: forms.reduce((data, form) => replaceBytes(data, form, mask), entry.data),\n }));\n return writeZip(entries);\n}\n\n/**\n * maskSecretsInTrace masks secrets in a trace.zip file on disk, in place.\n *\n * What it does: reads the file, masks it with maskSecretsInZip and writes it\n * back. When there are no usable secrets it still rewrites nothing.\n * How: if anything throws, the error goes to the caller untouched, and the\n * caller must not upload the file (fail closed).\n */\nexport function maskSecretsInTrace(tracePath: string, secrets: string[]): void {\n if (secretForms(secrets).length === 0) {\n return;\n }\n const masked = maskSecretsInZip(fs.readFileSync(tracePath), secrets);\n fs.writeFileSync(tracePath, masked);\n}\n", "import type { BrowserContext } from 'playwright';\n\n/**\n * PageSheet is the small part of a style sheet that the in-page code below uses.\n *\n * Why: the runner is compiled without the browser's type library, so the few things the code\n * running inside the page needs are declared here by hand (the same way secret-screen.ts does).\n */\ninterface PageSheet {\n insertRule(rule: string): number;\n}\n\n// The page's `document` and the style sheet maker, as seen by code that runs inside the page.\ndeclare const document: { adoptedStyleSheets: PageSheet[] };\ndeclare const CSSStyleSheet: new () => PageSheet;\n\n/**\n * hideSelectorsInPage is the code that runs inside every page and frame of a replay.\n *\n * What it does: builds one style sheet with a \"hide this\" rule for each selector the site owner\n * listed, and attaches it to the document.\n * How and why:\n * - `visibility: hidden` keeps the layout still, so clicks and waits behave as before, while\n * the area is blank in every screenshot and trace picture.\n * - Each rule is added on its own with insertRule, which accepts exactly one rule. A selector\n * that is broken, or that tries to smuggle in a second rule, throws and is skipped, so one bad\n * entry cannot stop the others or change any other style.\n * - A constructed style sheet is used (not a <style> tag) so a strict Content-Security-Policy\n * on the tested site cannot block it.\n */\nexport function hideSelectorsInPage(selectors: string[]): void {\n const sheet = new CSSStyleSheet();\n for (const selector of selectors) {\n try {\n sheet.insertRule(`${selector} { visibility: hidden !important; }`);\n } catch {\n // A selector the browser rejects is skipped on purpose; the others still apply.\n }\n }\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];\n}\n\n/**\n * installScreenshotHide makes every page of the replay hide the site's excluded areas.\n *\n * What it does: registers hideSelectorsInPage to run before any page script, in every frame,\n * when the list is not empty.\n * Why before page scripts: trace pictures are taken continuously and cannot be edited later, so\n * the area must already be hidden when the page first draws it.\n */\nexport async function installScreenshotHide(\n context: BrowserContext,\n selectors: string[],\n): Promise<void> {\n if (selectors.length === 0) return;\n await context.addInitScript(hideSelectorsInPage, selectors);\n}\n", "import type { Locator, Page } from 'playwright';\nimport { MIN_SECRET_LENGTH } from './trace-redaction.js';\n\n/**\n * StyledField is the small part of a page element that the in-page code below uses.\n *\n * Why: the runner is compiled without the browser's type library, so the few things the code\n * running inside the page needs are declared here by hand (the same way near-match.ts does).\n */\ninterface StyledField {\n value?: string;\n style: { setProperty(name: string, value: string, priority: string): void };\n}\n\n// The page's `document`, as seen by code that runs inside the page.\ndeclare const document: { querySelectorAll(selector: string): Iterable<StyledField> };\n\n/**\n * SCREEN_MASK_STYLE is the one style that turns a field's letters into dots.\n *\n * What it is: the browser's own `text-security` look, the same one a password field has.\n * Why this and not clearing the value: the field keeps its real value, so the page and the\n * rest of the run behave exactly as before; only what is drawn on the screen changes. Chrome,\n * Safari and Firefox engines all draw it (checked for Firefox 134 by comparing a masked field's\n * screenshot with a real password field's; a pixel test keeps that proven).\n */\nconst SCREEN_MASK_STYLE = '-webkit-text-security';\n\n/**\n * usableSecrets keeps the secret values that are long enough to look for.\n *\n * What it does: drops empty or very short values, the same ones the trace masking skips\n * (MIN_SECRET_LENGTH), because matching a 1 or 2 character value would hit unrelated text.\n * How: a plain filter on length.\n */\nexport function usableSecrets(secrets: string[]): string[] {\n return secrets.filter((value) => value.length >= MIN_SECRET_LENGTH);\n}\n\n/**\n * holdsSecret says whether some text contains any of the secret values.\n *\n * What it does: used before typing, to decide if the field about to be filled must be\n * hidden on screen. How: a substring check against each usable secret.\n */\nexport function holdsSecret(text: string, secrets: string[]): boolean {\n return usableSecrets(secrets).some((value) => text.includes(value));\n}\n\n/**\n * hideField draws one field's content as dots.\n *\n * What it does: sets the dot style on the field. It is called BEFORE a secret is typed, so the\n * screenshots the browser keeps in the trace never show the plain text, not even for a moment.\n * How: runs a tiny function inside the page on the located element.\n */\nexport async function hideField(field: Locator): Promise<void> {\n await field.evaluate((node, style) => {\n (node as StyledField).style.setProperty(style, 'disc', 'important');\n }, SCREEN_MASK_STYLE);\n}\n\n/**\n * hideSecretFields draws every field that currently holds a secret as dots, on the page and in\n * all its frames.\n *\n * What it does: finds inputs and text areas whose value contains a secret and hides them. It is\n * called just before the failure screenshot, so a secret that is on screen in a field (for\n * example after a \"show password\" toggle, or in a field this run did not type into) is not\n * saved into the picture.\n * How: runs one function in each frame that looks at every input and text area and sets the dot\n * style where the value matches. A frame that cannot be reached (it closed, or is cross-site and\n * blocked) is skipped; the other frames are still done.\n */\nexport async function hideSecretFields(page: Page, secrets: string[]): Promise<void> {\n const values = usableSecrets(secrets);\n if (values.length === 0) {\n return;\n }\n for (const frame of page.frames()) {\n try {\n await frame.evaluate(\n ({ list, style }) => {\n for (const field of document.querySelectorAll('input, textarea')) {\n const value = field.value ?? '';\n if (list.some((secret) => value.includes(secret))) {\n field.style.setProperty(style, 'disc', 'important');\n }\n }\n },\n { list: values, style: SCREEN_MASK_STYLE },\n );\n } catch {\n // This frame cannot be reached; the remaining frames are still hidden.\n }\n }\n}\n", "import { usableSecrets } from './secret-screen.js';\n\n/**\n * How much one run may export. The dashboard copies these two numbers from its config into\n * the bundle when the run is claimed; the runner never invents them.\n */\nexport interface ExportLimits {\n /** The most characters one exported value may have. */\n max_value_length: number;\n /** The most bytes all exported values of the run may take together. */\n max_total_bytes: number;\n}\n\n/** Where an exported value came from. */\nexport type ExportSource = 'extracted' | 'saved';\n\n/** Why a flagged value was kept back instead of exported. */\nexport type ExportWithheldReason = 'secret' | 'too_long' | 'too_large';\n\n/** One flagged value the runner kept back. The value itself is never listed. */\nexport interface ExportWithheld {\n name: string;\n source: ExportSource;\n reason: ExportWithheldReason;\n}\n\n/** What the collector hands to the run result. */\nexport interface ExportOutcome {\n exports: Record<string, string>;\n exports_withheld: ExportWithheld[];\n}\n\n/**\n * ExportCollector keeps the values a test marked \"Export this value\" and decides, in one place,\n * which of them may leave the run.\n *\n * What it is: a small object created once per run. The executor calls `add` each time a flagged\n * value is seen (a response value read by an extraction rule, or a name a fill step saved), and\n * calls `outcome` once at the end to fill the run result.\n * What it does: stores every flagged value by name. At the end it keeps a value only when it does\n * not contain a vault or row secret, is not longer than the per-value limit, and fits in the run's\n * total size budget. Anything else goes to the withheld list with its reason, without the value.\n * How it works: `add` only records (a later add of the same name replaces the earlier one, so the\n * last value wins, the same as a variable). `outcome` walks the records in the order the names\n * first appeared and applies the three checks. Keeping the decision in `outcome` means there is\n * exactly one place that can let a value out, which is what makes it safe to audit.\n * When no limits were sent (a dashboard older than this feature), nothing is let out: every value\n * is withheld as too_large rather than guessed at.\n */\nexport class ExportCollector {\n // Flagged values by name, in the order the names first appeared.\n private readonly entries = new Map<string, { source: ExportSource; value: string }>();\n\n /**\n * Creates the collector for one run.\n *\n * `limits` are the size limits from the bundle (undefined when the dashboard sent none).\n * `secretValues` are the run's secret values (vault secrets and row secret columns). Values too\n * short to look for are ignored, the same rule the trace masking uses.\n */\n constructor(\n private readonly limits: ExportLimits | undefined,\n private readonly secretValues: string[],\n ) {}\n\n /**\n * Records one flagged value. Nothing is checked yet; `outcome` decides later.\n */\n add(name: string, source: ExportSource, value: string): void {\n this.entries.set(name, { source, value });\n }\n\n /**\n * Returns the values that may leave the run and the ones kept back.\n *\n * What it does: applies the secret, length and total-size checks in that order, per value, in\n * the order the names first appeared. The total counts UTF-8 bytes of the values that were let\n * out, so a withheld value never uses up the budget.\n */\n outcome(): ExportOutcome {\n const exports: Record<string, string> = {};\n const withheld: ExportWithheld[] = [];\n const secrets = usableSecrets(this.secretValues);\n let usedBytes = 0;\n for (const [name, entry] of this.entries) {\n const reason = this.refusal(entry.value, secrets, usedBytes);\n if (reason !== undefined) {\n withheld.push({ name, source: entry.source, reason });\n continue;\n }\n exports[name] = entry.value;\n usedBytes += Buffer.byteLength(entry.value, 'utf8');\n }\n return { exports, exports_withheld: withheld };\n }\n\n /**\n * Says why a value may not leave, or undefined when it may.\n *\n * `usedBytes` is the size already let out. The order matters: a secret is reported as a secret\n * even when it is also too long, because that is the more serious reason.\n */\n private refusal(\n value: string,\n secrets: string[],\n usedBytes: number,\n ): ExportWithheldReason | undefined {\n if (secrets.some((secret) => value.includes(secret))) {\n return 'secret';\n }\n if (this.limits === undefined) {\n return 'too_large';\n }\n if (value.length > this.limits.max_value_length) {\n return 'too_long';\n }\n if (usedBytes + Buffer.byteLength(value, 'utf8') > this.limits.max_total_bytes) {\n return 'too_large';\n }\n return undefined;\n }\n}\n", "import { randomBytes, randomInt, randomUUID } from 'node:crypto';\n\n/**\n * The kinds of made-up test data a step can ask for: unique text,\n * unique email, unique number, a uuid, or a date in the future or past.\n */\nexport const GENERATED_KINDS = [\n 'unique_text',\n 'unique_email',\n 'unique_number',\n 'uuid',\n 'future_date',\n 'past_date',\n] as const;\n\n/**\n * One of the kinds above, as a type. Built from the list so the two\n * stay in step.\n */\nexport type GeneratedKind = (typeof GENERATED_KINDS)[number];\n\n/**\n * Milliseconds in one day, used for date maths.\n */\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/**\n * How far from today each date kind goes:\n * future_date is 7 days ahead and past_date is 30 days back.\n */\nconst DATE_OFFSET_DAYS: Record<'future_date' | 'past_date', number> = {\n future_date: 7,\n past_date: -30,\n};\n\n/**\n * The input types a date can be typed into. The dashboard checks the\n * same list when a test is saved, so a bad combination is caught early.\n */\nconst DATE_INPUT_TYPES = new Set(['date', 'datetime-local', 'text']);\n\n/**\n * Answers: is this value one of the known kinds?\n * Used to tell a real kind apart from any other text in [[double brackets]].\n */\nexport function isGeneratedKind(kind: unknown): kind is GeneratedKind {\n return typeof kind === 'string' && (GENERATED_KINDS as readonly string[]).includes(kind);\n}\n\n/**\n * Finds placeholders inside text.\n * `[[kind]]` is a placeholder for a generated value.\n * `\\\\[[` is an escape that means a literal '[[' (not a placeholder).\n * If a name looks like a kind but is not one, callers treat it as an error.\n */\nconst TOKEN_PATTERN = /\\\\\\[\\[|\\[\\[([A-Za-z][A-Za-z0-9_-]*)\\]\\]/g;\n\n/**\n * Lists the [[name]] placeholders found in a piece of text.\n * Returns the valid kinds (in order) and the names that are not valid\n * kinds, so the caller can reject typos.\n */\nexport function inlineTokens(text: string): { kinds: GeneratedKind[]; unknown: string[] } {\n // Valid kinds found, in the order they appear.\n const kinds: GeneratedKind[] = [];\n // Names that were written as placeholders but are not valid kinds.\n const unknown: string[] = [];\n for (const match of text.matchAll(TOKEN_PATTERN)) {\n const name = match[1];\n if (name === undefined) {\n continue;\n }\n if (isGeneratedKind(name)) {\n kinds.push(name);\n } else {\n unknown.push(name);\n }\n }\n return { kinds, unknown };\n}\n\n/**\n * The sources of time and randomness. They are passed in so tests can\n * use fixed values and get predictable results.\n */\nexport interface GeneratedValuesOptions {\n /** The run's clock; every date kind is computed from its UTC date. */\n now: () => Date;\n /** Lowercase hex of `bytes` random bytes. */\n hex: (bytes: number) => string;\n /** A random integer in [min, max). */\n integer: (min: number, max: number) => number;\n uuid: () => string;\n}\n\n/**\n * The real sources used in production: the system clock and Node's\n * secure random functions.\n */\nexport const systemGeneratedValues: GeneratedValuesOptions = {\n now: () => new Date(),\n hex: (bytes) => randomBytes(bytes).toString('hex'),\n integer: (min, max) => randomInt(min, max),\n uuid: () => randomUUID(),\n};\n\n/**\n * Creates the made-up values for one run.\n * A kind is created once and then reused. This matters when a form has\n * two fields that must match (email and confirm email) or when a step is\n * retried: they all get the same value.\n */\nexport class GeneratedValues {\n /**\n * The first value created for each kind (before any date formatting).\n */\n private readonly base = new Map<GeneratedKind, string>();\n /**\n * The value each kind gave the first time it was used. This is what we\n * report in the run result.\n */\n private readonly handedOut = new Map<GeneratedKind, string>();\n\n /**\n * Keeps the clock and random sources.\n */\n constructor(private readonly options: GeneratedValuesOptions) {}\n\n /**\n * Returns the value to type into a field.\n * `inputType` is the recorded type of the field (date, text...). It only\n * matters for date kinds, where it decides the format.\n */\n valueFor(kind: GeneratedKind, inputType: string | undefined): string {\n const value = this.shape(kind, this.baseFor(kind), inputType);\n if (!this.handedOut.has(kind)) {\n this.handedOut.set(kind, value);\n }\n return value;\n }\n\n /**\n * Replaces each [[kind]] in a piece of text with that kind's value.\n * In this case dates are always plain YYYY-MM-DD because the surrounding\n * text decides the format, not the field type.\n * Throws if a placeholder name is not a valid kind.\n */\n expand(text: string): string {\n const { unknown } = inlineTokens(text);\n if (unknown.length > 0) {\n throw new Error(`unknown generated value [[${unknown[0]}]]`);\n }\n return text.replace(TOKEN_PATTERN, (match: string, name: string | undefined) => {\n if (name === undefined || !isGeneratedKind(name)) {\n return '[[';\n }\n const value = this.baseFor(name);\n if (!this.handedOut.has(name)) {\n this.handedOut.set(name, value);\n }\n return value;\n });\n }\n\n /**\n * Returns every kind used so far with the first value it produced.\n * Included in the run result so a person can see what was typed.\n */\n used(): Record<string, string> {\n return Object.fromEntries(this.handedOut);\n }\n\n /**\n * Returns the stored value for a kind, creating and saving it the first\n * time it is needed.\n */\n private baseFor(kind: GeneratedKind): string {\n const cached = this.base.get(kind);\n if (cached !== undefined) {\n return cached;\n }\n const created = this.create(kind);\n this.base.set(kind, created);\n return created;\n }\n\n /**\n * Makes a brand new value for a kind, for example 'test-1a2b3c4d' for\n * unique text or 'qa+1a2b3c4d@example.com' for email. Dates are counted\n * from the run's clock in UTC.\n */\n private create(kind: GeneratedKind): string {\n switch (kind) {\n case 'unique_text':\n return `test-${this.options.hex(4)}`;\n case 'unique_email':\n return `qa+${this.options.hex(4)}@example.com`;\n case 'unique_number':\n return String(this.options.integer(100_000_000, 1_000_000_000));\n case 'uuid':\n return this.options.uuid();\n case 'future_date':\n case 'past_date': {\n // Today's date moved forward or back by the kind's number of days.\n const moved = new Date(this.options.now().getTime() + DATE_OFFSET_DAYS[kind] * DAY_MS);\n return moved.toISOString().slice(0, 10);\n }\n }\n }\n\n /**\n * Gets a value ready for the target field. Most kinds are returned as\n * they are. Dates are checked against the allowed field types (throws\n * otherwise) and get a time added for datetime-local fields.\n */\n private shape(kind: GeneratedKind, base: string, inputType: string | undefined): string {\n if (kind !== 'future_date' && kind !== 'past_date') {\n return base;\n }\n if (inputType === undefined || !DATE_INPUT_TYPES.has(inputType)) {\n throw new Error(`${kind} cannot be filled into a ${inputType ?? 'unknown'} field`);\n }\n return inputType === 'datetime-local' ? `${base}T12:00` : base;\n }\n}\n", "import type { Locator } from 'playwright';\n\nimport type { StrategyFamily, Verification } from '@locus/locator-engine';\n\n/**\n * How long to wait for the found element's handle. The element was counted a moment ago, so this only\n * covers it vanishing; a short wait keeps the step fast.\n */\nconst HANDLE_TIMEOUT_MS = 500;\n\n/**\n * The few things the in-page function reads. The runner compiles without browser typings, so this small\n * shape stands in for the page's element and for the locator engine.\n */\ninterface PageEngine {\n strategyFamily(locator: { strategy: string; expression: string }): StrategyFamily;\n captureVerificationForReplay(\n el: unknown,\n tools: { scrub: (text: string) => string; isSecret: (el: PageField) => boolean },\n ): Verification;\n}\n\n/** The two properties of a form field the secret test reads. */\ninterface PageField {\n tagName: string;\n type?: string;\n}\n\n/**\n * What one look at the found element returns: its verification facts and the strategy family of each\n * locator asked about.\n */\nexport interface FoundInspection {\n found: Verification;\n /** Families in the same order as the locators passed in. */\n families: StrategyFamily[];\n}\n\n/**\n * Reads the found element's verification facts and names the strategy family of some locators, in one\n * trip to the page.\n *\n * What it does: runs the locator engine's own `captureVerificationForReplay` on the live element, so\n * replay reads identifiers and neighbours with exactly the rules the recorder used, and asks the same\n * engine for each locator's family so the runner holds no second copy of that rule.\n * How: loads the engine bundle once, in the element's own frame (so iframes work), then runs one small\n * function against the element. Page text is not scrubbed because a recorded value that the scrubber\n * would have changed was never stored. Password and hidden inputs count as secret, so their facts are\n * left out as at record time. Throws when the element vanished or its frame is gone; the caller treats\n * that as a failed step.\n */\nexport async function inspectFoundElement(\n locator: Locator,\n engineBundle: string,\n locators: ReadonlyArray<{ strategy: string; expression: string }>,\n): Promise<FoundInspection> {\n const element = await locator.elementHandle({ timeout: HANDLE_TIMEOUT_MS });\n if (element === null) throw new Error('the found element is gone, so it cannot be verified');\n const frame = await element.ownerFrame();\n if (frame === null) throw new Error('the found element has no frame, so it cannot be verified');\n const engine = await frame.evaluateHandle<PageEngine>(\n `(() => { ${engineBundle}\\n; return LocusEngine; })()`,\n );\n const inspection = await element.evaluate(\n (el, args) => ({\n found: args.loaded.captureVerificationForReplay(el, {\n scrub: (text) => text,\n isSecret: (field) =>\n field.tagName === 'INPUT' && (field.type === 'password' || field.type === 'hidden'),\n }),\n families: args.list.map((one) => args.loaded.strategyFamily(one)),\n }),\n {\n loaded: engine,\n list: locators.map((l) => ({ strategy: l.strategy, expression: l.expression })),\n },\n );\n await engine.dispose();\n await element.dispose();\n return inspection;\n}\n", "import type { StrategyFamily, Verification } from '@locus/locator-engine';\n\n/**\n * The comparison rules for target verification: before a step acts, did replay find the element that was\n * recorded? Everything here is a pure function with no page and no browser, so the rules can be tested\n * as a table. The executor only reads the live page and calls these.\n */\n\n/** A warning the check can attach to a passing step. Matches the run-result contract enum. */\nexport type TargetCheck =\n | 'unverified_target'\n | 'position_fallback_confirmed'\n | 'unverified_position'\n | 'semantic_fallback'\n | 'label_changed'\n | 'index_only';\n\n/** The result of a check: the step may go on (with warnings), or it must stop with a reason. */\nexport type TargetVerdict = { ok: true; checks: TargetCheck[] } | { ok: false; message: string };\n\n/** The re-record advice shown when a position-found target has nothing recorded to check it against. */\nconst RE_RECORD =\n 'This step was found by its position only and has no recorded details to check it against. Re-record it, or add a locator that does not depend on position.';\n\n/**\n * Says whether a locator ranked above the winner was ambiguous in a way that makes the winner untrusted.\n *\n * What it does: when a locator tried before the winner matched two or more elements, the winner was\n * only reached because a more trusted locator could not decide. That is accepted only when a second,\n * independent family also resolved exactly the winner's element.\n * How: counts the distinct strategy families among the winner and every other locator that matched\n * only the winner's element (the caller has already removed conflicting ones). Fewer than two families\n * means the winner stands alone and the step must fail as ambiguous.\n */\nexport function ambiguousBlocksWinner(input: {\n ambiguousAboveWinner: boolean;\n winnerFamily: StrategyFamily;\n agreeingFamilies: ReadonlyArray<StrategyFamily>;\n}): boolean {\n if (!input.ambiguousAboveWinner) return false;\n const families = new Set<StrategyFamily>([input.winnerFamily, ...input.agreeingFamilies]);\n return families.size < 2;\n}\n\n/**\n * Turns a word list into a sorted list without repeats.\n * What it does: lets two word lists be compared as sets, so order and repeated words do not matter.\n */\nfunction wordSet(words: ReadonlyArray<string>): string[] {\n return Array.from(new Set(words)).sort();\n}\n\n/**\n * Says whether two word lists hold exactly the same words.\n * What it does: compares them as sets (see wordSet), so \"basic plan\" and \"plan basic\" are equal.\n */\nfunction sameWords(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {\n const left = wordSet(a);\n const right = wordSet(b);\n return left.length === right.length && left.every((word, i) => word === right[i]);\n}\n\n/**\n * Writes a row's words for a failure message.\n * What it does: shows the words in quotes, or says there were no stable words, so the message reads\n * clearly when a row had only numbers.\n */\nfunction describeWords(words: ReadonlyArray<string>): string {\n return words.length === 0 ? 'no stable words' : `\"${words.join(' ')}\"`;\n}\n\n/** Identifier kinds a team renames without changing the element; the rest describe what kind of control it is. */\nconst RENAMEABLE_KINDS: ReadonlyArray<string> = [\n 'id',\n 'name',\n 'test_id',\n 'accessible_name',\n 'label_text',\n];\n\n/**\n * Checks the identity facts: do the strong recorded identifiers still describe the element found?\n *\n * What it does: a recorded identifier is strong when it was unique on the page at record time. If a\n * strong one now differs on the found element and none still agrees, it is a different element. If the\n * element's id agrees but its row now shares no stable word with the recorded row, the id was reused\n * for something else: that block is absolute and no setting can relax it. For an element found by\n * position, a renamed id or name is left to the neighbour check instead of blocking here.\n * Returns a failure message, or the warning to add on a pass (empty when all agree).\n */\nfunction checkIdentity(\n recorded: Verification,\n found: Verification,\n winnerFamily: StrategyFamily,\n): { ok: false; message: string } | { ok: true; checks: TargetCheck[] } {\n const strong = recorded.identifiers.filter((i) => i.unique_at_record);\n const agreeing = strong.filter((i) =>\n found.identifiers.some((f) => f.kind === i.kind && f.value === i.value),\n );\n const conflicting = strong.filter((i) => !agreeing.includes(i));\n // For an element found by position, a renamed id, name or label is not proof of another element: the\n // neighbour check that follows (same row, same place, same row words) decides. A changed type, role or\n // autocomplete means a different kind of control and always blocks.\n const renameable = conflicting.every((i) => RENAMEABLE_KINDS.includes(i.kind));\n if (\n conflicting.length > 0 &&\n agreeing.length === 0 &&\n !(winnerFamily === 'position' && renameable)\n ) {\n const first = conflicting[0]!;\n const now = found.identifiers.find((f) => f.kind === first.kind)?.value ?? null;\n return {\n ok: false,\n message: `The element found has ${first.kind} ${now === null ? 'missing' : `\"${now}\"`}, but the recording had ${first.kind} \"${first.value}\".`,\n };\n }\n const idAgrees = agreeing.some((i) => i.kind === 'id');\n const recordedText = recorded.neighbour?.row_text ?? null;\n if (idAgrees && recordedText !== null && recordedText.stable_words.length > 0) {\n const foundWords = found.neighbour?.row_text?.stable_words ?? [];\n const shared = recordedText.stable_words.filter((w) => foundWords.includes(w));\n if (shared.length === 0) {\n return {\n ok: false,\n message: `The id matches but the row is different: the recording had ${describeWords(recordedText.stable_words)}, the page now has ${describeWords(foundWords)}. The id looks reused for another item.`,\n };\n }\n if (!sameWords(recordedText.stable_words, foundWords))\n return { ok: true, checks: ['label_changed'] };\n }\n return { ok: true, checks: [] };\n}\n\n/**\n * Checks the neighbour signal for an element found by position: same row, same place in its container\n * and, when the row text is stable, the same words.\n *\n * What it does: compares the row index and the index in the container (a difference is a different\n * element) and then the row text. Stable text that differs is a different row; volatile text on either\n * side is never compared, only the position is, and that is reported as index_only.\n */\nfunction checkNeighbour(\n recorded: NonNullable<Verification['neighbour']>,\n found: Verification['neighbour'],\n): { ok: false; message: string } | { ok: true; checks: TargetCheck[] } {\n if (found === null) {\n return {\n ok: false,\n message: `The element found is not inside the ${recorded.container_kind} it was recorded in.`,\n };\n }\n if (found.container_kind !== recorded.container_kind) {\n return {\n ok: false,\n message: `The element found is in a ${found.container_kind}, but it was recorded in a ${recorded.container_kind}.`,\n };\n }\n if (found.row_index !== recorded.row_index) {\n return {\n ok: false,\n message: `The element found is in row ${(found.row_index ?? 0) + 1}, but it was recorded in row ${(recorded.row_index ?? 0) + 1}.`,\n };\n }\n if (found.index_in_container !== recorded.index_in_container) {\n return {\n ok: false,\n message: `The element found is number ${found.index_in_container + 1} in its ${found.container_kind}, but it was recorded as number ${recorded.index_in_container + 1}.`,\n };\n }\n const was = recorded.row_text;\n const now = found.row_text;\n if (was === null) return { ok: true, checks: ['unverified_position'] };\n if (was.volatile) return { ok: true, checks: ['index_only'] };\n if (was.stable_words.length === 0) return { ok: true, checks: ['unverified_position'] };\n const nowWords = now?.stable_words ?? [];\n if (!sameWords(was.stable_words, nowWords)) {\n return {\n ok: false,\n message: `The row text is different: the recording had ${describeWords(was.stable_words)}, the page now has ${describeWords(nowWords)}.`,\n };\n }\n return { ok: true, checks: ['position_fallback_confirmed'] };\n}\n\n/**\n * Decides whether the element replay found is the element that was recorded.\n *\n * What it does: with no recorded verification, a strong-locator winner passes with an\n * \"unverified_target\" warning and a position winner fails with the re-record message. With data, the\n * identity facts are checked first, then, for a position winner, the neighbour signal.\n * Why this order: the id-reuse block lives in the identity check and takes no input from anything\n * else, so a position-only fallback can never loosen it.\n */\nexport function verifyTarget(input: {\n recorded: Verification | null | undefined;\n found: Verification;\n winnerFamily: StrategyFamily;\n}): TargetVerdict {\n const { recorded, found, winnerFamily } = input;\n if (recorded === null || recorded === undefined) {\n if (winnerFamily === 'position') return { ok: false, message: RE_RECORD };\n return { ok: true, checks: ['unverified_target'] };\n }\n const identity = checkIdentity(recorded, found, winnerFamily);\n if (!identity.ok) return identity;\n if (winnerFamily !== 'position') return { ok: true, checks: identity.checks };\n if (recorded.neighbour === null) return { ok: false, message: RE_RECORD };\n const neighbour = checkNeighbour(recorded.neighbour, found.neighbour);\n if (!neighbour.ok) return neighbour;\n // A recording with no strong identifier (a type or role alone says what kind of control, not which one) has only its place and row text to go on, so a pass is\n // reported as an unverified position, not as a confirmed one.\n const hasStrongIdentifier = recorded.identifiers.some(\n (i) => i.unique_at_record && i.kind !== 'type' && i.kind !== 'role',\n );\n const neighbourChecks = hasStrongIdentifier\n ? neighbour.checks\n : neighbour.checks.map((c) =>\n c === 'position_fallback_confirmed' ? 'unverified_position' : c,\n );\n const checks = Array.from(new Set([...identity.checks, ...neighbourChecks]));\n return { ok: true, checks };\n}\n", "import type { Dialog } from 'playwright';\n\nexport type DialogType = 'alert' | 'confirm' | 'prompt';\n\n/** Contract `DialogResponse` with the prompt answer already resolved to text. */\nexport interface DialogExpectation {\n dialog_type: DialogType;\n action: 'accept' | 'dismiss';\n prompt_text?: string;\n message?: string;\n}\n\n/**\n * Whether a step re-arms the responder. Waits, assertions and checkpoints only observe the page, so they\n * leave the previous action's answers in place: its dialog may open after an async call, during them.\n */\nexport function armsDialogs(action: string): boolean {\n return (\n !action.startsWith('waitFor') && !action.startsWith('assert') && action !== 'manualCheckpoint'\n );\n}\n\n/**\n * Answers native alert, confirm and prompt dialogs. Playwright dismisses a dialog nobody handles, which\n * makes `confirm()` return false, so the handler is always installed. Expectations come from the step that\n * opens the dialog and are matched by order and type, never by message (messages carry dynamic ids). A\n * dialog without an expectation is accepted, which keeps definitions recorded before dialogs were\n * supported behaving like a user pressing OK.\n */\nexport class DialogResponder {\n private pending: DialogExpectation[] = [];\n private pendingLabel = '';\n private readonly unmet: string[] = [];\n\n /** Replaces the expectations for the step that is about to run; unmatched leftovers are reported. */\n arm(expectations: DialogExpectation[], stepLabel: string): void {\n this.flushPending();\n this.pending = [...expectations];\n this.pendingLabel = stepLabel;\n }\n\n /** Returns the expectations dropped by the last `arm` because no dialog matched them. */\n takeUnmet(): string[] {\n return this.unmet.splice(0);\n }\n\n /**\n * Playwright runs the page's JS thread blocked until this settles, so the handler must only call\n * accept or dismiss: no evaluate, screenshot or other page call.\n */\n async handle(dialog: Dialog): Promise<void> {\n const type = dialog.type();\n const index = this.pending.findIndex((e) => e.dialog_type === type);\n const expectation = index >= 0 ? this.pending.splice(index, 1)[0] : undefined;\n try {\n if (expectation?.action === 'dismiss') {\n await dialog.dismiss();\n } else {\n await dialog.accept(type === 'prompt' ? expectation?.prompt_text : undefined);\n }\n } catch {\n // The page navigated or closed while the dialog was open; nothing is left to answer.\n }\n }\n\n private flushPending(): void {\n for (const e of this.pending) {\n this.unmet.push(\n `${this.pendingLabel}: expected a ${e.dialog_type} dialog (${e.action}) that never appeared`,\n );\n }\n this.pending = [];\n }\n}\n", "import type { Page, Request } from 'playwright';\n\n/**\n * How a value seen on the page must compare to what the test author\n * wrote: exactly equal, contains it, or matches a regex.\n * `expand_values` says whether {{name}} placeholders (values saved by an\n * earlier step) should be filled in first.\n */\nexport interface ExpectedValue {\n match: 'exact' | 'contains' | 'regex';\n value: string;\n /** When true, `{{name}}` saved by an earlier step is replaced in `value`. */\n expand_values: boolean;\n}\n\n/**\n * The outcome of one check of a condition: did it hold, and what did\n * we actually see (null if we saw nothing).\n */\nexport interface ConditionProbe {\n passed: boolean;\n actual: string | null;\n /**\n * True when the check can never pass because the test itself is wrong\n * (for example \"is checked\" asked of a plain <div>). Polling stops at\n * once and the outcome is reported as a test-authoring problem, not as\n * an app failure. Left out for every ordinary result.\n */\n authoringGap?: boolean;\n}\n\n/**\n * A flag name set on the page's window during replay.\n * The Locus recorder looks for it and stays off, so it does not record\n * over the app being tested. Must match packages/recorder/src/index.ts.\n */\nexport const REPLAY_MARKER = '__locusReplay';\n\n/**\n * A tiny script run on every replayed page that sets the flag above.\n */\nexport const REPLAY_MARKER_SCRIPT = `Object.defineProperty(window, '${REPLAY_MARKER}', { value: true });`;\n\n/**\n * The kinds of network request we wait for before moving on: pages,\n * scripts, fetch and XHR calls. Images and fonts are ignored because\n * they do not mean the app is still reacting.\n */\nconst SETTLE_RESOURCE_TYPES = new Set(['document', 'script', 'fetch', 'xhr']);\n\n/**\n * Checks a seen value against the author's rule (exact, contains or\n * regex). Throws if the author wrote an invalid regex.\n */\nexport function matchesExpected(actual: string, expected: ExpectedValue): boolean {\n switch (expected.match) {\n case 'exact':\n return actual === expected.value;\n case 'contains':\n return actual.includes(expected.value);\n case 'regex':\n return new RegExp(expected.value).test(actual);\n }\n}\n\n/**\n * Turns any run of spaces/tabs/new lines into one space and trims the\n * ends, so line breaks in the page text never cause a mismatch.\n */\nexport function collapseWhitespace(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Writes a rule as short text for reports, for example\n * `contains 'Logged In'`.\n */\nexport function describeExpected(expected: ExpectedValue): string {\n return `${expected.match} '${expected.value}'`;\n}\n\n/**\n * Gets just the first line of an error message, to keep reports short.\n */\nexport function errorLine(err: unknown): string {\n return (err instanceof Error ? err.message : String(err)).split('\\n')[0] ?? '';\n}\n\n/**\n * Keeps checking a condition until it passes or time runs out, then\n * returns the last result. It checks every 100ms.\n * If a check throws (for example the element disappeared while the page\n * was updating) that counts as 'not yet', not as a crash.\n */\nexport async function pollCondition(\n page: Page,\n timeoutMs: number,\n probe: () => Promise<ConditionProbe>,\n): Promise<ConditionProbe> {\n // The time when we stop trying.\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n let result: ConditionProbe;\n try {\n result = await probe();\n } catch (err: unknown) {\n result = { passed: false, actual: `error: ${errorLine(err)}` };\n }\n if (result.passed || result.authoringGap === true || Date.now() >= deadline) {\n return result;\n }\n await page.waitForTimeout(100);\n }\n}\n\n/**\n * Waits for the page to go quiet after an action.\n * It watches network requests and, when asked to `settle`, waits until\n * nothing important has been in progress for a short while.\n * Very old requests (long polling, streams) are ignored so they cannot\n * block us forever, and running out of time is not a failure.\n */\nexport class NetworkSettler {\n /**\n * Requests that have started but not finished, with their start time.\n */\n private readonly inflight = new Map<Request, number>();\n\n /**\n * Starts watching the page. Tracked requests are added when they start\n * and removed when they finish or fail.\n * `timeoutMs` is the most we wait; `quietMs` is how long it must be quiet.\n */\n constructor(\n private readonly page: Page,\n private readonly timeoutMs: number,\n private readonly quietMs: number,\n ) {\n page.on('request', (req: Request) => {\n if (SETTLE_RESOURCE_TYPES.has(req.resourceType())) {\n this.inflight.set(req, Date.now());\n }\n });\n page.on('requestfinished', (req: Request) => {\n this.inflight.delete(req);\n });\n page.on('requestfailed', (req: Request) => {\n this.inflight.delete(req);\n });\n }\n\n /**\n * Waits until no tracked request has been running for `quietMs`, or\n * until the time limit is reached (then it just returns). Checks every\n * 50ms.\n */\n async settle(): Promise<void> {\n const deadline = Date.now() + this.timeoutMs;\n // When the current quiet period began, or null if requests are active.\n let quietSince: number | null = null;\n while (Date.now() < deadline) {\n const now = Date.now();\n // True if some tracked request is still running and is not too old.\n const busy = [...this.inflight.values()].some(\n (startedAt) => now - startedAt < this.timeoutMs,\n );\n if (busy) {\n quietSince = null;\n } else {\n quietSince ??= now;\n if (now - quietSince >= this.quietMs) {\n return;\n }\n }\n await this.page.waitForTimeout(50);\n }\n }\n}\n\n/**\n * Keeps track of time limits for one run.\n * Every timeout is multiplied by the environment's factor (slower\n * environments get more time) and never goes past the run's overall\n * deadline.\n */\nexport class RunBudget {\n /**\n * The moment the whole run must be finished.\n */\n private readonly deadline: number;\n\n /**\n * Starts the run's clock. `multiplier` stretches the per-step timeouts\n * (for example 2 gives slow environments twice as long).\n */\n constructor(\n runTimeoutMs: number,\n private readonly multiplier: number,\n ) {\n this.deadline = Date.now() + runTimeoutMs;\n }\n\n /**\n * How many milliseconds are left before the run deadline (never below 0).\n */\n remainingMs(): number {\n return Math.max(0, this.deadline - Date.now());\n }\n\n /**\n * True when the run deadline has passed.\n */\n expired(): boolean {\n return this.remainingMs() === 0;\n }\n\n /**\n * Returns a timeout to use: the wanted time times the multiplier, but no\n * more than what is left of the run. It is never 0, because Playwright\n * reads 0 as 'no timeout at all'.\n */\n limit(timeoutMs: number): number {\n return Math.max(1, Math.min(Math.round(timeoutMs * this.multiplier), this.remainingMs()));\n }\n\n /**\n * Like `limit`, but without the deadline cap. For waits that end quietly\n * instead of failing, such as the network settle.\n */\n scaled(timeoutMs: number): number {\n return Math.round(timeoutMs * this.multiplier);\n }\n}\n\n/**\n * How many milliseconds a step spent in each stage (finding the element,\n * acting on it, settling, checking conditions), added up over retries.\n */\nexport interface StepTimings {\n resolve_ms: number;\n action_ms: number;\n settle_ms: number;\n conditions_ms: number;\n}\n\n/**\n * A stopwatch that splits a step's time between its stages. Time keeps\n * adding to the current stage until `enter` moves to the next one.\n */\nexport class PhaseTimer {\n /**\n * The totals so far for each stage.\n */\n readonly timings: StepTimings = { resolve_ms: 0, action_ms: 0, settle_ms: 0, conditions_ms: 0 };\n /**\n * The stage currently being timed.\n */\n private phase: keyof StepTimings = 'resolve_ms';\n /**\n * When the current stage's clock last started. It reads the monotonic\n * clock, which never goes backwards. The wall clock (Date.now) can jump\n * back when the system time is synced, and that gave negative timings\n * that the run-result contract rejects.\n */\n private since = performance.now();\n\n /**\n * Moves to a new stage, first adding the time spent so far to the old one.\n */\n enter(phase: keyof StepTimings): void {\n this.flush();\n this.phase = phase;\n }\n\n /**\n * Adds the time since the last switch to the current stage and restarts\n * the clock.\n */\n flush(): void {\n const now = performance.now();\n this.timings[this.phase] += Math.round(Math.max(0, now - this.since));\n this.since = now;\n }\n}\n", "import type { JSHandle, Locator, Page } from 'playwright';\n\nimport type { LocatorSet, Verification } from '@locus/locator-engine';\n\n/**\n * Size limits from the run-result contract (NearMatch).\n * The report may hold at most 5 look-alike elements, each with at most\n * 10 changes, and text is cut to 200 characters. If you change one of\n * these you must change the contract schema too.\n */\nexport const MAX_NEAR_MATCHES = 5;\n/**\n * Most differences listed for one look-alike element (contract limit).\n */\nexport const MAX_NEAR_MATCH_CHANGES = 10;\n/**\n * Longest text kept in a report field, in characters (contract limit).\n */\nexport const MAX_NEAR_MATCH_TEXT = 200;\n/**\n * Longest allowed name for a changed field, in characters.\n */\nconst MAX_CHANGE_FIELD = 64;\n\n/**\n * How much each clue counts when deciding if an element looks like the\n * one we recorded. The accessible name matters most, the tag least.\n * If the recording is missing a clue, the other weights are scaled up\n * so the total still adds to 1.\n */\nexport const SIGNAL_WEIGHTS = {\n accessible_name: 0.35,\n text: 0.2,\n role: 0.15,\n tag: 0.1,\n attributes: 0.2,\n} as const;\n\n/**\n * Attributes we never read, compare or store, because their value is\n * something a person typed or picked (privacy). Currently just `value`.\n */\nconst NEVER_READ_ATTRIBUTES: ReadonlySet<string> = new Set(['value']);\n\n/**\n * One look-alike element offered to the user: a short description, how\n * close it is (0-1), what changed, and fresh locators for it.\n */\nexport interface NearMatchOptions {\n /** Source of the locator-engine IIFE bundle (exposes `LocusEngine`). */\n engineBundle: string;\n /** Elements examined on the page at most. */\n scanCap: number;\n /** Wall-clock cap for the whole capture. */\n timeoutMs: number;\n /** Score (0-1) a candidate needs to be reported. */\n minScore: number;\n}\n\n/**\n * The element as it was recorded, built from the step's saved locators\n * (they all describe the same element).\n */\nexport interface RecordedTarget {\n tag: string;\n role: string | null;\n accessible_name: string | null;\n text: string | null;\n attributes: Record<string, string>;\n}\n\n/**\n * What the live page says about one possible look-alike element.\n * It never includes `value` or password inputs.\n */\nexport interface CandidateDescriptor {\n tag: string;\n role: string | null;\n accessible_name: string | null;\n text: string | null;\n attributes: Record<string, string>;\n}\n\n/**\n * One difference between the recorded element and a look-alike:\n * which field, what it was, and what it is now.\n */\nexport interface NearMatchChange {\n field: string;\n recorded: string | null;\n now: string | null;\n}\n\nexport interface NearMatch {\n description: string;\n score: number;\n changes: NearMatchChange[];\n locator_set: LocatorSet;\n}\n\n/**\n * The loosely typed fields we read from a saved locator. Saved data is\n * not trusted, so every field is `unknown` until checked.\n */\ninterface RawLocatorFields {\n tag?: unknown;\n role?: unknown;\n accessible_name?: unknown;\n text?: unknown;\n attributes?: unknown;\n}\n\n/**\n * Returns the value if it is a non-blank string, otherwise null.\n */\nfunction asText(value: unknown): string | null {\n return typeof value === 'string' && value.trim() !== '' ? value : null;\n}\n\n/**\n * Works out which element was recorded from a step's saved locators.\n * It uses the first locator that has a tag, keeps only text attributes\n * and skips `value`. Returns null if no locator has a tag (for example a\n * hand-written test), because then there is nothing to compare with.\n */\nexport function recordedTargetOf(locators: ReadonlyArray<RawLocatorFields>): RecordedTarget | null {\n // The first saved locator that includes the element's tag name.\n const withTag = locators.find((l) => typeof l.tag === 'string' && l.tag !== '');\n if (!withTag) return null;\n // The recorded attributes we are allowed to use (text only, no `value`).\n const attributes: Record<string, string> = {};\n if (typeof withTag.attributes === 'object' && withTag.attributes !== null) {\n for (const [name, value] of Object.entries(withTag.attributes as Record<string, unknown>)) {\n if (typeof value === 'string' && !NEVER_READ_ATTRIBUTES.has(name)) attributes[name] = value;\n }\n }\n return {\n tag: (withTag.tag as string).toLowerCase(),\n role: asText(withTag.role),\n accessible_name: asText(withTag.accessible_name),\n text: asText(withTag.text),\n attributes,\n };\n}\n\n/**\n * Splits text into overlapping two-letter pieces and counts them,\n * for example 'cat' becomes 'ca' and 'at'. Text is lower-cased and\n * whitespace is tidied first. Very short text is kept as one piece.\n */\nfunction bigrams(text: string): Map<string, number> {\n const normalized = text.toLowerCase().replace(/\\s+/g, ' ').trim();\n const grams = new Map<string, number>();\n if (normalized.length < 2) {\n if (normalized !== '') grams.set(normalized, 1);\n return grams;\n }\n for (let i = 0; i < normalized.length - 1; i++) {\n const gram = normalized.slice(i, i + 2);\n grams.set(gram, (grams.get(gram) ?? 0) + 1);\n }\n return grams;\n}\n\n/**\n * Says how alike two texts are, from 0 (nothing in common) to 1\n * (identical). It compares the two-letter pieces from `bigrams` (the Dice\n * coefficient), ignoring case and extra spaces. Small edits such as a\n * changed word ending still score high.\n */\nexport function textSimilarity(a: string, b: string): number {\n const left = bigrams(a);\n const right = bigrams(b);\n // Total number of pieces in both texts.\n let total = 0;\n for (const n of left.values()) total += n;\n for (const n of right.values()) total += n;\n if (total === 0) return 0;\n // Number of pieces both texts have.\n let shared = 0;\n for (const [gram, n] of left) shared += Math.min(n, right.get(gram) ?? 0);\n return (2 * shared) / total;\n}\n\n/**\n * Says what fraction of the recorded attributes still have the same\n * value on the candidate. Returns null if nothing was recorded, which\n * means 'skip this clue' rather than 'no match'.\n */\nfunction attributeSimilarity(\n recorded: Record<string, string>,\n candidate: Record<string, string>,\n): number | null {\n const names = Object.keys(recorded);\n if (names.length === 0) return null;\n let same = 0;\n for (const name of names) {\n if (candidate[name] === recorded[name]) same++;\n }\n return same / names.length;\n}\n\n/**\n * Gives a candidate element a score from 0 to 1 for how much it looks\n * like the recorded one, using the clues in SIGNAL_WEIGHTS.\n * A clue the recording does not have is left out, and the others are\n * scaled up, so a recording without text is not punished for it.\n * Returns 0 if nothing could be compared.\n */\nexport function scoreCandidate(recorded: RecordedTarget, candidate: CandidateDescriptor): number {\n // Running total of weight times similarity.\n let weighted = 0;\n // Running total of the weights actually used.\n let weights = 0;\n // Adds one clue to the totals. A null similarity means the clue is not\n // available, so it is skipped.\n const add = (weight: number, similarity: number | null): void => {\n if (similarity === null) return;\n weighted += weight * similarity;\n weights += weight;\n };\n add(\n SIGNAL_WEIGHTS.accessible_name,\n recorded.accessible_name === null\n ? null\n : candidate.accessible_name === null\n ? 0\n : textSimilarity(recorded.accessible_name, candidate.accessible_name),\n );\n add(\n SIGNAL_WEIGHTS.text,\n recorded.text === null\n ? null\n : candidate.text === null\n ? 0\n : textSimilarity(recorded.text, candidate.text),\n );\n add(\n SIGNAL_WEIGHTS.role,\n recorded.role === null ? null : recorded.role === candidate.role ? 1 : 0,\n );\n add(SIGNAL_WEIGHTS.tag, recorded.tag === candidate.tag ? 1 : 0);\n add(SIGNAL_WEIGHTS.attributes, attributeSimilarity(recorded.attributes, candidate.attributes));\n return weights === 0 ? 0 : Math.round((weighted / weights) * 1000) / 1000;\n}\n\n/**\n * Cuts text to the report's maximum length. Null stays null.\n */\nfunction bounded(value: string | null): string | null {\n if (value === null) return null;\n return value.length > MAX_NEAR_MATCH_TEXT ? value.slice(0, MAX_NEAR_MATCH_TEXT) : value;\n}\n\n/**\n * Lists what is different between the recorded element and a candidate:\n * name, text, tag, role and each recorded attribute. Stops at the\n * report's limit, cuts long text, and never includes typed values.\n */\nexport function changesBetween(\n recorded: RecordedTarget,\n candidate: CandidateDescriptor,\n): NearMatchChange[] {\n // The differences found so far.\n const changes: NearMatchChange[] = [];\n // Adds a difference if the two values are not the same and there is\n // still room in the list.\n const compare = (field: string, before: string | null, now: string | null): void => {\n if (before === now || changes.length >= MAX_NEAR_MATCH_CHANGES) return;\n changes.push({\n field: field.slice(0, MAX_CHANGE_FIELD),\n recorded: bounded(before),\n now: bounded(now),\n });\n };\n compare('accessible_name', recorded.accessible_name, candidate.accessible_name);\n compare('text', recorded.text, candidate.text);\n compare('tag', recorded.tag, candidate.tag);\n compare('role', recorded.role, candidate.role);\n for (const name of Object.keys(recorded.attributes)) {\n compare(\n `attribute:${name}`,\n recorded.attributes[name] ?? null,\n candidate.attributes[name] ?? null,\n );\n }\n return changes;\n}\n\n/**\n * Makes a short label for a candidate, such as `button \"Save\"`:\n * its role (or tag) followed by its name (or text) when it has one.\n */\nexport function describeCandidate(candidate: CandidateDescriptor): string {\n const kind = candidate.role ?? candidate.tag;\n const label = candidate.accessible_name ?? candidate.text;\n const text = label === null ? kind : `${kind} \"${label}\"`;\n return text.length > MAX_NEAR_MATCH_TEXT ? text.slice(0, MAX_NEAR_MATCH_TEXT) : text;\n}\n\n/**\n * Picks the best look-alikes. Scores every candidate, drops those below\n * the minimum score, sorts best first (ties keep page order) and keeps\n * at most 5. Returns each one's position in the input list and its score.\n */\nexport function rankCandidates(\n recorded: RecordedTarget,\n candidates: ReadonlyArray<CandidateDescriptor>,\n minScore: number,\n): Array<{ index: number; score: number }> {\n return candidates\n .map((candidate, index) => ({ index, score: scoreCandidate(recorded, candidate) }))\n .filter((entry) => entry.score >= minScore)\n .sort((a, b) => b.score - a.score || a.index - b.index)\n .slice(0, MAX_NEAR_MATCHES);\n}\n\n/**\n * The few browser element features the in-page code needs. The runner is\n * compiled without browser types, so we describe them ourselves.\n */\ninterface PageElement {\n tagName: string;\n type?: string;\n getAttribute(name: string): string | null;\n}\n/**\n * Tells TypeScript that `document` exists in the page. It is only\n * valid inside code that Playwright runs in the browser.\n */\ndeclare const document: { querySelectorAll(selector: string): Iterable<PageElement> };\n\n/**\n * The locator engine's functions that we call inside the page: hidden\n * check, accessible name, text, role and building a full locator set.\n */\ninterface PageEngine {\n isHidden(el: PageElement): boolean;\n accessibleName(el: PageElement): { name: string; source: string } | null;\n elementText(el: PageElement): string;\n implicitRole(el: PageElement): string | null;\n buildLocatorSet(el: PageElement): LocatorSet;\n captureVerification(el: PageElement, tools: unknown): Verification;\n storageCaptureTools: unknown;\n}\n\n/**\n * Runs in the page. Collects the elements worth scoring: those with the\n * same tag (or role) as the recorded element. Password inputs are\n * skipped and at most `cap` elements are taken so a huge page cannot\n * make this slow.\n */\nfunction collectElements(args: { tag: string; role: string | null; cap: number }): PageElement[] {\n // CSS selector for elements with the recorded role, if there is one.\n // Quotes are stripped from the role so it cannot break the selector.\n const roleSelector = args.role === null ? null : '[role=\"' + args.role.replace(/\"/g, '') + '\"]';\n // Final selector: the tag, plus the role selector if any.\n const selector = roleSelector === null ? args.tag : args.tag + ',' + roleSelector;\n // The elements collected so far.\n const found: PageElement[] = [];\n for (const el of document.querySelectorAll(selector)) {\n if (found.length >= args.cap) break;\n if (el.tagName === 'INPUT' && el.type === 'password') continue;\n found.push(el);\n }\n return found;\n}\n\n/**\n * Runs in the page. Puts one element into a list so it can be described\n * the same way as a scanned list.\n */\nfunction wrapElement(el: PageElement): PageElement[] {\n return [el];\n}\n\n/**\n * Runs in the page. Turns elements into plain descriptions\n * (tag, role, name, text, chosen attributes). Hidden elements and\n * password inputs give null. Only the attributes we ask for are read and\n * `value` is never read. Text is cut to `maxText` characters.\n */\nfunction describeElements(args: {\n engine: PageEngine;\n elements: PageElement[];\n attributeNames: string[];\n maxText: number;\n}): Array<CandidateDescriptor | null> {\n // Shortens text, and turns empty text into null.\n const cut = (text: string | null): string | null =>\n text === null || text === '' ? null : text.slice(0, args.maxText);\n return args.elements.map((el) => {\n if (args.engine.isHidden(el)) return null;\n if (el.tagName === 'INPUT' && el.type === 'password') return null;\n const name = args.engine.accessibleName(el);\n const attributes: Record<string, string> = {};\n for (const attr of args.attributeNames) {\n const value = el.getAttribute(attr);\n if (value !== null) attributes[attr] = value.slice(0, args.maxText);\n }\n return {\n tag: el.tagName.toLowerCase(),\n role: el.getAttribute('role') || args.engine.implicitRole(el) || null,\n accessible_name: cut(name !== null && name.source !== 'value' ? name.name : null),\n text: cut(args.engine.elementText(el)),\n attributes,\n };\n });\n}\n\n/**\n * Runs in the page. Builds a full set of locators for each chosen\n * element, so the user can adopt the new locators.\n */\nfunction buildLocatorSets(args: {\n engine: PageEngine;\n elements: PageElement[];\n indexes: number[];\n}): LocatorSet[] {\n return args.indexes.map((i) => {\n const el = args.elements[i]!;\n const set = args.engine.buildLocatorSet(el);\n // The facts a person's accepted repair will store. A failed read leaves them null, which later\n // refuses the accept instead of saving a target with nothing to verify.\n try {\n set.verification = args.engine.captureVerification(el, args.engine.storageCaptureTools);\n } catch {\n set.verification = null;\n }\n return set;\n });\n}\n\n/**\n * Releases browser handles we created so the page can free memory.\n * Errors are ignored: if the page already closed there is nothing left\n * to release.\n */\nasync function disposeAll(handles: ReadonlyArray<JSHandle | null>): Promise<void> {\n await Promise.all(\n handles.map(async (handle) => {\n if (handle === null) return;\n try {\n await handle.dispose();\n } catch {\n // the page may already be gone; nothing left to release\n }\n }),\n );\n}\n\n/**\n * Looks for look-alike elements on the live page.\n * Steps: load the locator engine into the page, collect same-tag\n * elements, describe the visible ones, score and rank them, then build\n * locators only for the winners. Every browser handle is added to\n * `handles` so the caller can release them.\n */\nasync function capture(\n page: Page,\n recorded: RecordedTarget,\n options: NearMatchOptions,\n handles: JSHandle[],\n): Promise<NearMatch[]> {\n // A handle to the locator engine inside the page.\n const engine = await page.evaluateHandle<PageEngine>(\n `(() => { ${options.engineBundle}\\n; return LocusEngine; })()`,\n );\n handles.push(engine);\n // A handle to the list of elements inside the page.\n const elements = await page.evaluateHandle(collectElements, {\n tag: recorded.tag,\n role: recorded.role,\n cap: options.scanCap,\n });\n handles.push(elements);\n\n // A description of each element (null for hidden ones).\n const described = await page.evaluate(describeElements, {\n engine,\n elements,\n attributeNames: Object.keys(recorded.attributes),\n maxText: MAX_NEAR_MATCH_TEXT,\n });\n // The elements that were visible, with their position in the page list.\n const visible: Array<{ original: number; descriptor: CandidateDescriptor }> = [];\n described.forEach((descriptor, original) => {\n if (descriptor !== null) visible.push({ original, descriptor });\n });\n // The best look-alikes, best first.\n const ranked = rankCandidates(\n recorded,\n visible.map((v) => v.descriptor),\n options.minScore,\n );\n if (ranked.length === 0) return [];\n\n // The locator sets built for the best look-alikes.\n const sets = await page.evaluate(buildLocatorSets, {\n engine,\n elements,\n indexes: ranked.map((r) => visible[r.index]!.original),\n });\n return ranked.map((entry, n) => {\n const descriptor = visible[entry.index]!.descriptor;\n return {\n description: describeCandidate(descriptor),\n score: entry.score,\n changes: changesBetween(recorded, descriptor),\n locator_set: sets[n]!,\n };\n });\n}\n\n/**\n * Describes the one element a step actually found (using a backup\n * locator) and builds fresh locators for it, so a person can update the\n * recorded locators. Returns an empty list if the element or its\n * description cannot be had.\n */\nasync function captureResolved(\n page: Page,\n locator: Locator,\n recorded: RecordedTarget,\n options: NearMatchOptions,\n handles: JSHandle[],\n): Promise<NearMatch[]> {\n const engine = await page.evaluateHandle<PageEngine>(\n `(() => { ${options.engineBundle}\\n; return LocusEngine; })()`,\n );\n handles.push(engine);\n // A handle to the element the step found.\n const element = await locator.elementHandle({ timeout: options.timeoutMs });\n if (element === null) return [];\n handles.push(element);\n const elements = await page.evaluateHandle(wrapElement, element);\n handles.push(elements);\n const [descriptor] = await page.evaluate(describeElements, {\n engine,\n elements,\n attributeNames: Object.keys(recorded.attributes),\n maxText: MAX_NEAR_MATCH_TEXT,\n });\n if (descriptor === null || descriptor === undefined) return [];\n const [set] = await page.evaluate(buildLocatorSets, { engine, elements, indexes: [0] });\n if (set === undefined) return [];\n return [\n {\n description: describeCandidate(descriptor),\n score: scoreCandidate(recorded, descriptor),\n changes: changesBetween(recorded, descriptor),\n locator_set: set,\n },\n ];\n}\n\n/**\n * Runs a capture job with a time limit, and always releases the browser\n * handles it made afterwards. If the job fails or takes too long the\n * result is an empty list, so the capture can never change how the step\n * failed.\n */\nasync function withinBudget(\n options: NearMatchOptions,\n work: (handles: JSHandle[]) => Promise<NearMatch[]>,\n): Promise<NearMatch[]> {\n // Browser handles created during the job, released at the end.\n const handles: JSHandle[] = [];\n // The time-limit timer, cleared at the end.\n let timer: NodeJS.Timeout | undefined;\n try {\n // A promise that finishes with an empty list when time runs out; it\n // races against the real work.\n const timeout = new Promise<NearMatch[]>((resolve) => {\n timer = setTimeout(() => resolve([]), options.timeoutMs);\n });\n return await Promise.race([work(handles), timeout]);\n } catch {\n return [];\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n await disposeAll(handles);\n }\n}\n\n/**\n * Called when a step cannot find its element. Looks for elements on the\n * live page that look like the recorded one.\n * It never throws and never takes longer than the time limit: any error,\n * timeout or closed page just gives an empty list. It talks to the page\n * through the browser debugging protocol rather than adding a script\n * tag, so it still works on pages with a strict content security policy.\n */\nexport function captureNearMatches(\n page: Page,\n recorded: RecordedTarget,\n options: NearMatchOptions,\n): Promise<NearMatch[]> {\n return withinBudget(options, (handles) => capture(page, recorded, options, handles));\n}\n\n/**\n * Called when a step found its element only through a backup locator.\n * Describes that element with fresh locators so a person can refresh the\n * saved ones. Same safety rules as `captureNearMatches`.\n */\nexport function captureResolvedMatch(\n page: Page,\n locator: Locator,\n recorded: RecordedTarget,\n options: NearMatchOptions,\n): Promise<NearMatch[]> {\n return withinBudget(options, (handles) =>\n captureResolved(page, locator, recorded, options, handles),\n );\n}\n", "import type { RunnerConfig } from './config.js';\n\n/**\n * The log levels we accept (debug, info, warn, error).\n * It is taken from the config type so the logger and the config\n * can never disagree about what a valid level is.\n */\nexport type LogLevel = RunnerConfig['logLevel'];\ntype Level = LogLevel;\n/**\n * A number for each level so we can compare them.\n * A message is only printed if its number is at least the configured\n * level's number. Example: with level 'warn' (30), 'info' (20) is skipped.\n */\nconst ORDER: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };\n\n/**\n * What the rest of the runner uses to write logs.\n * There is one method per level. Each takes a message and optional\n * extra fields, which end up in the same JSON line.\n */\nexport interface Logger {\n debug(message: string, fields?: Record<string, unknown>): void;\n info(message: string, fields?: Record<string, unknown>): void;\n warn(message: string, fields?: Record<string, unknown>): void;\n error(message: string, fields?: Record<string, unknown>): void;\n}\n\n/**\n * Creates the runner's logger.\n * It writes one JSON object per line, in the same shape the Go services\n * use, so all logs can be read and searched the same way.\n * The `write` function is passed in (instead of calling console directly)\n * so tests can capture the output.\n */\nexport function createLogger(service: string, level: Level, write: (line: string) => void): Logger {\n // Prints one log line, but only if its level is high enough.\n // Extra fields are added last, so avoid field names like 'time' or\n // 'level' or they will overwrite the standard ones.\n const emit = (at: Level, message: string, fields?: Record<string, unknown>): void => {\n if (ORDER[at] < ORDER[level]) {\n return;\n }\n write(\n JSON.stringify({\n time: new Date().toISOString(),\n level: at,\n service,\n msg: message,\n ...fields,\n }),\n );\n };\n return {\n debug: (message, fields) => emit('debug', message, fields),\n info: (message, fields) => emit('info', message, fields),\n warn: (message, fields) => emit('warn', message, fields),\n error: (message, fields) => emit('error', message, fields),\n };\n}\n", "import { RequestSigner } from './signer.js';\nimport type { BrowserName } from './browsers.js';\nimport type { ExportLimits } from './exports.js';\n\n/**\n * What the dashboard says about one fixture a run picks. The bytes are fetched separately.\n * `sha256` is the digest of the plain bytes, so the runner can check what it downloaded.\n * `deleted_at` is set for a deleted fixture, and `missing` is true when no record exists.\n */\n/**\n * BundleRow is the data-driven row that came with a claimed run.\n *\n * What it is: the same shape as the dashboard's `BundleRow` (shared/pkg/models/data_set.go).\n * What it does: carries the row's text values and, for secret columns, only the NAME of the\n * vault secret; the secret value arrives in `RunBundle.secrets` under that name.\n * How: plain JSON fields, none optional, so a missing key is a contract break.\n */\nexport interface BundleRow {\n row_id: string;\n index: number;\n label: string;\n values: Record<string, string>;\n secret_columns: Record<string, string>;\n}\n\nexport interface RunBundleFixture {\n name: string;\n content_type: string;\n size_bytes: number;\n sha256: string;\n deleted_at: string | null;\n missing: boolean;\n}\n\n/**\n * Everything the runner needs to execute one run. The dashboard sends it\n * when the runner claims the run. It holds who the run belongs to\n * (tenant, site, test case), the steps to replay, any secrets, how much\n * to stretch timeouts, where to upload screenshots/traces, and optional\n * extras for the chosen environment (base URL, variables, headers,\n * login state).\n */\nexport interface RunBundle {\n run_id: string;\n tenant_id: string;\n site_id: string;\n test_case_id: string;\n def_version: number;\n definition: {\n start_url: string;\n steps: Array<Record<string, unknown>>;\n [key: string]: unknown;\n };\n secrets: Record<string, string>;\n /**\n * The data-driven row this run replays, or null/absent for a test case without a data set.\n * Its text values and secret columns reach both the {{...}} lookup and the \"variable\" fill.\n */\n row?: BundleRow | null;\n /** Every fixture the definition picks, by id: what the library knows about it (never the bytes). */\n fixtures: Record<string, RunBundleFixture>;\n /** Environment scale for step, settle and condition timeouts (1 = as configured). */\n timeout_multiplier: number;\n /**\n * True only when the environment owner switched on \"accept invalid HTTPS certificates\"\n * (self-signed staging servers). False means the browser checks certificates normally.\n */\n allow_invalid_tls: boolean;\n /**\n * The browser this run must replay in: 'chromium' or 'firefox'. Always present; the runner\n * refuses a bundle without a known value instead of guessing.\n */\n browser: BrowserName;\n /**\n * CSS selectors the site owner wants hidden in every screenshot and trace picture.\n * Always present; an empty list means nothing is hidden.\n */\n screenshot_hide_selectors: string[];\n artifact_upload_urls: {\n trace?: string;\n screenshot?: string;\n [key: string]: string | undefined;\n };\n environment?: string;\n environment_slug?: string;\n base_url_override?: string;\n variables?: Record<string, string>;\n headers?: Record<string, string>;\n is_auth_prerequisite?: boolean;\n storage_state?: Record<string, unknown>;\n storage_state_ref?: string;\n /**\n * How much this run may export. The dashboard sends it with every claim from this version on;\n * when it is missing the runner lets no flagged value out.\n */\n export_limits?: ExportLimits;\n}\n\n/**\n * The error code the dashboard sends when a heartbeat or finish call comes for a run that a\n * person has cancelled.\n */\nconst RUN_CANCELLED_CODE = 'RUN_CANCELLED';\n\n/**\n * Thrown when the dashboard says the run was cancelled.\n * It is its own class so the consumer can tell \"stop, nobody wants this result\" apart from a\n * real network or server failure, which only gets logged.\n */\nexport class RunCancelledError extends Error {\n /**\n * Builds the error for one run.\n */\n constructor(runId: string) {\n super(`run ${runId} was cancelled`);\n this.name = 'RunCancelledError';\n }\n}\n\n/**\n * Turns a failed reply from the dashboard into an error.\n * What it does: if the reply body carries the RUN_CANCELLED code it returns a\n * RunCancelledError; otherwise it returns a plain Error carrying the message the caller built\n * (call name, HTTP status and reply text), exactly as before.\n * How it works: the body is JSON in the shape {status, error, code}. A body that is not JSON\n * simply falls through to the plain error, because a proxy page must not hide the real status.\n */\nfunction failedReply(runId: string, message: string, body: string): Error {\n try {\n const parsed = JSON.parse(body) as { code?: unknown };\n if (parsed.code === RUN_CANCELLED_CODE) {\n return new RunCancelledError(runId);\n }\n } catch {\n // Not JSON: fall through to the plain error below.\n }\n return new Error(message);\n}\n\n/**\n * Settings needed to talk to the dashboard: its address, this runner's\n * id, and the key and secret used to sign requests.\n */\nexport interface DashboardClientOptions {\n baseUrl: string;\n runnerId: string;\n hmacKey: string;\n hmacSecret: string;\n}\n\n/**\n * Talks to the dashboard's internal run API.\n * It can claim a run, say 'I am still working', and report the final\n * result. Every request is signed so the dashboard knows it is us.\n */\nexport class DashboardClient {\n /**\n * The dashboard address with any trailing slashes removed, so\n * joining paths never produces '//'.\n */\n private readonly baseUrl: string;\n /**\n * This runner's id. The dashboard uses it to know who owns a run.\n */\n private readonly runnerId: string;\n /**\n * Adds the signature headers to each request.\n */\n private readonly signer: RequestSigner;\n\n /**\n * Cleans up the base URL and creates the signer from the key and secret.\n */\n constructor(options: DashboardClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.runnerId = options.runnerId;\n this.signer = new RequestSigner({ key: options.hmacKey, secret: options.hmacSecret });\n }\n\n /**\n * Asks the dashboard to give this runner a queued run, and returns\n * everything needed to run it (see RunBundle).\n * If the dashboard refuses (for example another runner got it first) it\n * throws an error that includes the HTTP status and the reply text.\n */\n async claim(runId: string): Promise<RunBundle> {\n const path = `/internal/v1/runs/${encodeURIComponent(runId)}/claim`;\n const body = JSON.stringify({ runner_id: this.runnerId });\n const headers = this.signer.sign('POST', path, body);\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text();\n throw new Error(`claim run ${runId} failed (HTTP ${res.status}): ${errText}`);\n }\n\n const payload = (await res.json()) as { data: RunBundle };\n return payload.data;\n }\n\n /**\n * Downloads the bytes of one fixture the run picks.\n * The request is signed like every other internal call. The dashboard checks the fixture\n * belongs to this run's site and definition, so a wrong id fails here. Any non-OK reply\n * throws an error with the HTTP status and reply text, and the caller turns it into a\n * step failure.\n */\n async fixture(runId: string, fixtureId: string): Promise<Buffer> {\n const path = `/internal/v1/runs/${encodeURIComponent(runId)}/fixtures/${encodeURIComponent(fixtureId)}`;\n const headers = this.signer.sign('GET', path, '');\n\n const res = await fetch(`${this.baseUrl}${path}`, { method: 'GET', headers });\n\n if (!res.ok) {\n const errText = await res.text();\n throw new Error(`fixture ${fixtureId} failed (HTTP ${res.status}): ${errText}`);\n }\n return Buffer.from(await res.arrayBuffer());\n }\n\n /**\n * Tells the dashboard 'this run is still alive'. If the heartbeats stop,\n * the dashboard treats the run as abandoned. Throws on a failed reply,\n * which the caller only logs.\n */\n async heartbeat(runId: string): Promise<void> {\n const path = `/internal/v1/runs/${encodeURIComponent(runId)}/heartbeat`;\n const body = JSON.stringify({ runner_id: this.runnerId });\n const headers = this.signer.sign('POST', path, body);\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text();\n throw failedReply(\n runId,\n `heartbeat for run ${runId} failed (HTTP ${res.status}): ${errText}`,\n errText,\n );\n }\n }\n\n /**\n * Sends the final result of the run to the dashboard.\n * The runner id goes in an extra header so the dashboard can check the\n * result comes from the runner that owns the run.\n */\n async finish(runId: string, result: unknown): Promise<void> {\n const path = `/internal/v1/runs/${encodeURIComponent(runId)}/finish`;\n const body = JSON.stringify(result);\n const headers = this.signer.sign('POST', path, body);\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Runner-Id': this.runnerId,\n ...headers,\n },\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text();\n throw failedReply(\n runId,\n `finish run ${runId} failed (HTTP ${res.status}): ${errText}`,\n errText,\n );\n }\n }\n}\n", "import { RunCancelledError, type RunBundle } from './dashboard-client.js';\n\n/**\n * Standard semver version string of the runner client.\n */\nexport const RUNNER_VERSION = '0.1.1';\n\n/**\n * Header key for sending client version to Locus server.\n */\nexport const HEADER_RUNNER_VERSION = 'X-Runner-Version';\n\n/**\n * Header key for sending runner instance identifier.\n */\nexport const HEADER_RUNNER_ID = 'X-Runner-Id';\n\n/**\n * Error code returned by server when run execution was cancelled.\n */\nconst CODE_RUN_CANCELLED = 'RUN_CANCELLED';\n\n/**\n * Error code returned by server when client runner version is below server minimum.\n */\nconst CODE_UPGRADE_REQUIRED = 'RUNNER_UPGRADE_REQUIRED';\n\n/**\n * Options required to instantiate a RunnerClient.\n *\n * What it is: typed configuration options for RunnerClient.\n * What it does: supplies server base URL, runner API token, and optional identifiers.\n * How it works: validated in constructor ensuring no blank URL or token.\n */\nexport interface RunnerClientOptions {\n baseUrl: string;\n token: string;\n runnerId?: string;\n version?: string;\n}\n\n/**\n * Discriminator status for customer runner claim operations.\n */\nexport type ClaimStatus = 'claimed' | 'idle' | 'finished';\n\n/**\n * Result payload returned by RunnerClient.claim.\n *\n * What it is: discriminated union of potential claim outcomes.\n * What it does: conveys either an active run bundle to replay, an idle signal, or collection completion.\n * How it works: mapped from the server's RunnerClaimResponse data structure.\n */\nexport type ClaimResult =\n | { status: 'claimed'; bundle: RunBundle }\n | { status: 'idle' }\n | { status: 'finished' };\n\n/**\n * Heartbeat response indicating lease renewal and cancellation status.\n *\n * What it is: keepalive response status from POST /api/v1/runner/runs/{id}/heartbeat.\n * What it does: signals whether the lease was updated and if execution was cancelled.\n * How it works: when cancelled is true, the consumer stops execution immediately.\n */\nexport interface HeartbeatResult {\n ok: boolean;\n cancelled: boolean;\n}\n\n/**\n * Options for creating a collection run via the runner client.\n *\n * What it is: request payload for POST /api/v1/collection-runs.\n * What it does: specifies target site, environment, test cases or folder, and executor mode.\n * How it works: sent with RoleRunner token, defaulting executor to 'local'.\n */\nexport interface CreateCollectionRunOptions {\n site_id: string;\n environment_id?: string | undefined;\n environment_slug?: string | undefined;\n test_case_ids?: string[] | undefined;\n folder_id?: string | undefined;\n all?: boolean | undefined;\n browser?: string | undefined;\n executor?: 'hosted' | 'local' | undefined;\n}\n\n/**\n * Server response for a newly created collection run.\n *\n * What it is: simplified response object from POST /api/v1/collection-runs.\n * What it does: returns the generated collection run identifier and initial status.\n * How it works: unpacked from the canonical API response envelope.\n */\nexport interface CreateCollectionRunResponse {\n id: string;\n status: string;\n site_id: string;\n total_runs: number;\n}\n\n/**\n * Custom error thrown when the public runner API returns an HTTP error response.\n *\n * What it is: dedicated error class representing failed runner HTTP interactions.\n * What it does: captures HTTP status code, machine-readable error code, and server message.\n * How it works: constructed from parsed server error payloads or fallback response status text.\n */\nexport class RunnerApiError extends Error {\n // HTTP status code returned by the gateway or service.\n readonly status: number;\n // Machine-readable error code if returned in server JSON envelope.\n readonly code?: string | undefined;\n\n /**\n * Constructs a RunnerApiError with status, message, and optional code.\n *\n * What it does: initializes the Error superclass and attaches status and code attributes.\n * How it works: sets class name to RunnerApiError for clean error inspection in catch blocks.\n */\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'RunnerApiError';\n this.status = status;\n this.code = code;\n }\n}\n\n/**\n * Specialized error thrown when the server enforces a higher runner minimum version.\n *\n * What it is: specialized subclass of RunnerApiError for HTTP 426 upgrade requirements.\n * What it does: prompts the operator or CI pipeline to upgrade the runner package.\n * How it works: triggered when server responds with RUNNER_UPGRADE_REQUIRED code.\n */\nexport class RunnerUpgradeRequiredError extends RunnerApiError {\n /**\n * Constructs a RunnerUpgradeRequiredError.\n *\n * What it does: sets class name to RunnerUpgradeRequiredError and fixes code to RUNNER_UPGRADE_REQUIRED.\n * How it works: ensures callers can easily identify version rejection without inspecting strings.\n */\n constructor(message: string, status: number = 426) {\n super(message, status, CODE_UPGRADE_REQUIRED);\n this.name = 'RunnerUpgradeRequiredError';\n }\n}\n\n/**\n * Client for the public Locus Runner API.\n *\n * What it is: HTTP transport communicating with the Locus public gateway under /api/v1/runner/*.\n * What it does: handles claiming queued local runs, renewing leases via heartbeat, reporting final\n * run results, downloading upload fixtures, and triggering collection runs in local executor mode.\n * How it works: authenticates using Bearer token (API token with RoleRunner), passes X-Runner-Version\n * and X-Runner-Id on every call, and unwraps the canonical { status, data, error, message } envelope.\n */\nexport class RunnerClient {\n // Gateway base URL stripped of trailing slashes.\n private readonly baseUrl: string;\n // Secret API token with RoleRunner.\n private readonly token: string;\n // Unique runner process identifier sent in headers and claim bodies.\n private readonly runnerId: string;\n // Semantic version of this runner binary.\n private readonly version: string;\n\n /**\n * Validates options and initializes the RunnerClient.\n *\n * What it does: validates non-empty baseUrl and token, and assigns fallback identifiers.\n * How it works: strips trailing slashes from baseUrl; generates runnerId if not supplied.\n */\n constructor(options: RunnerClientOptions) {\n if (!options.baseUrl || options.baseUrl.trim() === '') {\n throw new Error('baseUrl is required for RunnerClient');\n }\n if (!options.token || options.token.trim() === '') {\n throw new Error('token is required for RunnerClient');\n }\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.token = options.token.trim();\n this.runnerId =\n options.runnerId && options.runnerId.trim() !== ''\n ? options.runnerId.trim()\n : `runner-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;\n this.version =\n options.version && options.version.trim() !== '' ? options.version.trim() : RUNNER_VERSION;\n }\n\n /**\n * Returns standard headers included on all outbound API requests.\n *\n * What it does: constructs Authorization, X-Runner-Version, and X-Runner-Id headers.\n * How it works: returns a clean key-value record applied to fetch options.\n */\n private headers(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.token}`,\n [HEADER_RUNNER_VERSION]: this.version,\n [HEADER_RUNNER_ID]: this.runnerId,\n };\n }\n\n /**\n * Helper that checks response status and unwraps the JSON response envelope.\n *\n * What it does: reads response body, detects error conditions, and extracts the data property.\n * How it works: checks res.ok; parses JSON; throws RunnerUpgradeRequiredError, RunCancelledError,\n * or RunnerApiError on failure; returns typed data payload on success.\n */\n private async parseEnvelope<T>(res: Response, runIdForCancel?: string): Promise<T> {\n const rawText = await res.text();\n let parsed: {\n status?: string;\n data?: unknown;\n error?: string;\n message?: string;\n code?: string;\n } | null = null;\n try {\n parsed = JSON.parse(rawText) as {\n status?: string;\n data?: unknown;\n error?: string;\n message?: string;\n code?: string;\n };\n } catch {\n // Body is not JSON\n }\n\n if (!res.ok) {\n const code = parsed?.code ?? parsed?.error;\n const message =\n parsed?.message ?? parsed?.error ?? `Request failed with HTTP ${res.status}: ${rawText}`;\n if (res.status === 426 || code === CODE_UPGRADE_REQUIRED) {\n throw new RunnerUpgradeRequiredError(message, res.status);\n }\n if (code === CODE_RUN_CANCELLED && runIdForCancel) {\n throw new RunCancelledError(runIdForCancel);\n }\n throw new RunnerApiError(message, res.status, code);\n }\n\n if (!parsed || typeof parsed !== 'object') {\n throw new RunnerApiError('Invalid JSON response from server', res.status);\n }\n\n return (parsed.data !== undefined ? parsed.data : parsed) as T;\n }\n\n /**\n * Atomically claims the next ready local run for this runner's tenant.\n *\n * What it does: sends POST /api/v1/runner/claim with optional collectionRunId filter.\n * How it works: parses RunnerClaimResponse; returns { status: 'claimed', bundle } when a run\n * is claimed, { status: 'idle' } when no runs are ready, or { status: 'finished' } when\n * the target collection run has finished.\n */\n async claim(collectionRunId?: string): Promise<ClaimResult> {\n const path = '/api/v1/runner/claim';\n const body: Record<string, string> = { runner_id: this.runnerId };\n if (collectionRunId && collectionRunId.trim() !== '') {\n body.collection_run_id = collectionRunId.trim();\n }\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.headers(),\n },\n body: JSON.stringify(body),\n });\n\n const data = await this.parseEnvelope<{ status: string; [key: string]: unknown }>(res);\n if (data.status === 'claimed') {\n return {\n status: 'claimed',\n bundle: data as unknown as RunBundle,\n };\n }\n if (data.status === 'finished') {\n return { status: 'finished' };\n }\n return { status: 'idle' };\n }\n\n /**\n * Renews the execution lease for an in-flight run and detects operator cancellation.\n *\n * What it does: sends POST /api/v1/runner/runs/{id}/heartbeat.\n * How it works: returns HeartbeatResult with ok and cancelled booleans. If server responds\n * with RUN_CANCELLED error or cancelled: true, execution should be aborted.\n */\n async heartbeat(runId: string): Promise<HeartbeatResult> {\n const path = `/api/v1/runner/runs/${encodeURIComponent(runId)}/heartbeat`;\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.headers(),\n },\n body: JSON.stringify({ runner_id: this.runnerId }),\n });\n\n try {\n const data = await this.parseEnvelope<HeartbeatResult>(res, runId);\n return {\n ok: Boolean(data.ok),\n cancelled: Boolean(data.cancelled),\n };\n } catch (err) {\n if (err instanceof RunCancelledError) {\n return { ok: true, cancelled: true };\n }\n throw err;\n }\n }\n\n /**\n * Submits the completed RunResult payload for a claimed local run.\n *\n * What it does: sends POST /api/v1/runner/runs/{id}/finish with the test result.\n * How it works: verifies that result matches contract shape and posts raw JSON;\n * converts server RUN_CANCELLED response into RunCancelledError.\n */\n async finish(runId: string, result: unknown): Promise<void> {\n const path = `/api/v1/runner/runs/${encodeURIComponent(runId)}/finish`;\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.headers(),\n },\n body: JSON.stringify(result),\n });\n\n await this.parseEnvelope<{ ok: boolean }>(res, runId);\n }\n\n /**\n * Streams raw fixture bytes for a file upload step in a claimed run.\n *\n * What it does: sends GET /api/v1/runner/runs/{id}/fixtures/{fixtureId}.\n * How it works: fetches raw binary payload from server, returning it as a Node Buffer.\n */\n async fixture(runId: string, fixtureId: string): Promise<Buffer> {\n const path = `/api/v1/runner/runs/${encodeURIComponent(runId)}/fixtures/${encodeURIComponent(fixtureId)}`;\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: this.headers(),\n });\n\n if (!res.ok) {\n await this.parseEnvelope(res);\n }\n\n const arrayBuffer = await res.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n /**\n * Creates a new collection run targeted for local execution.\n *\n * What it does: sends POST /api/v1/collection-runs to trigger a test suite replay.\n * How it works: enforces executor: 'local' (unless explicitly overridden) and returns\n * the created collection run summary including run id.\n */\n async createCollectionRun(\n options: CreateCollectionRunOptions,\n ): Promise<CreateCollectionRunResponse> {\n const path = '/api/v1/collection-runs';\n const payload = {\n site_id: options.site_id,\n environment_id: options.environment_id,\n environment_slug: options.environment_slug,\n test_case_ids: options.test_case_ids,\n folder_id: options.folder_id,\n all: options.all,\n browser: options.browser,\n executor: options.executor ?? 'local',\n };\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.headers(),\n },\n body: JSON.stringify(payload),\n });\n\n return this.parseEnvelope<CreateCollectionRunResponse>(res);\n }\n\n /**\n * Returns the runner process identifier used by this client.\n *\n * What it does: getter for runnerId.\n * How it works: returns the string identifier.\n */\n getRunnerId(): string {\n return this.runnerId;\n }\n\n /**\n * Returns the client version string sent to the server.\n *\n * What it does: getter for version.\n * How it works: returns the semver string.\n */\n getVersion(): string {\n return this.version;\n }\n}\n", "/**\n * Summary record of one completed test case run for reporting.\n *\n * What it is: normalized result data captured during runner execution.\n * What it does: contains test case identifier, name, status, duration, and error details.\n * How it works: aggregated across claimed runs during a collection run in run mode.\n */\nexport interface RunSummary {\n runId: string;\n testCaseId: string;\n testCaseName: string;\n status: 'passed' | 'failed' | 'cancelled' | 'interrupted';\n durationMs: number;\n errorMessage?: string | undefined;\n failureStep?: number | undefined;\n}\n\n/**\n * Escapes special XML characters in text attributes and elements.\n *\n * What it does: converts &, <, >, \", and ' to their XML entity equivalents.\n * How it works: strips ASCII control characters (except tab, newline, carriage return)\n * and replaces reserved characters sequentially.\n */\nexport function escapeXml(str: string): string {\n // Strip control characters invalid in XML 1.0.\n // eslint-disable-next-line no-control-regex\n const clean = str.replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/g, '');\n return clean\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Converts milliseconds to fractional seconds string formatted to three decimal places.\n *\n * What it does: calculates seconds from ms duration and formats as \"0.000\".\n * How it works: divides by 1000 and calls toFixed(3).\n */\nexport function formatSeconds(ms: number): string {\n return (ms / 1000).toFixed(3);\n}\n\n/**\n * Generates standard JUnit XML string from an array of test execution summaries.\n *\n * What it does: compiles run results into standard <testsuites> / <testsuite> / <testcase> XML.\n * What it does: calculates totals for tests, failures, errors, skipped, and total duration;\n * adds <failure> or <error> child elements for failed runs.\n * How it works: stringifies structured XML with utf-8 XML declaration, adhering strictly\n * to CI tool expectations (Jenkins, GitLab CI, GitHub Actions).\n */\nexport function generateJUnitXml(suiteName: string, runs: RunSummary[]): string {\n let failures = 0;\n let errors = 0;\n let skipped = 0;\n let totalDurationMs = 0;\n\n for (const r of runs) {\n totalDurationMs += r.durationMs;\n if (r.status === 'failed') {\n failures++;\n } else if (r.status === 'interrupted') {\n errors++;\n } else if (r.status === 'cancelled') {\n skipped++;\n }\n }\n\n const testsCount = runs.length;\n const suiteTime = formatSeconds(totalDurationMs);\n const escapedSuiteName = escapeXml(suiteName);\n\n const lines: string[] = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n `<testsuites tests=\"${testsCount}\" failures=\"${failures}\" errors=\"${errors}\" skipped=\"${skipped}\" time=\"${suiteTime}\">`,\n ` <testsuite name=\"${escapedSuiteName}\" tests=\"${testsCount}\" failures=\"${failures}\" errors=\"${errors}\" skipped=\"${skipped}\" time=\"${suiteTime}\">`,\n ];\n\n for (const r of runs) {\n const escapedName = escapeXml(r.testCaseName || r.testCaseId || r.runId);\n const caseTime = formatSeconds(r.durationMs);\n\n if (r.status === 'passed') {\n lines.push(\n ` <testcase classname=\"${escapedSuiteName}\" name=\"${escapedName}\" time=\"${caseTime}\" />`,\n );\n } else if (r.status === 'failed') {\n lines.push(\n ` <testcase classname=\"${escapedSuiteName}\" name=\"${escapedName}\" time=\"${caseTime}\">`,\n );\n const msg = escapeXml(r.errorMessage || 'Test case execution failed');\n const stepInfo = r.failureStep !== undefined ? `Step ${r.failureStep} failed: ` : '';\n lines.push(` <failure message=\"${msg}\" type=\"failure\">${stepInfo}${msg}</failure>`);\n lines.push(' </testcase>');\n } else if (r.status === 'interrupted') {\n lines.push(\n ` <testcase classname=\"${escapedSuiteName}\" name=\"${escapedName}\" time=\"${caseTime}\">`,\n );\n const msg = escapeXml(r.errorMessage || 'Execution was interrupted');\n lines.push(` <error message=\"${msg}\" type=\"error\">${msg}</error>`);\n lines.push(' </testcase>');\n } else if (r.status === 'cancelled') {\n lines.push(\n ` <testcase classname=\"${escapedSuiteName}\" name=\"${escapedName}\" time=\"${caseTime}\">`,\n );\n lines.push(' <skipped message=\"Test run cancelled\" />');\n lines.push(' </testcase>');\n }\n }\n\n lines.push(' </testsuite>');\n lines.push('</testsuites>');\n return lines.join('\\n');\n}\n\n/**\n * Extracts a RunSummary from a completed RunResult and corresponding RunBundle metadata.\n *\n * What it does: parses status, timings, and failure reasons from a RunResult object.\n * How it works: scans steps for failure message and index; returns structured RunSummary.\n */\nexport function extractSummary(\n runId: string,\n testCaseId: string,\n testCaseName: string,\n result: unknown,\n): RunSummary {\n const r = (result && typeof result === 'object' ? result : {}) as {\n status?: string;\n started_at?: string;\n finished_at?: string;\n steps?: Array<{ status?: string; error?: unknown }>;\n };\n let errorMessage: string | undefined;\n let failureStep: number | undefined;\n\n if (r.status === 'failed') {\n const steps = r.steps ?? [];\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n if (step && step.status === 'failed') {\n failureStep = i + 1;\n if (typeof step.error === 'string' && step.error) {\n errorMessage = step.error;\n } else if (\n typeof step.error === 'object' &&\n step.error !== null &&\n 'message' in step.error &&\n typeof (step.error as { message?: unknown }).message === 'string'\n ) {\n errorMessage = (step.error as { message: string }).message;\n } else {\n errorMessage = 'Step assertion or execution failed';\n }\n break;\n }\n }\n if (!errorMessage) {\n errorMessage = 'Test execution failed';\n }\n }\n\n const startTime = new Date(r.started_at ?? '').getTime();\n const finishTime = new Date(r.finished_at ?? '').getTime();\n const durationMs =\n Number.isNaN(startTime) || Number.isNaN(finishTime) ? 0 : Math.max(0, finishTime - startTime);\n\n return {\n runId,\n testCaseId,\n testCaseName,\n status: r.status === 'passed' ? 'passed' : 'failed',\n durationMs,\n errorMessage,\n failureStep,\n };\n}\n", "import { RunCancelledError, type RunBundle } from './dashboard-client.js';\nimport type { Executor } from './executor.js';\nimport type { Logger } from './logger.js';\nimport type { RunnerClient } from './runner-client.js';\nimport { extractSummary, type RunSummary } from './junit.js';\n\n/**\n * Configuration options for LocalRunnerConsumer.\n *\n * What it is: typed dependency and tuning settings for the customer runner loop.\n * What it does: configures API client, browser executor, polling delays, and concurrency.\n * How it works: validated in constructor ensuring non-zero positive numbers.\n */\nexport interface LocalConsumerOptions {\n client: RunnerClient;\n executor: Executor;\n log?: Logger | undefined;\n concurrency?: number | undefined;\n heartbeatIntervalMs?: number | undefined;\n pollIntervalMs?: number | undefined;\n maxBackoffMs?: number | undefined;\n collectionRunId?: string | undefined;\n onRunFinished?: ((summary: RunSummary) => void) | undefined;\n}\n\n/**\n * Execution loop for customer-hosted replay runners.\n *\n * What it is: polling worker and execution manager for customer replay runners.\n * What it does: claims ready local runs from the public Locus API, coordinates browser replay\n * via Executor, sends periodic heartbeats to maintain execution leases, posts final results,\n * and detects cancellation events promptly.\n * How it works: operates in two modes:\n * 1. Targeted mode (collectionRunId supplied): polls claims until server responds \"finished\",\n * executes local runs, and resolves upon completion (for CI \"run\" command).\n * 2. Daemon mode (no collectionRunId): continuously polls for local tenant runs until interrupted\n * (for tester workstation \"listen\" command).\n */\nexport class LocalRunnerConsumer {\n // Public runner HTTP client for gateway calls.\n private readonly client: RunnerClient;\n // Browser step replayer and artifact recorder.\n private readonly executor: Executor;\n // Optional logger for diagnostic and lifecycle reporting.\n private readonly log?: Logger | undefined;\n // Maximum simultaneous run execution slots.\n private readonly concurrency: number;\n // Milliseconds between lease extension heartbeats.\n private readonly heartbeatIntervalMs: number;\n // Base milliseconds to sleep between empty polling attempts.\n private readonly pollIntervalMs: number;\n // Maximum backoff ceiling when polling repeatedly returns idle or errors.\n private readonly maxBackoffMs: number;\n // Optional target collection run identifier restricting execution.\n private readonly collectionRunId?: string | undefined;\n // Callback invoked whenever a run finishes replay.\n private readonly onRunFinished?: ((summary: RunSummary) => void) | undefined;\n // In-flight run execution promises occupying concurrency slots.\n private readonly inFlight = new Set<Promise<void>>();\n // Active flag controlling the polling loop lifetime.\n private running = false;\n // Callback resolving the exited promise when loop terminates.\n private resolveExited: () => void = () => undefined;\n // Promise awaiting drain of all in-flight runs and complete loop shutdown.\n private readonly exited = new Promise<void>((resolve) => {\n this.resolveExited = resolve;\n });\n // Active sleep timer for current idle backoff delay.\n private sleepTimer: NodeJS.Timeout | null = null;\n // Resolver callback for interrupting current sleep on consumer stop.\n private sleepResolve: (() => void) | null = null;\n\n /**\n * Constructs and validates LocalRunnerConsumer configuration.\n *\n * What it does: verifies non-nil client and executor, and applies permitted customer CLI defaults.\n * How it works: sets default concurrency to 1, heartbeat to 5000ms, and polling to 2000ms.\n */\n constructor(options: LocalConsumerOptions) {\n if (!options.client) {\n throw new Error('client is required for LocalRunnerConsumer');\n }\n if (!options.executor) {\n throw new Error('executor is required for LocalRunnerConsumer');\n }\n this.client = options.client;\n this.executor = options.executor;\n this.log = options.log;\n this.concurrency = options.concurrency ?? 1;\n if (this.concurrency < 1) {\n throw new Error('concurrency must be at least 1');\n }\n this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 5000;\n this.pollIntervalMs = options.pollIntervalMs ?? 2000;\n this.maxBackoffMs = options.maxBackoffMs ?? 10000;\n this.collectionRunId = options.collectionRunId;\n this.onRunFinished = options.onRunFinished;\n }\n\n /**\n * Starts the polling loop and executes local runs until finished or stopped.\n *\n * What it does: checks available slots, polls /api/v1/runner/claim, and dispatches runs.\n * How it works: when claimed, starts run in background; when idle, sleeps with linear backoff;\n * when finished (in targeted collection mode), drains in-flight runs and returns.\n */\n async start(): Promise<void> {\n this.running = true;\n let currentBackoff = this.pollIntervalMs;\n\n this.log?.info('local runner consumer started', {\n event: 'consumer_start',\n concurrency: this.concurrency,\n collectionRunId: this.collectionRunId ?? 'all_tenant_runs',\n });\n\n while (this.running) {\n try {\n const freeSlots = this.concurrency - this.inFlight.size;\n if (freeSlots < 1) {\n // All slots busy; wait for at least one in-flight run to settle before claiming next.\n await Promise.race(this.inFlight);\n continue;\n }\n\n const claimResult = await this.client.claim(this.collectionRunId);\n\n if (claimResult.status === 'claimed') {\n currentBackoff = this.pollIntervalMs;\n this.dispatch(claimResult.bundle);\n continue;\n }\n\n if (claimResult.status === 'finished') {\n this.log?.info('target collection run has completed', {\n event: 'collection_finished',\n collectionRunId: this.collectionRunId,\n });\n break;\n }\n\n // Status is idle; back off slightly before polling again.\n await this.sleep(currentBackoff);\n currentBackoff = Math.min(currentBackoff + 1000, this.maxBackoffMs);\n } catch (err: unknown) {\n if (!this.running) break;\n const msg = err instanceof Error ? err.message : String(err);\n this.log?.error('error during runner polling cycle', {\n event: 'poll_error',\n error: msg,\n });\n await this.sleep(currentBackoff);\n currentBackoff = Math.min(currentBackoff * 1.5, this.maxBackoffMs);\n }\n }\n\n // Wait for all currently executing runs to complete cleanly before exiting.\n await Promise.allSettled([...this.inFlight]);\n this.running = false;\n this.resolveExited();\n }\n\n /**\n * Requests graceful termination of the consumer and waits for running runs to drain.\n *\n * What it does: sets running flag to false, cancels idle sleep delay, and awaits the exited promise.\n * How it works: interrupts active sleep immediately; allows executing runs to complete and report.\n */\n async stop(): Promise<void> {\n if (!this.running) {\n return;\n }\n this.running = false;\n if (this.sleepTimer) {\n clearTimeout(this.sleepTimer);\n this.sleepTimer = null;\n }\n if (this.sleepResolve) {\n this.sleepResolve();\n this.sleepResolve = null;\n }\n await this.exited;\n }\n\n /**\n * Helper that sleeps for the specified number of milliseconds unless cancelled or stopped.\n *\n * What it does: promise-based delay helper holding the event loop open during idle polling.\n * How it works: wraps setTimeout in a promise and stores resolvers to permit immediate cancellation.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n this.sleepResolve = resolve;\n this.sleepTimer = setTimeout(() => {\n this.sleepTimer = null;\n this.sleepResolve = null;\n resolve();\n }, ms);\n });\n }\n\n /**\n * Dispatches a claimed run bundle into the inFlight execution pool.\n *\n * What it does: wraps processRun in tracking promises and adds to inFlight set.\n * How it works: catches unhandled exceptions, removes promise in finally, and handles cleanup.\n */\n private dispatch(bundle: RunBundle): void {\n const runId = bundle.run_id;\n const tracked: Promise<void> = this.processRun(bundle)\n .catch((err: unknown) => {\n this.log?.error('run execution failed unexpectedly', {\n event: 'run_fatal',\n runId,\n error: err instanceof Error ? err.message : String(err),\n });\n })\n .finally(() => {\n this.inFlight.delete(tracked);\n });\n\n this.inFlight.add(tracked);\n }\n\n /**\n * Executes a single claimed run from start to completion.\n *\n * What it does: starts background heartbeat timer, replays steps in browser via Executor,\n * detects cancel events, posts final RunResult payload, and invokes onRunFinished callback.\n * How it works: aborts cancel controller if heartbeat indicates cancellation; clears timer\n * in finally block; skips finish call if cancelled.\n */\n private async processRun(bundle: RunBundle): Promise<void> {\n const runId = bundle.run_id;\n const testCaseId = bundle.test_case_id;\n const testCaseName = (bundle.definition as { name?: string }).name ?? testCaseId;\n\n this.log?.info('starting replay for claimed run', {\n event: 'run_start',\n runId,\n testCaseId,\n });\n\n const cancel = new AbortController();\n\n const heartbeatTimer = setInterval(() => {\n this.client\n .heartbeat(runId)\n .then((res) => {\n if (res.cancelled) {\n this.log?.info('run cancelled via heartbeat, aborting browser execution', {\n event: 'run_cancelled',\n runId,\n });\n cancel.abort();\n }\n })\n .catch((err: unknown) => {\n if (err instanceof RunCancelledError) {\n this.log?.info('run cancelled via error response, aborting browser execution', {\n event: 'run_cancelled',\n runId,\n });\n cancel.abort();\n return;\n }\n this.log?.warn('heartbeat keepalive failed', {\n event: 'heartbeat_warn',\n runId,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n }, this.heartbeatIntervalMs);\n\n try {\n const runResult = await this.executor.execute(bundle, cancel.signal);\n\n if (cancel.signal.aborted) {\n this.log?.info('run execution was cancelled; discarding result', {\n event: 'result_discarded_cancelled',\n runId,\n });\n const startTime = new Date(runResult.started_at).getTime();\n const finishTime = new Date(runResult.finished_at).getTime();\n const durationMs =\n Number.isNaN(startTime) || Number.isNaN(finishTime)\n ? 0\n : Math.max(0, finishTime - startTime);\n const summary: RunSummary = {\n runId,\n testCaseId,\n testCaseName,\n status: 'cancelled',\n durationMs,\n };\n this.onRunFinished?.(summary);\n return;\n }\n\n this.log?.info('run execution finished, submitting result to Locus', {\n event: 'run_finish',\n runId,\n status: runResult.status,\n });\n\n await this.client.finish(runId, runResult);\n\n const summary = extractSummary(runId, testCaseId, testCaseName, runResult);\n this.onRunFinished?.(summary);\n } catch (err: unknown) {\n if (cancel.signal.aborted || err instanceof RunCancelledError) {\n this.log?.info('run cancelled during execution', {\n event: 'run_cancelled_caught',\n runId,\n });\n const summary: RunSummary = {\n runId,\n testCaseId,\n testCaseName,\n status: 'cancelled',\n durationMs: 0,\n };\n this.onRunFinished?.(summary);\n return;\n }\n\n this.log?.error('run crashed during execution', {\n event: 'run_crash',\n runId,\n error: err instanceof Error ? err.message : String(err),\n });\n\n const summary: RunSummary = {\n runId,\n testCaseId,\n testCaseName,\n status: 'interrupted',\n durationMs: 0,\n errorMessage: err instanceof Error ? err.message : String(err),\n };\n this.onRunFinished?.(summary);\n } finally {\n clearInterval(heartbeatTimer);\n }\n }\n\n /**\n * Returns whether the consumer loop is currently running.\n *\n * What it does: getter for running status.\n * How it works: returns current boolean flag.\n */\n isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Returns the count of runs currently executing in-flight.\n *\n * What it does: reports busy concurrency slots.\n * How it works: returns size of inFlight Set.\n */\n getActiveRunsCount(): number {\n return this.inFlight.size;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAEA,SAAS,cAAc,qBAAqB;AAC5C,SAAS,MAAM,eAAe;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;;;ACJ1B,IAAM,iBAAiB,OAAO,OAAO;AAGrC,IAAM,gBAAgB;AAkBf,SAAS,mBACd,WACA,UACA,iBACqB;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