chore: sync current main into the CI baseline repair
Accept the independently merged baseline fixes and retain only the reconstruction fixture coverage still missing from main. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> # Conflicts: # tests/boundary/mcp/ghidraInventoryMcp.test.ts # tests/process-global/cleanLinuxHopperRuntime.test.ts
This commit is contained in:
@@ -131,7 +131,7 @@ const browserParameters = (
|
||||
}
|
||||
const observedOrigin = browserResultTargetOrigin(result);
|
||||
const scope = {
|
||||
cdp_endpoint: input.cdp_endpoint,
|
||||
cdp_endpoint: input.cdp_endpoint.recorded,
|
||||
allowed_origins:
|
||||
input.allowed_origins.length > 0
|
||||
? input.allowed_origins
|
||||
|
||||
@@ -23,6 +23,20 @@ import type { Result } from "../../domain/result.js";
|
||||
|
||||
const target = "a".repeat(64);
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const methodName = "-[BuildViewController buildTapped:]";
|
||||
const methodSymbol = {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "user_defined",
|
||||
};
|
||||
const methodInventoryEntry = {
|
||||
address: "0x1000",
|
||||
value: methodName,
|
||||
symbol: methodSymbol,
|
||||
};
|
||||
|
||||
const evidence = [
|
||||
{
|
||||
kind: "interface_builder_resource" as const,
|
||||
@@ -258,8 +272,12 @@ describe("native UI action trace", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
it("builds the evidence path from the active app and native provider", async () => {
|
||||
const tools = new EnhancedTools(testAnalysis());
|
||||
it("builds the evidence path from provider names with declared symbol facts", async () => {
|
||||
const tools = new EnhancedTools(
|
||||
testAnalysis({
|
||||
list_names: () => execution("list_names", [methodInventoryEntry]),
|
||||
}),
|
||||
);
|
||||
const result = await tools.execute("trace_native_ui_action", {
|
||||
action: "buildTapped:",
|
||||
});
|
||||
@@ -392,18 +410,117 @@ describe("bounded native UI tracing", () => {
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("binds dispatch metadata to the active target digest", async () => {
|
||||
const result = await new EnhancedTools(testAnalysis()).execute(
|
||||
"inspect_native_dispatch_metadata",
|
||||
{ max_records: 10 },
|
||||
);
|
||||
describe("native dispatch inventory", () => {
|
||||
it.each([
|
||||
{ label: "plain value", entry: { address: "0x1000", value: methodName } },
|
||||
{ label: "value with symbol facts", entry: methodInventoryEntry },
|
||||
{
|
||||
label: "legacy name with symbol facts",
|
||||
entry: { address: "0x1000", name: methodName, symbol: methodSymbol },
|
||||
},
|
||||
])(
|
||||
"binds $label inventory to the target without overstating dispatch coverage",
|
||||
async ({ entry }) => {
|
||||
const result = await new EnhancedTools(
|
||||
testAnalysis({
|
||||
list_names: () => execution("list_names", [entry]),
|
||||
}),
|
||||
).execute("inspect_native_dispatch_metadata", { max_records: 10 });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { target_sha256: target },
|
||||
});
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
target_sha256: target,
|
||||
provider,
|
||||
result: {
|
||||
objc_dispatch_implementations: [
|
||||
{
|
||||
class_name: "BuildViewController",
|
||||
selector: "buildTapped:",
|
||||
implementation_address: "0x1000",
|
||||
decode: { status: "partial", reason: "symbol_name_only" },
|
||||
},
|
||||
],
|
||||
coverage: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
facet: "objc_dispatch_implementations",
|
||||
status: "partial",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
facet: "swift_dispatch_tables",
|
||||
status: "unsupported",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
facet: "relative_pointers",
|
||||
status: "unsupported",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "malformed symbol flag",
|
||||
entry: {
|
||||
...methodInventoryEntry,
|
||||
symbol: { ...methodSymbol, primary: "true" },
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "unknown symbol source",
|
||||
entry: {
|
||||
...methodInventoryEntry,
|
||||
symbol: { ...methodSymbol, source: "unknown" },
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "incomplete symbol",
|
||||
entry: { ...methodInventoryEntry, symbol: { primary: true } },
|
||||
},
|
||||
{
|
||||
label: "malformed legacy symbol",
|
||||
entry: { address: "0x1000", name: methodName, symbol: null },
|
||||
},
|
||||
{
|
||||
label: "malformed address",
|
||||
entry: { ...methodInventoryEntry, address: 4096 },
|
||||
},
|
||||
{
|
||||
label: "malformed value with a legacy name",
|
||||
entry: { ...methodInventoryEntry, value: 42, name: methodName },
|
||||
},
|
||||
{
|
||||
label: "undeclared field",
|
||||
entry: { address: "0x1000", value: methodName, unexpected: true },
|
||||
},
|
||||
])(
|
||||
"rejects $label inventory in both dispatch consumers",
|
||||
async ({ entry }) => {
|
||||
const tools = new EnhancedTools(
|
||||
testAnalysis({
|
||||
list_names: () => execution("list_names", [entry]),
|
||||
}),
|
||||
);
|
||||
for (const [operation, parameters] of [
|
||||
["inspect_native_dispatch_metadata", { max_records: 10 }],
|
||||
["trace_native_ui_action", { action: "buildTapped:" }],
|
||||
] as const) {
|
||||
expect(await tools.execute(operation, parameters)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisOutputError",
|
||||
operation: "list_names",
|
||||
reason: "provider returned an invalid inventory",
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("native UI query outcomes", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { addressedValue } from "../../contracts/toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
nativeDispatchMetadataResultSchema,
|
||||
inspectNativeDispatchMetadata,
|
||||
@@ -36,8 +37,11 @@ export const inspectNativeDispatch = async (
|
||||
const names = z
|
||||
.array(
|
||||
z.union([
|
||||
z.strictObject({ address: z.string(), value: z.string() }),
|
||||
z.strictObject({ address: z.string(), name: z.string() }),
|
||||
addressedValue.strict(),
|
||||
addressedValue
|
||||
.omit({ value: true })
|
||||
.extend({ name: z.string() })
|
||||
.strict(),
|
||||
]),
|
||||
)
|
||||
.safeParse(execution.value.result);
|
||||
|
||||
@@ -49,13 +49,14 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
discoverCdpEndpoint,
|
||||
hasCdpTargetWebSocket,
|
||||
type CdpEndpointDiscovery,
|
||||
type CdpEndpointTarget,
|
||||
} from "./CdpEndpoint.js";
|
||||
import {
|
||||
attachCdpTargetSession,
|
||||
closeCdpTargetSession,
|
||||
openCdpEndpoint,
|
||||
openCdpTargetSession,
|
||||
type CdpTargetSession,
|
||||
} from "./CdpTargetSession.js";
|
||||
@@ -82,11 +83,13 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<BrowserTargetList, AnalysisError>> {
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
const endpoint = await openCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"list_browser_targets",
|
||||
options.signal,
|
||||
);
|
||||
await endpoint.connection?.close();
|
||||
const { discovery } = endpoint;
|
||||
const selected = selectTargets(
|
||||
discovery,
|
||||
input.allowed_origins.length === 0
|
||||
@@ -169,45 +172,19 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
input: ObserveWebSessionInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebObservationSession, AnalysisError>> {
|
||||
let targetSession: CdpTargetSession | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"observe_web_session",
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
"observe_web_session",
|
||||
options.signal,
|
||||
);
|
||||
return ok(
|
||||
webObservationSessionSchema.parse(
|
||||
await observeCdpSession({
|
||||
connection: targetSession.connection,
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
await withTargetSession(
|
||||
input,
|
||||
"observe_web_session",
|
||||
options,
|
||||
observeCdpSession,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "observe_web_session"));
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
CLEANUP_DOMAINS,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,45 +192,19 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebMcpDiscovery, AnalysisError>> {
|
||||
let targetSession: CdpTargetSession | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"discover_webmcp_tools",
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
"discover_webmcp_tools",
|
||||
options.signal,
|
||||
);
|
||||
return ok(
|
||||
webMcpDiscoverySchema.parse(
|
||||
await discoverWebMcp({
|
||||
connection: targetSession.connection,
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
await withTargetSession(
|
||||
input,
|
||||
"discover_webmcp_tools",
|
||||
options,
|
||||
discoverWebMcp,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "discover_webmcp_tools"));
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
CLEANUP_DOMAINS,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,45 +224,19 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
input: CaptureWebScreenshotInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebScreenshot, AnalysisError>> {
|
||||
let targetSession: CdpTargetSession | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"capture_web_screenshot",
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
"capture_web_screenshot",
|
||||
options.signal,
|
||||
);
|
||||
return ok(
|
||||
webScreenshotSchema.parse(
|
||||
await captureCdpScreenshot({
|
||||
connection: targetSession.connection,
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
await withTargetSession(
|
||||
input,
|
||||
"capture_web_screenshot",
|
||||
options,
|
||||
captureCdpScreenshot,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "capture_web_screenshot"));
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
CLEANUP_DOMAINS,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,44 +261,83 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options: ExecutionOptions,
|
||||
operation: "inspect_web_page" | "analyze_web_bundle",
|
||||
): Promise<CapturedPage> {
|
||||
let targetSession: CdpTargetSession | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
operation,
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession = await openCdpTargetSession(
|
||||
discovery,
|
||||
target,
|
||||
operation,
|
||||
options.signal,
|
||||
);
|
||||
return await capturePage({
|
||||
connection: targetSession.connection,
|
||||
sessionId: targetSession.sessionId,
|
||||
operation,
|
||||
discovery,
|
||||
target,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
});
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
CLEANUP_DOMAINS,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
return await withTargetSession(
|
||||
input,
|
||||
operation,
|
||||
options,
|
||||
async (session) => await capturePage({ ...session, operation }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Facts and transport handed to one target operation. */
|
||||
interface CdpTargetOperationSession<Input> {
|
||||
readonly connection: CdpTargetSession["connection"];
|
||||
readonly sessionId: CdpTargetSession["sessionId"];
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: Input;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: NonNullable<ExecutionOptions["progress"]>;
|
||||
}
|
||||
|
||||
/** Authorize one discovered target, run work in its session, and close REA's socket. */
|
||||
const withTargetSession = async <
|
||||
Input extends Pick<
|
||||
InspectWebPageInput,
|
||||
"cdp_endpoint" | "target_id" | "allowed_origins"
|
||||
>,
|
||||
Output,
|
||||
>(
|
||||
input: Input,
|
||||
operation: BrowserObservationOperation,
|
||||
options: ExecutionOptions,
|
||||
work: (session: CdpTargetOperationSession<Input>) => Promise<Output>,
|
||||
): Promise<Output> => {
|
||||
const endpoint = await openCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
operation,
|
||||
options.signal,
|
||||
);
|
||||
let targetSession: CdpTargetSession | undefined;
|
||||
try {
|
||||
const target = authorizeTarget(endpoint.discovery, input);
|
||||
const scopedInput = scopeToTargetOrigin(input, target);
|
||||
targetSession =
|
||||
endpoint.connection === undefined
|
||||
? await openCdpTargetSession(
|
||||
endpoint.discovery,
|
||||
target,
|
||||
operation,
|
||||
options.signal,
|
||||
)
|
||||
: await attachCdpTargetSession(
|
||||
endpoint.connection,
|
||||
target,
|
||||
operation,
|
||||
options.signal,
|
||||
);
|
||||
return await work({
|
||||
connection: targetSession.connection,
|
||||
sessionId: targetSession.sessionId,
|
||||
discovery: endpoint.discovery,
|
||||
target,
|
||||
input: scopedInput,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined ? {} : { progress: options.progress }),
|
||||
});
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(
|
||||
targetSession,
|
||||
CLEANUP_DOMAINS,
|
||||
options.signal,
|
||||
);
|
||||
// An unadopted browser socket is closed here; closing is idempotent.
|
||||
await endpoint.connection?.close();
|
||||
}
|
||||
};
|
||||
|
||||
const selectTargets = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
allowedOrigins: ReadonlySet<string> | undefined,
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { BrowserObservationOperation } from "../domain/browserObservationEr
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import { urlDeclaresQueryOrFragment } from "../domain/urlComponents.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
import type { CdpConnection } from "./CdpConnection.js";
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
Browser: z.string().min(1),
|
||||
@@ -40,6 +41,26 @@ interface CdpDiscoveryResponseLimits {
|
||||
readonly timeoutMs: number;
|
||||
}
|
||||
|
||||
const browserSocketVersionSchema = z.object({
|
||||
protocolVersion: z.string().min(1),
|
||||
product: z.string().min(1),
|
||||
revision: z.string(),
|
||||
userAgent: z.string(),
|
||||
jsVersion: z.string(),
|
||||
});
|
||||
|
||||
const browserSocketTargetsSchema = z.object({
|
||||
targetInfos: z.array(
|
||||
z.object({
|
||||
targetId: z.string().min(1),
|
||||
type: z.string().min(1),
|
||||
title: z.string().default(""),
|
||||
url: z.string(),
|
||||
attached: z.boolean().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
/** Validated direct CDP WebSocket bound to one discovered page target. */
|
||||
interface CdpPageWebSocketEndpoint {
|
||||
readonly scope: "page";
|
||||
@@ -124,6 +145,88 @@ export const discoverCdpEndpoint = async (
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Run browser-socket discovery work, including its WebSocket handshake, under
|
||||
* the HTTP discovery deadline. Reaching the deadline is a timeout, not a
|
||||
* caller cancellation, so the internal abort is not carried as its cause.
|
||||
*/
|
||||
export const withCdpDiscoveryDeadline = async <T>(
|
||||
operation: BrowserObservationOperation,
|
||||
signal: AbortSignal | undefined,
|
||||
work: (deadlineSignal: AbortSignal) => Promise<T>,
|
||||
timeoutMs: number = CDP_DISCOVERY_RESPONSE_LIMITS.timeoutMs,
|
||||
): Promise<T> => {
|
||||
const deadline = new AbortController();
|
||||
const timer = setTimeout(() => deadline.abort(), timeoutMs);
|
||||
try {
|
||||
return await work(
|
||||
signal === undefined
|
||||
? deadline.signal
|
||||
: AbortSignal.any([signal, deadline.signal]),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (deadline.signal.aborted && signal?.aborted !== true)
|
||||
throw new BrowserObservationError(operation, "timeout", {
|
||||
detail: `CDP browser-socket discovery exceeded its ${String(timeoutMs)} ms deadline.`,
|
||||
});
|
||||
throw cause;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Read discovery facts over a browser socket that has no HTTP discovery.
|
||||
* Each reply is bounded by the connection's protocol message limit; callers
|
||||
* apply the discovery deadline through `signal`.
|
||||
*/
|
||||
export const discoverCdpBrowserSocket = async (
|
||||
connection: CdpConnection,
|
||||
url: string,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpEndpointDiscovery> => {
|
||||
const versionInput = await connection.send(
|
||||
"Browser.getVersion",
|
||||
{},
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
const targetsInput = await connection.send(
|
||||
"Target.getTargets",
|
||||
{},
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
const version = parseCdpEndpointValue(
|
||||
browserSocketVersionSchema,
|
||||
versionInput,
|
||||
operation,
|
||||
);
|
||||
const targets = parseCdpEndpointValue(
|
||||
browserSocketTargetsSchema,
|
||||
targetsInput,
|
||||
operation,
|
||||
);
|
||||
return {
|
||||
webSocket: { scope: "browser", url },
|
||||
version: {
|
||||
product: version.product,
|
||||
protocol_version: version.protocolVersion,
|
||||
revision: version.revision,
|
||||
user_agent: version.userAgent,
|
||||
js_version: version.jsVersion,
|
||||
},
|
||||
targets: targets.targetInfos.map((target) => ({
|
||||
id: target.targetId,
|
||||
type: target.type,
|
||||
title: sanitizeTargetTitle(target.title, target.url),
|
||||
url: target.url,
|
||||
attached: target.attached ?? null,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const sanitizeTargetTitle = (value: string, targetUrl: string): string => {
|
||||
let url: URL;
|
||||
try {
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { BrowserObservationEndpoint } from "../domain/browserObservation.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import {
|
||||
cdpTargetWebSocket,
|
||||
discoverCdpBrowserSocket,
|
||||
discoverCdpEndpoint,
|
||||
withCdpDiscoveryDeadline,
|
||||
type CdpEndpointDiscovery,
|
||||
type CdpEndpointTarget,
|
||||
} from "./CdpEndpoint.js";
|
||||
@@ -13,6 +17,59 @@ export interface CdpTargetSession {
|
||||
readonly sessionId: string | undefined;
|
||||
}
|
||||
|
||||
/** Discovery for one caller-selected endpoint and the browser socket that read it. */
|
||||
export interface CdpOpenedEndpoint {
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
/**
|
||||
* Browser socket kept for the target session, because a browser may ask
|
||||
* the user to approve each socket. HTTP discovery opens no socket.
|
||||
*/
|
||||
readonly connection: CdpConnection | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover one passive browser endpoint through its selected transport. A
|
||||
* browser socket's handshake and discovery share one discovery deadline.
|
||||
*/
|
||||
export const openCdpEndpoint = async (
|
||||
endpoint: BrowserObservationEndpoint,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
timeoutMs?: number,
|
||||
): Promise<CdpOpenedEndpoint> => {
|
||||
if (endpoint.transport === "http_discovery")
|
||||
return {
|
||||
discovery: await discoverCdpEndpoint(endpoint.url, operation, signal),
|
||||
connection: undefined,
|
||||
};
|
||||
return await withCdpDiscoveryDeadline(
|
||||
operation,
|
||||
signal,
|
||||
async (deadlineSignal) => {
|
||||
const connection = await CdpConnection.connect(
|
||||
endpoint.url,
|
||||
operation,
|
||||
deadlineSignal,
|
||||
);
|
||||
try {
|
||||
return {
|
||||
discovery: await discoverCdpBrowserSocket(
|
||||
connection,
|
||||
endpoint.url,
|
||||
operation,
|
||||
deadlineSignal,
|
||||
),
|
||||
connection,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
await connection.close();
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
};
|
||||
|
||||
/** Open one authorized target through its supported browser or page transport. */
|
||||
export const openCdpTargetSession = async (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
@@ -29,6 +86,16 @@ export const openCdpTargetSession = async (
|
||||
limits,
|
||||
);
|
||||
if (webSocket.scope === "page") return { connection, sessionId: undefined };
|
||||
return await attachCdpTargetSession(connection, target, operation, signal);
|
||||
};
|
||||
|
||||
/** Attach one target through an open browser socket, which the session then owns. */
|
||||
export const attachCdpTargetSession = async (
|
||||
connection: CdpConnection,
|
||||
target: CdpEndpointTarget,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpTargetSession> => {
|
||||
try {
|
||||
const attached = await connection.send(
|
||||
"Target.attachToTarget",
|
||||
|
||||
@@ -743,8 +743,8 @@ const originalModuleEdges = (
|
||||
check();
|
||||
const dependency = originalDependency(node);
|
||||
if (dependency === null) return;
|
||||
const { kind, specifier } = dependency;
|
||||
if (kind === "require" && t.isCallExpression(node)) {
|
||||
const { kind, specifier, requireCallee } = dependency;
|
||||
if (requireCallee !== undefined) {
|
||||
unboundRequires ??= new Set(
|
||||
analyzeParsedJavaScriptReferences(parsed, "require")
|
||||
.filter(
|
||||
@@ -756,7 +756,7 @@ const originalModuleEdges = (
|
||||
`${String(location.start.line)}:${String(location.start.column)}`,
|
||||
),
|
||||
);
|
||||
const location = node.callee.loc?.start;
|
||||
const location = requireCallee.loc?.start;
|
||||
if (
|
||||
location === undefined ||
|
||||
!unboundRequires.has(
|
||||
@@ -1039,6 +1039,7 @@ const originalDependency = (
|
||||
): {
|
||||
readonly kind: ParsedSourceMapItem["original_module_edges"][number]["kind"];
|
||||
readonly specifier: string;
|
||||
readonly requireCallee?: t.Identifier;
|
||||
} | null => {
|
||||
if (
|
||||
t.isImportDeclaration(node) ||
|
||||
@@ -1051,11 +1052,15 @@ const originalDependency = (
|
||||
if (t.isImportExpression(node) && t.isStringLiteral(node.source))
|
||||
return { kind: "dynamic_import", specifier: node.source.value };
|
||||
if (
|
||||
t.isCallExpression(node) &&
|
||||
(t.isCallExpression(node) || t.isOptionalCallExpression(node)) &&
|
||||
t.isIdentifier(node.callee, { name: "require" }) &&
|
||||
t.isStringLiteral(node.arguments[0])
|
||||
)
|
||||
return { kind: "require", specifier: node.arguments[0].value };
|
||||
return {
|
||||
kind: "require",
|
||||
specifier: node.arguments[0].value,
|
||||
requireCallee: node.callee,
|
||||
};
|
||||
// `import x = require("m")` is only legal at module top level and always
|
||||
// refers to the host loader, so it needs no unbound-`require` check. The
|
||||
// `moduleReference` is an entity name for a local alias instead, which
|
||||
|
||||
@@ -46,7 +46,9 @@ const registerWebMcp = (
|
||||
cli.command(CLI_COMMANDS.discoverWebMcpTools, {
|
||||
description: "Passively discover page-declared WebMCP tools",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
@@ -150,7 +152,9 @@ const registerScreenshot = (
|
||||
description:
|
||||
"Capture one visible page viewport within the supplied origin scope",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
|
||||
@@ -42,7 +42,9 @@ const registerTargetList = (
|
||||
description:
|
||||
"List page targets from a selected loopback CDP browser, optionally filtered by origin",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
}),
|
||||
options: z.object({ ...browserScopeOptions }),
|
||||
run: ({ args, options }) =>
|
||||
@@ -75,7 +77,9 @@ const registerPageInspection = (
|
||||
description:
|
||||
"Passively inspect one page through CDP, defaulting to its current origin",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: browserPageInspectionOptions,
|
||||
@@ -118,7 +122,9 @@ const registerBundleAnalysis = (
|
||||
description:
|
||||
"Capture and statically analyze a page bundle, defaulting to the selected target origin",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
@@ -162,7 +168,9 @@ const registerObservationSession = (
|
||||
cli.command(CLI_COMMANDS.observeWebSession, {
|
||||
description: "Observe user-driven page navigation during a chosen window",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
endpoint: z
|
||||
.string()
|
||||
.describe("Loopback CDP HTTP endpoint or browser WebSocket URL"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "incur";
|
||||
|
||||
import type { DirectAnalysis } from "../composition/directAnalysis.js";
|
||||
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
|
||||
import { createHistoricalSourceSummary } from "../domain/referenceSourceSummary.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { importReferenceSource } from "../application/ReferenceSourceImport.js";
|
||||
@@ -241,11 +242,48 @@ const registerReferenceSourceCommand = (
|
||||
.string()
|
||||
.describe("Local source directory to import as historical reference"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
options: z.object({
|
||||
detail: z
|
||||
.enum(["full", "summary"])
|
||||
.default("full")
|
||||
.describe(
|
||||
"Complete committed graph or compact historical-source summary",
|
||||
),
|
||||
outlineDepth: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.safe()
|
||||
.optional()
|
||||
.describe(
|
||||
"Summary outline path depth (default: 2; 0 omits entries); requires --detail summary",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
"import-reference-source",
|
||||
async () => {
|
||||
if (
|
||||
options.outlineDepth !== undefined &&
|
||||
options.detail !== "summary"
|
||||
)
|
||||
return {
|
||||
error: "Import failed",
|
||||
...projectAnalysisError(
|
||||
new AnalysisInputError(
|
||||
"import-reference-source",
|
||||
{ userMessage: "--outline-depth requires --detail summary" },
|
||||
[
|
||||
{
|
||||
path: ["outlineDepth"],
|
||||
reason: "invalid_value",
|
||||
message: "--outline-depth requires --detail summary",
|
||||
},
|
||||
],
|
||||
),
|
||||
),
|
||||
};
|
||||
const config = parseConfig(environment);
|
||||
if (!config.ok)
|
||||
return {
|
||||
@@ -255,6 +293,9 @@ const registerReferenceSourceCommand = (
|
||||
return runReferenceSourceImport(
|
||||
args.root,
|
||||
config.value.referenceSourcePolicy,
|
||||
options.detail === "summary"
|
||||
? (options.outlineDepth ?? 2)
|
||||
: undefined,
|
||||
);
|
||||
},
|
||||
isReferenceSourceImportCliFailure,
|
||||
@@ -265,6 +306,7 @@ const registerReferenceSourceCommand = (
|
||||
const runReferenceSourceImport = async (
|
||||
root: string,
|
||||
policy: ReferenceSourcePolicy,
|
||||
outlineDepth: number | undefined,
|
||||
): Promise<unknown> => {
|
||||
const resources = new ArtifactResourceScope();
|
||||
let outcome:
|
||||
@@ -346,7 +388,9 @@ const runReferenceSourceImport = async (
|
||||
cause: closeOutcome.cause,
|
||||
}),
|
||||
};
|
||||
return imported.value;
|
||||
return outlineDepth === undefined
|
||||
? imported.value
|
||||
: createHistoricalSourceSummary(imported.value, outlineDepth);
|
||||
};
|
||||
|
||||
const mergeReferenceSourceCleanup = (
|
||||
|
||||
+13
-4
@@ -65,12 +65,19 @@ const accessDeniedSystemCode = (
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* A `file:` URL or `scheme://` URL is not an operator-relative filesystem path.
|
||||
* One-letter prefixes stay paths so Windows drive paths resolve normally.
|
||||
*/
|
||||
const URL_REFERENCE = /^(?:file:|[A-Za-z][A-Za-z0-9+.-]+:\/\/)/iu;
|
||||
|
||||
/**
|
||||
* Resolve named string fields of CLI-supplied JSON against the operator
|
||||
* working directory. Each entry is a key path from the document root; only
|
||||
* fields holding nonblank strings are resolved, everything else passes through
|
||||
* untouched so shared schemas can reject blank paths. Shared MCP contracts reject
|
||||
* relative paths, so CLI workflows resolve operator-relative values before validation.
|
||||
* fields holding nonblank, non-URL strings are resolved, everything else passes
|
||||
* through untouched so shared schemas can reject blank paths and URLs. Shared MCP
|
||||
* contracts reject relative paths, so CLI workflows resolve operator-relative
|
||||
* values before validation.
|
||||
*/
|
||||
export const resolveCliJsonPaths = (
|
||||
value: unknown,
|
||||
@@ -94,7 +101,9 @@ const resolveJsonPath = (
|
||||
if (tail.length === 0)
|
||||
return [
|
||||
key,
|
||||
typeof entry === "string" && entry.trim().length > 0
|
||||
typeof entry === "string" &&
|
||||
entry.trim().length > 0 &&
|
||||
!URL_REFERENCE.test(entry)
|
||||
? resolve(entry)
|
||||
: entry,
|
||||
];
|
||||
|
||||
@@ -56,4 +56,38 @@ describe("CLI JSON path normalization", () => {
|
||||
});
|
||||
expect(input.browser.executable_path).toBe(" browser ");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"file:///opt/electron",
|
||||
"FILE:electron",
|
||||
"https://example.test/app",
|
||||
])("keeps URL %j distinguishable from a local path", (value) => {
|
||||
const input = {
|
||||
executable_path: value,
|
||||
application_path: resolve("/synthetic/app"),
|
||||
};
|
||||
const normalized = resolveCliJsonPaths(input, paths);
|
||||
expect(normalized).toEqual(input);
|
||||
const parsed = electronActiveObservationInputSchema.safeParse(normalized);
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("Expected URL path rejection");
|
||||
expect(parsed.error.issues).toEqual([
|
||||
expect.objectContaining({
|
||||
path: ["executable_path"],
|
||||
message: expect.stringContaining(
|
||||
"must be absolute local filesystem paths",
|
||||
),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"bin/electron",
|
||||
"release:v1/electron",
|
||||
"C:\\Electron\\electron.exe",
|
||||
])("keeps resolving local path %j", (value) => {
|
||||
expect(resolveCliJsonPaths({ executable_path: value }, paths)).toEqual({
|
||||
executable_path: resolve(value),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { evidenceSchema } from "../../domain/evidence.js";
|
||||
import { managedNativeVerificationInputSchema } from "../../domain/managed/managedNativeVerificationSchemas.js";
|
||||
|
||||
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
@@ -34,35 +35,6 @@ export const managedReconstructionReferenceInputSchema =
|
||||
static_members: evidenceSchema,
|
||||
});
|
||||
|
||||
/** Inline Evidence inputs for managed/native verification. */
|
||||
export const managedNativeVerificationReferenceInputSchema = z
|
||||
.strictObject({
|
||||
managed_boundaries: evidenceSchema,
|
||||
native_observations: z
|
||||
.array(evidenceSchema)
|
||||
.min(1)
|
||||
.describe("Native function or export Evidence records"),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
const ids = new Set<string>([input.managed_boundaries.evidence_id]);
|
||||
for (const [index, evidence] of input.native_observations.entries()) {
|
||||
if (evidence.evidence_id === input.managed_boundaries.evidence_id)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["native_observations", index],
|
||||
message:
|
||||
"Native observation Evidence must be distinct from managed boundary Evidence",
|
||||
});
|
||||
if (ids.has(evidence.evidence_id))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["native_observations", index],
|
||||
message: "Native observation Evidence IDs must be unique",
|
||||
});
|
||||
ids.add(evidence.evidence_id);
|
||||
}
|
||||
});
|
||||
|
||||
const managedApplicationGraphReferenceFacts = {} as const;
|
||||
|
||||
const managedApplicationGraphReferenceShape = z.strictObject({
|
||||
@@ -146,7 +118,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
|
||||
description:
|
||||
"Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states.",
|
||||
kind: "application",
|
||||
inputSchema: managedNativeVerificationReferenceInputSchema,
|
||||
inputSchema: managedNativeVerificationInputSchema,
|
||||
outputSchema: nativeVerificationOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { managedNativeVerificationInputSchema } from "../domain/managed/managedNativeVerificationSchemas.js";
|
||||
import { toolContract } from "./toolContracts.js";
|
||||
import { toolInputSchemaWithMetadata } from "./toolSchemaMetadata.js";
|
||||
|
||||
import { traceJavaScriptSemanticsRequestSchema } from "./javascript/applicationWorkflowInputContracts.js";
|
||||
import { JAVASCRIPT_FEATURE_TRACE_EXAMPLE } from "./javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import {
|
||||
@@ -10,7 +14,6 @@ import {
|
||||
import {
|
||||
compareManagedMembersReferenceInputSchema,
|
||||
managedApplicationGraphReferenceInputSchema,
|
||||
managedNativeVerificationReferenceInputSchema,
|
||||
} from "./managed/managedWorkflowToolContracts.js";
|
||||
|
||||
describe("workflow input contracts", () => {
|
||||
@@ -41,17 +44,6 @@ describe("workflow input contracts", () => {
|
||||
}).success,
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
managedNativeVerificationReferenceInputSchema.safeParse({
|
||||
managed_boundaries:
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
|
||||
native_observations: [
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0],
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0],
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
managedApplicationGraphReferenceInputSchema.safeParse({
|
||||
managed_artifact: MANAGED_APPLICATION_GRAPH_EXAMPLE.managed_members,
|
||||
@@ -62,4 +54,80 @@ describe("workflow input contracts", () => {
|
||||
managedApplicationGraphReferenceInputSchema.safeParse({}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "one observation reusing the boundary",
|
||||
observations: [MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries],
|
||||
issues: [
|
||||
{
|
||||
path: ["native_observations", 0],
|
||||
message:
|
||||
"Native observation Evidence must be distinct from managed boundary Evidence",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "repeated native observations",
|
||||
observations: [
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0],
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0],
|
||||
],
|
||||
issues: [
|
||||
{
|
||||
path: ["native_observations", 1],
|
||||
message: "Native observation Evidence IDs must be unique",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "repeated observations reusing the boundary",
|
||||
observations: [
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
|
||||
],
|
||||
issues: [
|
||||
{
|
||||
path: ["native_observations", 0],
|
||||
message:
|
||||
"Native observation Evidence must be distinct from managed boundary Evidence",
|
||||
},
|
||||
{
|
||||
path: ["native_observations", 1],
|
||||
message:
|
||||
"Native observation Evidence must be distinct from managed boundary Evidence",
|
||||
},
|
||||
{
|
||||
path: ["native_observations", 1],
|
||||
message: "Native observation Evidence IDs must be unique",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "distinct native observations",
|
||||
observations: MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
|
||||
issues: [],
|
||||
},
|
||||
])(
|
||||
"preserves managed/native diagnostics for $name",
|
||||
async ({ observations, issues }) => {
|
||||
const input = {
|
||||
managed_boundaries:
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
|
||||
native_observations: observations,
|
||||
};
|
||||
const contract = toolContract("verify_managed_native_boundaries");
|
||||
for (const schema of [
|
||||
managedNativeVerificationInputSchema,
|
||||
contract.inputSchema,
|
||||
toolInputSchemaWithMetadata(contract),
|
||||
]) {
|
||||
const result = await schema["~standard"].validate(input);
|
||||
expect(
|
||||
result.issues?.map(({ path, message }) => ({ path, message })) ?? [],
|
||||
).toEqual(issues);
|
||||
if (issues.length === 0) expect(result).toEqual({ value: input });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserObservationEndpointSchema,
|
||||
browserOriginSchema,
|
||||
recordedBrowserObservationEndpointSchema,
|
||||
sanitizeEndpointCandidate,
|
||||
sanitizeBrowserUrl,
|
||||
} from "./browserObservation.js";
|
||||
@@ -45,6 +47,58 @@ describe("browser observation contracts", () => {
|
||||
])
|
||||
expect(browserEndpointSchema.safeParse(value).success, value).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a loopback browser socket and records it without its identifier", () => {
|
||||
expect(
|
||||
browserObservationEndpointSchema.parse("http://127.0.0.1:9222/"),
|
||||
).toEqual({
|
||||
transport: "http_discovery",
|
||||
url: "http://127.0.0.1:9222",
|
||||
recorded: "http://127.0.0.1:9222",
|
||||
});
|
||||
expect(
|
||||
browserObservationEndpointSchema.parse(
|
||||
"ws://[::1]:9222/devtools/browser/0b1c-socket-id",
|
||||
),
|
||||
).toEqual({
|
||||
transport: "browser_websocket",
|
||||
url: "ws://[::1]:9222/devtools/browser/0b1c-socket-id",
|
||||
recorded: "ws://[::1]:9222/devtools/browser/[REDACTED]",
|
||||
});
|
||||
for (const value of [
|
||||
"ws://127.0.0.1/devtools/browser/id",
|
||||
"ws://localhost:9222/devtools/browser/id",
|
||||
"wss://127.0.0.1:9222/devtools/browser/id",
|
||||
"ws://user:pass@127.0.0.1:9222/devtools/browser/id",
|
||||
"ws://127.0.0.1:9222/devtools/browser/id?token=x",
|
||||
"ws://127.0.0.1:9222/devtools/browser/id#fragment",
|
||||
"ws://127.0.0.1:9222/devtools/browser/id?",
|
||||
"ws://127.0.0.1:9222/devtools/browser/id#",
|
||||
"ws://127.0.0.1:9222/devtools/browser/",
|
||||
"ws://127.0.0.1:9222/devtools/browser/id/extra",
|
||||
"ws://127.0.0.1:9222/devtools/page/id",
|
||||
])
|
||||
expect(
|
||||
browserObservationEndpointSchema.safeParse(value).success,
|
||||
value,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts recorded browser sockets only in their redacted form", () => {
|
||||
for (const value of [
|
||||
"http://127.0.0.1:9222",
|
||||
"ws://127.0.0.1:9222/devtools/browser/[REDACTED]",
|
||||
])
|
||||
expect(
|
||||
recordedBrowserObservationEndpointSchema.safeParse(value).success,
|
||||
value,
|
||||
).toBe(true);
|
||||
expect(
|
||||
recordedBrowserObservationEndpointSchema.safeParse(
|
||||
"ws://127.0.0.1:9222/devtools/browser/0b1c-socket-id",
|
||||
).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser observation sensitive surfaces and retention", () => {
|
||||
|
||||
@@ -43,46 +43,125 @@ export const browserOriginSchema = z
|
||||
export const isLiteralLoopbackHostname = (hostname: string): boolean =>
|
||||
hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
||||
|
||||
const HTTP_ENDPOINT_MESSAGE =
|
||||
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1";
|
||||
const BROWSER_SOCKET_PATH = "/devtools/browser/";
|
||||
const REDACTED_BROWSER_SOCKET_PATH = `${BROWSER_SOCKET_PATH}[REDACTED]`;
|
||||
|
||||
/** Normalized origin of an accepted loopback CDP HTTP discovery endpoint. */
|
||||
const httpDiscoveryOrigin = (url: URL): string | undefined =>
|
||||
url.protocol === "http:" &&
|
||||
isLiteralLoopbackHostname(url.hostname) &&
|
||||
url.port !== "" &&
|
||||
url.username === "" &&
|
||||
url.password === "" &&
|
||||
url.pathname === "/" &&
|
||||
!urlDeclaresQueryOrFragment(url)
|
||||
? url.origin
|
||||
: undefined;
|
||||
|
||||
/** Scheme and authority of an accepted loopback CDP browser WebSocket. */
|
||||
const browserSocketAuthority = (url: URL): string | undefined => {
|
||||
const id = url.pathname.slice(BROWSER_SOCKET_PATH.length);
|
||||
return url.protocol === "ws:" &&
|
||||
isLiteralLoopbackHostname(url.hostname) &&
|
||||
url.port !== "" &&
|
||||
url.username === "" &&
|
||||
url.password === "" &&
|
||||
!urlDeclaresQueryOrFragment(url) &&
|
||||
url.pathname.startsWith(BROWSER_SOCKET_PATH) &&
|
||||
id.length > 0 &&
|
||||
!id.includes("/")
|
||||
? `${url.protocol}//${url.host}`
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/** Loopback-only HTTP endpoint accepted for a user-owned CDP browser. */
|
||||
export const browserEndpointSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.transform((value, context) => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch (cause: unknown) {
|
||||
// Invalid input is reported through the zod issue.
|
||||
void cause;
|
||||
const url = URL.parse(value);
|
||||
const origin = url === null ? undefined : httpDiscoveryOrigin(url);
|
||||
if (origin !== undefined) return origin;
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
url === null ? "Invalid CDP endpoint URL" : HTTP_ENDPOINT_MESSAGE,
|
||||
});
|
||||
return z.NEVER;
|
||||
});
|
||||
|
||||
/**
|
||||
* Caller-selected endpoint for passive browser observation. A browser socket
|
||||
* skips HTTP discovery; its identifier gates access, so `recorded` omits it.
|
||||
*/
|
||||
export interface BrowserObservationEndpoint {
|
||||
readonly transport: "http_discovery" | "browser_websocket";
|
||||
readonly url: string;
|
||||
readonly recorded: string;
|
||||
}
|
||||
|
||||
/** Loopback CDP HTTP discovery origin or browser WebSocket URL. */
|
||||
export const browserObservationEndpointSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Literal loopback CDP endpoint: http://127.0.0.1:PORT, or ws://127.0.0.1:PORT/devtools/browser/ID.",
|
||||
)
|
||||
.transform((value, context): BrowserObservationEndpoint => {
|
||||
const url = URL.parse(value);
|
||||
if (url === null) {
|
||||
context.addIssue({ code: "custom", message: "Invalid CDP endpoint URL" });
|
||||
return z.NEVER;
|
||||
}
|
||||
if (
|
||||
url.protocol !== "http:" ||
|
||||
!isLiteralLoopbackHostname(url.hostname) ||
|
||||
url.port === "" ||
|
||||
url.username !== "" ||
|
||||
url.password !== "" ||
|
||||
url.pathname !== "/" ||
|
||||
urlDeclaresQueryOrFragment(url)
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1",
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return url.origin;
|
||||
const origin = httpDiscoveryOrigin(url);
|
||||
if (origin !== undefined)
|
||||
return { transport: "http_discovery", url: origin, recorded: origin };
|
||||
const authority = browserSocketAuthority(url);
|
||||
if (authority !== undefined)
|
||||
return {
|
||||
transport: "browser_websocket",
|
||||
url: url.href,
|
||||
recorded: `${authority}${REDACTED_BROWSER_SOCKET_PATH}`,
|
||||
};
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
url.protocol === "ws:"
|
||||
? "CDP browser WebSocket must be ws://127.0.0.1:PORT/devtools/browser/ID or ws://[::1]:PORT/devtools/browser/ID"
|
||||
: HTTP_ENDPOINT_MESSAGE,
|
||||
});
|
||||
return z.NEVER;
|
||||
});
|
||||
|
||||
/** Evidence form of a passive browser endpoint, with any socket identifier redacted. */
|
||||
export const recordedBrowserObservationEndpointSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
(value) => {
|
||||
const url = URL.parse(value);
|
||||
return (
|
||||
url !== null &&
|
||||
(httpDiscoveryOrigin(url) !== undefined ||
|
||||
(browserSocketAuthority(url) !== undefined &&
|
||||
url.pathname === REDACTED_BROWSER_SOCKET_PATH))
|
||||
);
|
||||
},
|
||||
{
|
||||
message:
|
||||
"Recorded CDP endpoint must be a loopback HTTP origin or a redacted browser WebSocket URL",
|
||||
},
|
||||
);
|
||||
|
||||
export const browserAllowedOriginsSchema = z
|
||||
.array(browserOriginSchema)
|
||||
.transform((origins) => Array.from(new Set(origins)).sort())
|
||||
.default([]);
|
||||
|
||||
const browserInput = {
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
cdp_endpoint: browserObservationEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
};
|
||||
|
||||
|
||||
@@ -2,14 +2,14 @@ import { z } from "zod";
|
||||
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
browserObservationEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import { browserVersionSchema } from "./browserObservationSchemas.js";
|
||||
|
||||
/** Input for a navigation-aware browser observation window. */
|
||||
export const observeWebSessionInputSchema = z.strictObject({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
cdp_endpoint: browserObservationEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1),
|
||||
observation_ms: z.number().int().min(1).default(10_000),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
recordedBrowserObservationEndpointSchema,
|
||||
} from "../browserObservation.js";
|
||||
import {
|
||||
webPageInspectionSchema,
|
||||
@@ -424,14 +425,17 @@ const assertRuntimeParameters = (
|
||||
): void => {
|
||||
const common = {
|
||||
target_id: z.string().trim().min(1),
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
include_script_sources: z.boolean(),
|
||||
};
|
||||
if (expected.kind === "browser") {
|
||||
const parameters = parseAtPath(
|
||||
(value) =>
|
||||
z
|
||||
.object({ ...common, allowed_origins: browserAllowedOriginsSchema })
|
||||
.object({
|
||||
...common,
|
||||
cdp_endpoint: recordedBrowserObservationEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
})
|
||||
.passthrough()
|
||||
.parse(value),
|
||||
evidence.parameters,
|
||||
@@ -455,7 +459,11 @@ const assertRuntimeParameters = (
|
||||
return;
|
||||
}
|
||||
const parameters = parseAtPath(
|
||||
(value) => z.object(common).passthrough().parse(value),
|
||||
(value) =>
|
||||
z
|
||||
.object({ ...common, cdp_endpoint: browserEndpointSchema })
|
||||
.passthrough()
|
||||
.parse(value),
|
||||
evidence.parameters,
|
||||
[...path, "parameters"],
|
||||
);
|
||||
|
||||
@@ -92,7 +92,10 @@ export type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
|
||||
export const managedNativeVerificationInputSchema = z
|
||||
.strictObject({
|
||||
managed_boundaries: evidenceSchema,
|
||||
native_observations: z.array(evidenceSchema).min(1),
|
||||
native_observations: z
|
||||
.array(evidenceSchema)
|
||||
.min(1)
|
||||
.describe("Native function or export Evidence records"),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
const ids = new Set<string>();
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createHistoricalSourceGraph,
|
||||
createHistoricalSourceManifest,
|
||||
type HistoricalSourceGraphInput,
|
||||
} from "./referenceSourceGraph.js";
|
||||
import { createHistoricalSourceSummary } from "./referenceSourceSummary.js";
|
||||
|
||||
const input = (
|
||||
entries: HistoricalSourceGraphInput["entries"],
|
||||
): HistoricalSourceGraphInput => ({
|
||||
schema: "HistoricalSourceGraph",
|
||||
authority: "historical-reference",
|
||||
root_alias: "$REFERENCE_ROOT",
|
||||
inventory_state: "unknown",
|
||||
entries,
|
||||
relationships: [],
|
||||
parse_failures: [],
|
||||
exclusions: [],
|
||||
languages: [],
|
||||
manifests: [],
|
||||
vcs: null,
|
||||
provenance: { importer: "fixture", importer_version: null, caller: "test" },
|
||||
limitations: ["Inventory coverage is unknown"],
|
||||
});
|
||||
|
||||
describe("committed historical-source summaries", () => {
|
||||
it("preserves unknown coverage, sizes, directories and missing symlinks without mutating the graph", () => {
|
||||
const graph = createHistoricalSourceGraph(
|
||||
input([
|
||||
{
|
||||
path: "a",
|
||||
kind: "directory",
|
||||
tree_state: "unknown",
|
||||
classifications: ["unknown"],
|
||||
limitations: ["Not enumerated"],
|
||||
},
|
||||
{
|
||||
path: "b",
|
||||
kind: "file",
|
||||
sha256: null,
|
||||
size: null,
|
||||
content_state: "unreadable",
|
||||
language: null,
|
||||
classifications: ["unknown"],
|
||||
limitations: ["Not readable"],
|
||||
},
|
||||
{
|
||||
path: "c",
|
||||
kind: "symlink",
|
||||
target: "missing",
|
||||
target_state: "missing",
|
||||
classifications: ["unknown"],
|
||||
limitations: [],
|
||||
},
|
||||
]),
|
||||
);
|
||||
const original = structuredClone(graph);
|
||||
const summary = createHistoricalSourceSummary(graph, 1);
|
||||
expect(summary).toMatchObject({
|
||||
manifest: createHistoricalSourceManifest(original),
|
||||
inventory_state: "unknown",
|
||||
vcs: null,
|
||||
provenance: original.provenance,
|
||||
file_sizes: { known_bytes: "0", unknown_file_count: 1 },
|
||||
counts: { entries: 3, files: 1, directories: 1, symlinks: 1 },
|
||||
directory_tree_states: { unknown: 1, enumerated: 0 },
|
||||
file_content_states: { unreadable: 1, hashed: 0 },
|
||||
limitations: original.limitations,
|
||||
outline: {
|
||||
entries: [
|
||||
original.entries[0],
|
||||
expect.objectContaining({ size: null, content_state: "unreadable" }),
|
||||
original.entries[2],
|
||||
],
|
||||
omitted_entry_count: 0,
|
||||
},
|
||||
});
|
||||
expect(summary.outline.entries[1]).not.toHaveProperty("sha256");
|
||||
expect(graph).toEqual(original);
|
||||
});
|
||||
|
||||
it("sums known bytes losslessly beyond the JSON safe integer range", () => {
|
||||
const graph = createHistoricalSourceGraph(
|
||||
input(
|
||||
["a", "b"].map((path) => ({
|
||||
path,
|
||||
kind: "file",
|
||||
sha256: "a".repeat(64),
|
||||
size: Number.MAX_SAFE_INTEGER,
|
||||
content_state: "hashed",
|
||||
language: null,
|
||||
classifications: ["unknown"],
|
||||
limitations: [],
|
||||
})),
|
||||
),
|
||||
);
|
||||
expect(createHistoricalSourceSummary(graph, 0)).toMatchObject({
|
||||
file_sizes: { known_bytes: "18014398509481982", unknown_file_count: 0 },
|
||||
outline: { entries: [], omitted_entry_count: 2 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
createHistoricalSourceManifest,
|
||||
type HistoricalSourceGraph,
|
||||
} from "./referenceSourceGraph.js";
|
||||
|
||||
type Entry = HistoricalSourceGraph["entries"][number];
|
||||
|
||||
const outlineEntry = (entry: Entry) => {
|
||||
if (entry.kind !== "file") return entry;
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: entry.kind,
|
||||
language: entry.language,
|
||||
size: entry.size,
|
||||
content_state: entry.content_state,
|
||||
classifications: entry.classifications,
|
||||
limitations: entry.limitations,
|
||||
};
|
||||
};
|
||||
|
||||
/** Project one committed inventory without rereading or reinterpreting source. */
|
||||
export const createHistoricalSourceSummary = (
|
||||
graph: HistoricalSourceGraph,
|
||||
outlineDepth: number,
|
||||
) => {
|
||||
const manifest = createHistoricalSourceManifest(graph);
|
||||
const counts = {
|
||||
entries: graph.entries.length,
|
||||
files: 0,
|
||||
directories: 0,
|
||||
symlinks: 0,
|
||||
relationships: graph.relationships.length,
|
||||
parse_failures: graph.parse_failures.length,
|
||||
exclusions: graph.exclusions.length,
|
||||
};
|
||||
const contentStates = {
|
||||
hashed: 0,
|
||||
"redacted-secret": 0,
|
||||
excluded: 0,
|
||||
unreadable: 0,
|
||||
unknown: 0,
|
||||
};
|
||||
const treeStates = {
|
||||
enumerated: 0,
|
||||
partial: 0,
|
||||
excluded: 0,
|
||||
unreadable: 0,
|
||||
unknown: 0,
|
||||
};
|
||||
let knownBytes = 0n;
|
||||
let unknownSizeFiles = 0;
|
||||
const outline: ReturnType<typeof outlineEntry>[] = [];
|
||||
for (const entry of graph.entries) {
|
||||
if (entry.kind === "file") {
|
||||
counts.files += 1;
|
||||
contentStates[entry.content_state] += 1;
|
||||
if (entry.size === null) unknownSizeFiles += 1;
|
||||
else knownBytes += BigInt(entry.size);
|
||||
} else if (entry.kind === "directory") {
|
||||
counts.directories += 1;
|
||||
treeStates[entry.tree_state] += 1;
|
||||
} else counts.symlinks += 1;
|
||||
// Canonical entries already use Unicode code-point order; filtering preserves it.
|
||||
if (entry.path.split("/").length <= outlineDepth)
|
||||
outline.push(outlineEntry(entry));
|
||||
}
|
||||
return {
|
||||
schema: "HistoricalSourceSummary" as const,
|
||||
authority: graph.authority,
|
||||
root_alias: graph.root_alias,
|
||||
manifest,
|
||||
inventory_state: graph.inventory_state,
|
||||
provenance: graph.provenance,
|
||||
vcs: graph.vcs,
|
||||
languages: graph.languages,
|
||||
manifests: graph.manifests,
|
||||
counts,
|
||||
file_content_states: contentStates,
|
||||
directory_tree_states: treeStates,
|
||||
file_sizes: {
|
||||
// Decimal text keeps large totals exact; this covers only known inventoried sizes.
|
||||
known_bytes: knownBytes.toString(),
|
||||
unknown_file_count: unknownSizeFiles,
|
||||
},
|
||||
exclusions: graph.exclusions,
|
||||
limitations: graph.limitations,
|
||||
outline: {
|
||||
depth: outlineDepth,
|
||||
entries: outline,
|
||||
omitted_entry_count: graph.entries.length - outline.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
browserObservationEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
import { browserVersionSchema } from "./browserObservationSchemas.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
@@ -11,7 +11,7 @@ import { digestSchema, prefixedDigestSchema } from "./../domain/digests.js";
|
||||
|
||||
/** Input for passive discovery of page-registered WebMCP tools. */
|
||||
export const discoverWebMcpToolsInputSchema = z.strictObject({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
cdp_endpoint: browserObservationEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1),
|
||||
observation_ms: z.number().int().min(0).default(100),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { z } from "zod";
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
browserObservationEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
import { browserVersionSchema } from "./browserObservationSchemas.js";
|
||||
|
||||
@@ -34,7 +34,7 @@ export type WebScreenshotArtifact = z.infer<typeof webScreenshotArtifactSchema>;
|
||||
|
||||
/** Input for one read-only visible-viewport screenshot. */
|
||||
export const captureWebScreenshotInputSchema = z.strictObject({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
cdp_endpoint: browserObservationEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
@@ -266,6 +266,11 @@ const normalizeMacho = (
|
||||
]),
|
||||
exports: covered(exports, false, [
|
||||
"Merged nm/dyld_info results may be incomplete for stripped binaries.",
|
||||
...(dyldExports.some(({ sourceSymbol }) => sourceSymbol !== undefined)
|
||||
? [
|
||||
"Renamed re-exports are listed under their exported name; the source library's symbol name is not reported.",
|
||||
]
|
||||
: []),
|
||||
]),
|
||||
segments: covered(
|
||||
load.segments.map((segment) => ({
|
||||
|
||||
@@ -4,6 +4,8 @@ interface ParsedDyldSymbol {
|
||||
readonly weak: boolean | null;
|
||||
readonly reexport: boolean | null;
|
||||
readonly source: string | null;
|
||||
/** The source library's name for a symbol it re-exports under another name. */
|
||||
readonly sourceSymbol?: string;
|
||||
}
|
||||
|
||||
/** Decode Apple dyld inventory rows, projecting export offsets to VM addresses. */
|
||||
@@ -33,15 +35,23 @@ export const parseDyldSymbols = (
|
||||
];
|
||||
return [];
|
||||
}
|
||||
const reexport = /^\[re-export\]\s+(.+?)(?:\s+\(from (.+)\))?$/u.exec(line);
|
||||
if (reexport?.[1] !== undefined)
|
||||
// dyld_info prints `_sym (from lib)`, or `_new (_old from lib)` when the
|
||||
// source library names the symbol differently. Split the trailing
|
||||
// parenthesized suffix with string scans so a library path containing
|
||||
// " from ", or a source symbol containing parentheses such as
|
||||
// `operator()`, cannot pull the match into nested lazy quantifiers.
|
||||
const reexport = parseReexportRow(line, knownExportNames);
|
||||
if (reexport !== null)
|
||||
return [
|
||||
{
|
||||
name: reexport[1],
|
||||
name: reexport.name,
|
||||
address: null,
|
||||
weak: null,
|
||||
reexport: true,
|
||||
source: reexport[2] ?? null,
|
||||
source: reexport.source,
|
||||
...(reexport.sourceSymbol === undefined
|
||||
? {}
|
||||
: { sourceSymbol: reexport.sourceSymbol }),
|
||||
},
|
||||
];
|
||||
const exported = /^(0x[\da-f]+)\s+(.+?)(?:\s+\[([^\]]+)\])?$/iu.exec(line);
|
||||
@@ -78,3 +88,70 @@ export const parseDyldSymbols = (
|
||||
|
||||
const canonicalHex = (value: string | undefined): string | null =>
|
||||
value === undefined ? null : `0x${BigInt(value).toString(16)}`;
|
||||
|
||||
interface ReexportRow {
|
||||
readonly name: string;
|
||||
readonly source: string | null;
|
||||
readonly sourceSymbol?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a `[re-export]` row without nested lazy quantifiers.
|
||||
*
|
||||
* Returns null when the line is not a re-export row so callers fall through
|
||||
* to the plain export parser. Known names disambiguate nested parentheses;
|
||||
* when that inventory is incomplete, retain the suffix-based fallback.
|
||||
*/
|
||||
const parseReexportRow = (
|
||||
line: string,
|
||||
knownNames: ReadonlySet<string>,
|
||||
): ReexportRow | null => {
|
||||
const prefix = /^\[re-export\]\s+/u.exec(line);
|
||||
if (prefix === null) return null;
|
||||
const rest = line.slice(prefix[0].length);
|
||||
if (rest.length === 0) return null;
|
||||
if (!rest.endsWith(")")) return { name: rest, source: null };
|
||||
const candidates: ReexportRow[] = [];
|
||||
for (const match of rest.matchAll(/\s+\(/gu)) {
|
||||
const name = rest.slice(0, match.index);
|
||||
if (!knownNames.has(name)) continue;
|
||||
const parsed = reexportSuffix(
|
||||
name,
|
||||
rest.slice(match.index + match[0].length, -1),
|
||||
);
|
||||
if (parsed !== null) candidates.push(parsed);
|
||||
}
|
||||
// Exact nm identities establish a boundary even when names contain parentheses.
|
||||
// Competing known interpretations remain unknown rather than creating a new name.
|
||||
if (candidates.length > 0)
|
||||
return candidates.length === 1 ? candidates[0]! : null;
|
||||
if (knownNames.has(rest)) return { name: rest, source: null };
|
||||
let depth = 0;
|
||||
for (let index = rest.length - 1; index >= 0; index--) {
|
||||
if (rest[index] === ")") depth++;
|
||||
else if (rest[index] === "(" && --depth === 0) {
|
||||
if (index === 0 || !/\s/u.test(rest[index - 1]!)) break;
|
||||
const name = rest.slice(0, index).trimEnd();
|
||||
return (
|
||||
reexportSuffix(name, rest.slice(index + 1, -1)) ?? {
|
||||
name: rest,
|
||||
source: null,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
return { name: rest, source: null };
|
||||
};
|
||||
|
||||
const reexportSuffix = (name: string, inner: string): ReexportRow | null => {
|
||||
if (name.length === 0) return null;
|
||||
if (inner.startsWith("from ") && inner.length > 5)
|
||||
return { name, source: inner.slice(5) };
|
||||
const separator = /\s+from /u.exec(inner);
|
||||
if (separator === null) return null;
|
||||
const sourceSymbol = inner.slice(0, separator.index);
|
||||
const source = inner.slice(separator.index + separator[0].length);
|
||||
return sourceSymbol.length > 0 && source.length > 0
|
||||
? { name, source, sourceSymbol }
|
||||
: null;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user