mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(javascript): index feature, semantic, IPC, and source map lookups (#13319)
perf(javascript): eliminate double preload AST pass and index feature/semantic/IPC/sourcemap lookups
This commit is contained in:
1 parent
79887f7a3b
commit
fde2c87b86
17 files changed
+1860
-535
No files matched your search
@@ -67,21 +67,12 @@ export const createElectronIpcContext = (
|
||||
const owners = new Map(
|
||||
records.map((record) => [record.key, applicationOwner(record.file)]),
|
||||
);
|
||||
const handlers = records.filter(isMainHandler);
|
||||
const handlerIndex = indexMainHandlers(records);
|
||||
const states: ElectronIpcPairingState[] = records
|
||||
.filter(isPairableRendererTransmission)
|
||||
.map((transmission) => {
|
||||
const owner = owners.get(transmission.key);
|
||||
const channel = transmission.finding.channel;
|
||||
const matching =
|
||||
channel === null
|
||||
? []
|
||||
: handlers.filter(
|
||||
(handler) =>
|
||||
(handler.finding.channel === channel ||
|
||||
mayReceiveChannel(handler, channel)) &&
|
||||
compatibleIpcModes(transmission.finding, handler.finding),
|
||||
);
|
||||
const matching = matchingMainHandlers(handlerIndex, transmission.finding);
|
||||
const candidates = matching.filter(
|
||||
(handler) => owners.get(handler.key) === owner,
|
||||
);
|
||||
@@ -127,6 +118,84 @@ export const createElectronIpcContext = (
|
||||
return { records, owners, states, pairings };
|
||||
};
|
||||
|
||||
interface MainHandlerIndex {
|
||||
readonly exactByChannel: ReadonlyMap<string, readonly ElectronIpcRecord[]>;
|
||||
readonly guardedByChannel: ReadonlyMap<string, readonly ElectronIpcRecord[]>;
|
||||
readonly wildcardDynamic: readonly ElectronIpcRecord[];
|
||||
}
|
||||
|
||||
const pushRecordBucket = (
|
||||
map: Map<string, ElectronIpcRecord[]>,
|
||||
key: string,
|
||||
record: ElectronIpcRecord,
|
||||
): void => {
|
||||
const bucket = map.get(key);
|
||||
if (bucket === undefined) map.set(key, [record]);
|
||||
else bucket.push(record);
|
||||
};
|
||||
|
||||
/**
|
||||
* Index main handlers by literal channel, guarded literal invocation channels,
|
||||
* or wildcard dynamic receivers. An unresolved channel may receive any literal
|
||||
* channel, so it competes without ever pairing; a wrapper site whose
|
||||
* invocations all supplied literal channels is represented by their findings,
|
||||
* except guarded invocations, which still compete for their own channels.
|
||||
*/
|
||||
const indexMainHandlers = (
|
||||
records: readonly ElectronIpcRecord[],
|
||||
): MainHandlerIndex => {
|
||||
const exactByChannel = new Map<string, ElectronIpcRecord[]>();
|
||||
const guardedByChannel = new Map<string, ElectronIpcRecord[]>();
|
||||
const wildcardDynamic: ElectronIpcRecord[] = [];
|
||||
for (const record of records) {
|
||||
if (!isMainHandler(record)) continue;
|
||||
const { finding } = record;
|
||||
if (finding.channel !== null) {
|
||||
pushRecordBucket(exactByChannel, finding.channel, record);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
finding.receiver === undefined &&
|
||||
finding.invocation_channels === "literal"
|
||||
) {
|
||||
for (const channel of new Set(finding.guarded_invocation_channels ?? []))
|
||||
pushRecordBucket(guardedByChannel, channel, record);
|
||||
continue;
|
||||
}
|
||||
wildcardDynamic.push(record);
|
||||
}
|
||||
return { exactByChannel, guardedByChannel, wildcardDynamic };
|
||||
};
|
||||
|
||||
const matchingMainHandlers = (
|
||||
index: MainHandlerIndex,
|
||||
transmission: ElectronIpcFinding,
|
||||
): ElectronIpcRecord[] => {
|
||||
const channel = transmission.channel;
|
||||
if (channel === null) return [];
|
||||
const exact = index.exactByChannel.get(channel);
|
||||
const guarded = index.guardedByChannel.get(channel);
|
||||
const wildcard = index.wildcardDynamic;
|
||||
const matching: ElectronIpcRecord[] = [];
|
||||
let buckets = 0;
|
||||
for (const list of [exact, guarded, wildcard]) {
|
||||
if (list === undefined || list.length === 0) continue;
|
||||
let addedFromList = false;
|
||||
for (const handler of list) {
|
||||
if (!compatibleIpcModes(transmission, handler.finding)) continue;
|
||||
matching.push(handler);
|
||||
addedFromList = true;
|
||||
}
|
||||
if (addedFromList) buckets += 1;
|
||||
}
|
||||
// Each individual bucket preserves `records` order; sort only when merging multiple buckets.
|
||||
if (buckets > 1)
|
||||
matching.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.key, right.key),
|
||||
);
|
||||
return matching;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether one analyzed source loads an Electron module.
|
||||
*
|
||||
@@ -412,21 +481,6 @@ const isRendererTransmission = ({ finding }: ElectronIpcRecord): boolean =>
|
||||
const isPairableRendererTransmission = (record: ElectronIpcRecord): boolean =>
|
||||
isRendererTransmission(record) && record.finding.operation !== "send-to-host";
|
||||
|
||||
/**
|
||||
* An unresolved channel may receive any literal channel, so it competes without
|
||||
* ever pairing. A wrapper site whose invocations all supplied literal channels
|
||||
* is represented by their findings, except guarded invocations, which have none
|
||||
* and still compete for their own channels.
|
||||
*/
|
||||
const mayReceiveChannel = (
|
||||
{ finding }: ElectronIpcRecord,
|
||||
channel: string,
|
||||
): boolean =>
|
||||
finding.channel === null &&
|
||||
(finding.receiver !== undefined ||
|
||||
finding.invocation_channels !== "literal" ||
|
||||
finding.guarded_invocation_channels?.includes(channel) === true);
|
||||
|
||||
/** Only an ipcMain registration on the same literal channel can be paired. */
|
||||
const isExactIpcHandler = (handler: ElectronIpcRecord | undefined): boolean =>
|
||||
handler !== undefined &&
|
||||
|
||||
@@ -150,6 +150,7 @@ export const addElectronCallPaths = (
|
||||
projected.push({ file, path, coverage, nodes });
|
||||
}
|
||||
}
|
||||
const projectedByKey = indexProjectedPaths(projected);
|
||||
const wrapperCandidates = [
|
||||
...ipc.pairings.map((pairing) => ({ ...pairing, coverageLimited: false })),
|
||||
...ipc.states.flatMap(({ transmission, coverageLimitedCandidate }) =>
|
||||
@@ -165,11 +166,15 @@ export const addElectronCallPaths = (
|
||||
),
|
||||
];
|
||||
for (const { transmission, handler, coverageLimited } of wrapperCandidates) {
|
||||
const sources = projected.filter(
|
||||
(p) => p.path.entry_kind === "bridge-member" && matches(p, transmission),
|
||||
const sources = lookupProjectedPaths(
|
||||
projectedByKey,
|
||||
"bridge-member",
|
||||
transmission,
|
||||
);
|
||||
const targets = projected.filter(
|
||||
(p) => p.path.entry_kind === "ipc-handler" && matches(p, handler),
|
||||
const targets = lookupProjectedPaths(
|
||||
projectedByKey,
|
||||
"ipc-handler",
|
||||
handler,
|
||||
);
|
||||
for (const from of sources)
|
||||
for (const to of targets) {
|
||||
@@ -213,6 +218,55 @@ export const addElectronCallPaths = (
|
||||
}
|
||||
};
|
||||
|
||||
type ProjectedPathIndex = Readonly<
|
||||
Record<
|
||||
"bridge-member" | "ipc-handler",
|
||||
ReadonlyMap<string, ReadonlyMap<string, readonly ProjectedPath[]>>
|
||||
>
|
||||
>;
|
||||
|
||||
const indexProjectedPaths = (
|
||||
projected: readonly ProjectedPath[],
|
||||
): ProjectedPathIndex => {
|
||||
const indexed: Record<
|
||||
"bridge-member" | "ipc-handler",
|
||||
Map<string, Map<string, ProjectedPath[]>>
|
||||
> = {
|
||||
"bridge-member": new Map(),
|
||||
"ipc-handler": new Map(),
|
||||
};
|
||||
for (const entry of projected) {
|
||||
const { entry_kind: entryKind, channel } = entry.path;
|
||||
if (
|
||||
channel === null ||
|
||||
(entryKind !== "bridge-member" && entryKind !== "ipc-handler")
|
||||
)
|
||||
continue;
|
||||
let byChannel = indexed[entryKind].get(entry.file.path);
|
||||
if (byChannel === undefined) {
|
||||
byChannel = new Map();
|
||||
indexed[entryKind].set(entry.file.path, byChannel);
|
||||
}
|
||||
const bucket = byChannel.get(channel);
|
||||
if (bucket === undefined) byChannel.set(channel, [entry]);
|
||||
else bucket.push(entry);
|
||||
}
|
||||
return indexed;
|
||||
};
|
||||
|
||||
const lookupProjectedPaths = (
|
||||
indexed: ProjectedPathIndex,
|
||||
entryKind: "bridge-member" | "ipc-handler",
|
||||
record: ElectronIpcRecord,
|
||||
): ProjectedPath[] => {
|
||||
const channel = record.finding.channel;
|
||||
if (channel === null) return [];
|
||||
const candidates = indexed[entryKind].get(record.file.path)?.get(channel);
|
||||
return candidates === undefined
|
||||
? []
|
||||
: candidates.filter((entry) => matches(entry, record));
|
||||
};
|
||||
|
||||
const matches = (
|
||||
projected: ProjectedPath,
|
||||
record: ElectronIpcRecord,
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import {
|
||||
canBorrowParsedJsonSnapshot,
|
||||
freezeJsonSnapshot,
|
||||
immutableJsonSnapshotMember,
|
||||
isImmutableJsonSnapshot,
|
||||
} from "../../domain/immutableJson.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_PROVIDER,
|
||||
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
@@ -125,41 +132,70 @@ export const parseApplicationGraphEvidence = (
|
||||
const evidence = parseEvidenceInput(input);
|
||||
const owned = ownedApplicationSources.get(evidence);
|
||||
if (owned !== undefined) return owned;
|
||||
const immutable =
|
||||
isImmutableEvidence(evidence) && isImmutableJsonSnapshot(evidence);
|
||||
let source: ApplicationGraphEvidenceSource;
|
||||
if (evidence.operation === "analyze_javascript_application") {
|
||||
requirePredicate(evidence, "rea.javascript-application-analysis", path);
|
||||
requireProvider(evidence, JAVASCRIPT_APPLICATION_PROVIDER, path);
|
||||
return staticApplicationSource(evidence, path);
|
||||
}
|
||||
if (evidence.operation === "reconcile_javascript_runtime") {
|
||||
source = staticApplicationSource(evidence, path, immutable);
|
||||
} else if (evidence.operation === "reconcile_javascript_runtime") {
|
||||
requirePredicate(evidence, "rea.javascript-runtime-reconciliation", path);
|
||||
requireProvider(
|
||||
evidence,
|
||||
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
path,
|
||||
);
|
||||
return staticRuntimeSource(evidence, path);
|
||||
}
|
||||
if (evidence.operation === "project_managed_application_graph") {
|
||||
source = staticRuntimeSource(evidence, path, immutable);
|
||||
} else if (evidence.operation === "project_managed_application_graph") {
|
||||
requirePredicate(evidence, "rea.managed-application-graph", path);
|
||||
requireProvider(evidence, MANAGED_WORKFLOW_PROVIDER, path);
|
||||
return managedApplicationSource(evidence, path);
|
||||
source = managedApplicationSource(evidence, path, immutable);
|
||||
} else {
|
||||
throw invalidEvidence(
|
||||
path,
|
||||
"operation",
|
||||
"Expected authenticated JavaScript analysis, runtime reconciliation, or managed application graph Evidence.",
|
||||
);
|
||||
}
|
||||
throw invalidEvidence(
|
||||
path,
|
||||
"operation",
|
||||
"Expected authenticated JavaScript analysis, runtime reconciliation, or managed application graph Evidence.",
|
||||
);
|
||||
if (immutable) {
|
||||
const cached = Object.freeze(source);
|
||||
ownedApplicationSources.set(evidence, cached);
|
||||
return cached;
|
||||
}
|
||||
return source;
|
||||
});
|
||||
|
||||
const borrowOrSealNormalizedResult = <Parsed extends JsonValue>(
|
||||
evidence: Evidence,
|
||||
parsed: Parsed,
|
||||
immutable: boolean,
|
||||
memberKeys: readonly string[],
|
||||
): Parsed => {
|
||||
if (!immutable) return parsed;
|
||||
const snapshot = immutableJsonSnapshotMember(evidence, "normalized_result");
|
||||
const owned =
|
||||
snapshot !== undefined && canBorrowParsedJsonSnapshot(snapshot, parsed)
|
||||
? (snapshot as Parsed)
|
||||
: freezeJsonSnapshot(parsed);
|
||||
for (const key of memberKeys) immutableJsonSnapshotMember(owned, key);
|
||||
return owned;
|
||||
};
|
||||
|
||||
const staticApplicationSource = (
|
||||
evidence: Evidence,
|
||||
path: readonly (string | number)[],
|
||||
immutable: boolean,
|
||||
): ApplicationGraphEvidenceSource => {
|
||||
const result = parseCallerValue(
|
||||
const parsed = parseCallerValue(
|
||||
(input) => javascriptApplicationAnalysisResultSchema.parse(input),
|
||||
evidence.normalized_result,
|
||||
[...path, "normalized_result"],
|
||||
);
|
||||
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
|
||||
"graph",
|
||||
"semantic_graph",
|
||||
]);
|
||||
return staticApplicationSourceForResult(evidence, result, path);
|
||||
};
|
||||
|
||||
@@ -201,6 +237,7 @@ const staticApplicationSourceForResult = (
|
||||
const staticRuntimeSource = (
|
||||
evidence: Evidence,
|
||||
path: readonly (string | number)[],
|
||||
immutable: boolean,
|
||||
): ApplicationGraphEvidenceSource => {
|
||||
if (
|
||||
evidence.authority !== "analyst-inference" ||
|
||||
@@ -211,11 +248,14 @@ const staticRuntimeSource = (
|
||||
"authority",
|
||||
"Runtime reconciliation Evidence must use analyst-inference authority and inferred confidence.",
|
||||
);
|
||||
const result = parseCallerValue(
|
||||
const parsed = parseCallerValue(
|
||||
(input) => javascriptRuntimeReconciliationResultSchema.parse(input),
|
||||
evidence.normalized_result,
|
||||
[...path, "normalized_result"],
|
||||
);
|
||||
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
|
||||
"graph",
|
||||
]);
|
||||
assertResultEvidenceLinksInEnvelope(
|
||||
result.evidence_links,
|
||||
evidence,
|
||||
@@ -243,6 +283,7 @@ const staticRuntimeSource = (
|
||||
const managedApplicationSource = (
|
||||
evidence: Evidence,
|
||||
path: readonly (string | number)[],
|
||||
immutable: boolean,
|
||||
): ApplicationGraphEvidenceSource => {
|
||||
if (
|
||||
evidence.authority !== "analyst-inference" ||
|
||||
@@ -253,11 +294,14 @@ const managedApplicationSource = (
|
||||
"authority",
|
||||
"Managed application graph Evidence must use analyst-inference authority and inferred confidence.",
|
||||
);
|
||||
const result = parseCallerValue(
|
||||
const parsed = parseCallerValue(
|
||||
(input) => managedApplicationGraphResultSchema.parse(input),
|
||||
evidence.normalized_result,
|
||||
[...path, "normalized_result"],
|
||||
);
|
||||
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
|
||||
"graph",
|
||||
]);
|
||||
assertResultEvidenceLinksInEnvelope(
|
||||
result.evidence_links,
|
||||
evidence,
|
||||
|
||||
@@ -121,6 +121,7 @@ const addBundlerModuleNodes = (
|
||||
input: BundlerModuleProjectionInput,
|
||||
): void => {
|
||||
const { file, registration, chunk, coverage, limitations } = input;
|
||||
const entryModuleKeys = new Set(registration.entry_module_keys);
|
||||
for (const moduleValue of registration.modules) {
|
||||
const module = context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
@@ -139,9 +140,7 @@ const addBundlerModuleNodes = (
|
||||
chunk_keys: registration.chunk_keys,
|
||||
module_key: moduleValue.module_key,
|
||||
factory_require_name: moduleValue.factory_require_name,
|
||||
runtime_entry: registration.entry_module_keys.includes(
|
||||
moduleValue.module_key,
|
||||
),
|
||||
runtime_entry: entryModuleKeys.has(moduleValue.module_key),
|
||||
source_sha256: moduleValue.source_sha256,
|
||||
structural_fingerprint_sha256:
|
||||
moduleValue.structural_fingerprint_sha256,
|
||||
|
||||
@@ -30,6 +30,7 @@ export const createJavaScriptRuntimeReconciliationEvidence = (
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: result.evidence_links,
|
||||
},
|
||||
{ immutable: true },
|
||||
);
|
||||
|
||||
const parameters = (
|
||||
|
||||
@@ -111,6 +111,7 @@ const createManagedApplicationGraphEvidence = (
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: result.evidence_links,
|
||||
},
|
||||
{ immutable: true },
|
||||
);
|
||||
|
||||
const subjectTarget = (
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { isImmutableJsonSnapshot } from "../immutableJson.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||
import type {
|
||||
ApplicationEdge,
|
||||
ApplicationNode,
|
||||
} from "./javascriptApplicationGraphSchemas.js";
|
||||
|
||||
/** Directed adjacency entry for deterministic JAG traversal. */
|
||||
export interface FeatureAdjacencyEntry {
|
||||
readonly edge: ApplicationEdge;
|
||||
readonly nextNodeId: string;
|
||||
/** In "both", the step goes from a contained node up to its container. */
|
||||
readonly ascends: boolean;
|
||||
}
|
||||
|
||||
export type FeatureTraversalDirection = "outgoing" | "incoming" | "both";
|
||||
|
||||
/** Lazily populated immutable lookup index for one sealed JAG snapshot. */
|
||||
export interface FeatureGraphIndex {
|
||||
readonly nodesById: ReadonlyMap<string, ApplicationNode>;
|
||||
readonly nodesByKind: ReadonlyMap<
|
||||
ApplicationNode["kind"],
|
||||
readonly ApplicationNode[]
|
||||
>;
|
||||
adjacency(
|
||||
direction: FeatureTraversalDirection,
|
||||
): ReadonlyMap<string, readonly FeatureAdjacencyEntry[]>;
|
||||
}
|
||||
|
||||
const featureGraphIndexes = new WeakMap<
|
||||
JavaScriptApplicationGraph,
|
||||
FeatureGraphIndex
|
||||
>();
|
||||
|
||||
/** Return a cached structural index when `graph` is an authenticated immutable snapshot. */
|
||||
export const getFeatureGraphIndex = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
): FeatureGraphIndex | undefined => {
|
||||
if (!isImmutableJsonSnapshot(graph)) return undefined;
|
||||
let index = featureGraphIndexes.get(graph);
|
||||
if (index === undefined) {
|
||||
index = buildFeatureGraphIndex(graph);
|
||||
featureGraphIndexes.set(graph, index);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
const buildFeatureGraphIndex = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
): FeatureGraphIndex => {
|
||||
const nodesById = new Map<string, ApplicationNode>();
|
||||
const nodesByKind = new Map<ApplicationNode["kind"], ApplicationNode[]>();
|
||||
for (const node of graph.nodes) {
|
||||
nodesById.set(node.node_id, node);
|
||||
const bucket = nodesByKind.get(node.kind);
|
||||
if (bucket === undefined) nodesByKind.set(node.kind, [node]);
|
||||
else bucket.push(node);
|
||||
}
|
||||
const adjacencyCache: Partial<
|
||||
Record<
|
||||
FeatureTraversalDirection,
|
||||
ReadonlyMap<string, readonly FeatureAdjacencyEntry[]>
|
||||
>
|
||||
> = {};
|
||||
return {
|
||||
nodesById,
|
||||
nodesByKind,
|
||||
adjacency(direction) {
|
||||
let cached = adjacencyCache[direction];
|
||||
if (cached === undefined) {
|
||||
cached = buildFeatureAdjacency(graph.edges, direction);
|
||||
adjacencyCache[direction] = cached;
|
||||
}
|
||||
return cached;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Build deterministic sorted adjacency lists for one traversal direction. */
|
||||
export const buildFeatureAdjacency = (
|
||||
edges: readonly ApplicationEdge[],
|
||||
direction: FeatureTraversalDirection,
|
||||
): ReadonlyMap<string, FeatureAdjacencyEntry[]> => {
|
||||
const adjacency = new Map<string, FeatureAdjacencyEntry[]>();
|
||||
for (const edge of edges) {
|
||||
if (direction !== "incoming")
|
||||
addAdjacency(adjacency, edge.source_node_id, {
|
||||
edge,
|
||||
nextNodeId: edge.target_node_id,
|
||||
ascends: false,
|
||||
});
|
||||
if (direction !== "outgoing")
|
||||
addAdjacency(adjacency, edge.target_node_id, {
|
||||
edge,
|
||||
nextNodeId: edge.source_node_id,
|
||||
ascends: direction === "both" && edge.relation === "contains",
|
||||
});
|
||||
}
|
||||
for (const entries of adjacency.values())
|
||||
if (entries.length > 1)
|
||||
entries.sort(
|
||||
(left, right) =>
|
||||
compareUnicodeCodePoints(left.edge.edge_id, right.edge.edge_id) ||
|
||||
compareUnicodeCodePoints(left.nextNodeId, right.nextNodeId),
|
||||
);
|
||||
return adjacency;
|
||||
};
|
||||
|
||||
const addAdjacency = (
|
||||
adjacency: Map<string, FeatureAdjacencyEntry[]>,
|
||||
nodeId: string,
|
||||
entry: FeatureAdjacencyEntry,
|
||||
): void => {
|
||||
const entries = adjacency.get(nodeId);
|
||||
if (entries === undefined) adjacency.set(nodeId, [entry]);
|
||||
else entries.push(entry);
|
||||
};
|
||||
@@ -1,8 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildSyntheticJavaScriptApplicationGraph } from "./javascriptApplicationGraph.fixture.js";
|
||||
import { freezeJsonSnapshot } from "../immutableJson.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
import { findApplicationFeatureSeeds } from "./javascriptFeatureSeed.js";
|
||||
import { semanticFixtureGraph } from "../../../tests/support/javascriptSemanticGraphFixture.js";
|
||||
import {
|
||||
findApplicationFeatureSeeds,
|
||||
findApplicationFeatureSeedsInGraph,
|
||||
} from "./javascriptFeatureSeed.js";
|
||||
import { traceApplicationFeature } from "./javascriptFeatureTrace.js";
|
||||
|
||||
describe("application feature seed property matching", () => {
|
||||
it("finds a string after 512 other property values", () => {
|
||||
@@ -65,3 +71,137 @@ const graphNodeWithProperties = (
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
describe("feature seed normalization, field gating, and immutable WeakMap index", () => {
|
||||
it("matches ASCII fast-path and Unicode NFKC values while gating irrelevant fields", () => {
|
||||
const channelNode = {
|
||||
...graphNodeWithProperties({
|
||||
unrelated: "ipc:AuthToken",
|
||||
channel: "ipc:AuthToken",
|
||||
}),
|
||||
kind: "ipc-channel" as const,
|
||||
};
|
||||
const apiNode = {
|
||||
...graphNodeWithProperties({
|
||||
unrelated: "getToken",
|
||||
methods: ["getToken"],
|
||||
}),
|
||||
kind: "context-bridge-api" as const,
|
||||
};
|
||||
const unicodeNode = graphNodeWithProperties({
|
||||
title: "file-HÉLLO",
|
||||
nested: { unused: true },
|
||||
});
|
||||
const template = buildSyntheticJavaScriptApplicationGraph().nodes[0];
|
||||
if (template === undefined) throw new Error("Expected fixture graph node");
|
||||
expect(
|
||||
findApplicationFeatureSeeds([template, channelNode], {
|
||||
kind: "channel",
|
||||
value: "IPC:authtoken",
|
||||
match: "exact",
|
||||
case_sensitive: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
node_id: channelNode.node_id,
|
||||
kind: "ipc-channel",
|
||||
basis: "property",
|
||||
field: "observations[0].properties.channel",
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
findApplicationFeatureSeeds([apiNode], {
|
||||
kind: "api",
|
||||
value: "gettoken",
|
||||
match: "exact",
|
||||
case_sensitive: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
node_id: apiNode.node_id,
|
||||
kind: "context-bridge-api",
|
||||
basis: "property",
|
||||
field: "observations[0].properties.methods[0]",
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
findApplicationFeatureSeeds([unicodeNode], {
|
||||
kind: "string",
|
||||
value: "FILE-héllo",
|
||||
match: "contains",
|
||||
case_sensitive: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
node_id: unicodeNode.node_id,
|
||||
kind: unicodeNode.kind,
|
||||
basis: "property",
|
||||
field: "observations[0].properties.title",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("matches mutable parity with immutable JAG and semantic-label WeakMap indexes", () => {
|
||||
const mutableGraph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const immutableGraph = freezeJsonSnapshot(structuredClone(mutableGraph));
|
||||
const mutableSemantic = semanticFixtureGraph();
|
||||
const immutableSemantic = freezeJsonSnapshot(
|
||||
structuredClone(mutableSemantic),
|
||||
);
|
||||
const seed = {
|
||||
kind: "string" as const,
|
||||
value: "app.example.invalid",
|
||||
match: "contains" as const,
|
||||
case_sensitive: false,
|
||||
};
|
||||
expect(findApplicationFeatureSeedsInGraph(immutableGraph, seed)).toEqual(
|
||||
findApplicationFeatureSeedsInGraph(mutableGraph, seed),
|
||||
);
|
||||
const evId = `ev_${"a".repeat(64)}`;
|
||||
const traceHitA = traceApplicationFeature({
|
||||
sourceEvidenceId: evId,
|
||||
graph: immutableGraph,
|
||||
semanticGraph: immutableSemantic,
|
||||
nativeEvidence: [],
|
||||
seed,
|
||||
direction: "both",
|
||||
});
|
||||
const traceHitB = traceApplicationFeature({
|
||||
sourceEvidenceId: evId,
|
||||
graph: immutableGraph,
|
||||
semanticGraph: immutableSemantic,
|
||||
nativeEvidence: [],
|
||||
seed,
|
||||
direction: "both",
|
||||
});
|
||||
expect(traceHitB).toEqual(traceHitA);
|
||||
|
||||
const missSeed = {
|
||||
kind: "string" as const,
|
||||
value:
|
||||
immutableSemantic.nodes.find((n) => n.label !== null)?.label ??
|
||||
"missing",
|
||||
match: "contains" as const,
|
||||
case_sensitive: false,
|
||||
};
|
||||
const missMutable = traceApplicationFeature({
|
||||
sourceEvidenceId: evId,
|
||||
graph: mutableGraph,
|
||||
semanticGraph: mutableSemantic,
|
||||
semanticPage: { offset: 0, limit: 2 },
|
||||
nativeEvidence: [],
|
||||
seed: missSeed,
|
||||
direction: "outgoing",
|
||||
});
|
||||
const missImmutableWarm = traceApplicationFeature({
|
||||
sourceEvidenceId: evId,
|
||||
graph: immutableGraph,
|
||||
semanticGraph: immutableSemantic,
|
||||
semanticPage: { offset: 0, limit: 2 },
|
||||
nativeEvidence: [],
|
||||
seed: missSeed,
|
||||
direction: "outgoing",
|
||||
});
|
||||
expect(missImmutableWarm).toEqual(missMutable);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { isJavaScriptModuleUnit } from "./javascriptModuleUnits.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
|
||||
import { getFeatureGraphIndex } from "./javascriptFeatureGraphIndex.js";
|
||||
import {
|
||||
featureSeedMatchMode,
|
||||
type ApplicationFeatureSeed,
|
||||
@@ -15,69 +17,178 @@ export interface ApplicationFeatureSeedMatch {
|
||||
readonly field: string;
|
||||
}
|
||||
|
||||
interface CandidateField {
|
||||
readonly basis: ApplicationFeatureSeedMatch["basis"];
|
||||
readonly field: string;
|
||||
/** Structural field path, retaining literal keys but omitting array indexes. */
|
||||
readonly selectionPath?: string;
|
||||
readonly value: string;
|
||||
interface SuffixPattern {
|
||||
readonly name: string;
|
||||
readonly dotName: string;
|
||||
}
|
||||
|
||||
type TypedSeedKind = "api" | "channel" | "module" | "native-export";
|
||||
|
||||
const suffixPatterns = (names: readonly string[]): readonly SuffixPattern[] =>
|
||||
names.map((name) => ({ name, dotName: `.${name}` }));
|
||||
|
||||
const SCALAR_PATTERNS: Readonly<
|
||||
Record<TypedSeedKind, readonly SuffixPattern[]>
|
||||
> = {
|
||||
api: suffixPatterns([
|
||||
"label",
|
||||
"api_name",
|
||||
"api_key",
|
||||
"key",
|
||||
"methods",
|
||||
"members",
|
||||
]),
|
||||
channel: suffixPatterns(["label", "channel", "key"]),
|
||||
module: suffixPatterns([
|
||||
"label",
|
||||
"module_key",
|
||||
"path",
|
||||
"source",
|
||||
"original_source",
|
||||
"source_root",
|
||||
"exports",
|
||||
]),
|
||||
"native-export": suffixPatterns([
|
||||
"label",
|
||||
"key",
|
||||
"requested_members",
|
||||
"members",
|
||||
]),
|
||||
};
|
||||
|
||||
const MEMBER_PATTERNS: Readonly<
|
||||
Record<TypedSeedKind, readonly SuffixPattern[]>
|
||||
> = {
|
||||
api: suffixPatterns(["methods", "members"]),
|
||||
channel: [],
|
||||
module: suffixPatterns(["exports"]),
|
||||
"native-export": suffixPatterns(["requested_members", "members"]),
|
||||
};
|
||||
|
||||
const keyMatchesAny = (
|
||||
key: string,
|
||||
patterns: readonly SuffixPattern[],
|
||||
): boolean => {
|
||||
for (const { name, dotName } of patterns)
|
||||
if (key === name || key.endsWith(dotName)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Locate every graph node matching a typed literal seed without regex execution. */
|
||||
export const findApplicationFeatureSeeds = (
|
||||
nodes: readonly ApplicationNode[],
|
||||
seed: ApplicationFeatureSeed,
|
||||
): ApplicationFeatureSeedMatch[] =>
|
||||
nodes
|
||||
.flatMap((node) => seedMatch(node, seed))
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(
|
||||
`${left.node_id}\0${left.basis}\0${left.field}`,
|
||||
`${right.node_id}\0${right.basis}\0${right.field}`,
|
||||
),
|
||||
);
|
||||
): ApplicationFeatureSeedMatch[] => collectSeedMatches([nodes], seed);
|
||||
|
||||
const seedMatch = (
|
||||
node: ApplicationNode,
|
||||
/** Locate matching seeds using immutable graph indexes when available. */
|
||||
export const findApplicationFeatureSeedsInGraph = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
seed: ApplicationFeatureSeed,
|
||||
): ApplicationFeatureSeedMatch[] => {
|
||||
const index = getFeatureGraphIndex(graph);
|
||||
if (index === undefined)
|
||||
return findApplicationFeatureSeeds(graph.nodes, seed);
|
||||
const mode = featureSeedMatchMode(seed);
|
||||
if (seed.kind === "node-id" && mode === "exact") {
|
||||
const query = normalizeFeatureSeedText(seed.value, seed.case_sensitive);
|
||||
const node = index.nodesById.get(query);
|
||||
return node === undefined
|
||||
? []
|
||||
: [
|
||||
{
|
||||
node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
basis: "node-id",
|
||||
field: "node_id",
|
||||
},
|
||||
];
|
||||
}
|
||||
return collectSeedMatches(
|
||||
candidateNodeBuckets(graph, index, seed.kind),
|
||||
seed,
|
||||
);
|
||||
};
|
||||
|
||||
const candidateNodeBuckets = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
index: NonNullable<ReturnType<typeof getFeatureGraphIndex>>,
|
||||
kind: ApplicationFeatureSeed["kind"],
|
||||
): readonly (readonly ApplicationNode[])[] => {
|
||||
if (kind === "string" || kind === "node-id") return [graph.nodes];
|
||||
if (kind === "route") return [index.nodesByKind.get("endpoint") ?? []];
|
||||
if (kind === "api")
|
||||
return [
|
||||
index.nodesByKind.get("context-bridge-api") ?? [],
|
||||
index.nodesByKind.get("javascript-expression") ?? [],
|
||||
];
|
||||
if (kind === "channel") return [index.nodesByKind.get("ipc-channel") ?? []];
|
||||
if (kind === "module")
|
||||
return [
|
||||
index.nodesByKind.get("javascript-asset") ?? [],
|
||||
index.nodesByKind.get("javascript-module") ?? [],
|
||||
index.nodesByKind.get("source-module") ?? [],
|
||||
];
|
||||
return [index.nodesByKind.get("native-export") ?? []];
|
||||
};
|
||||
|
||||
const collectSeedMatches = (
|
||||
buckets: readonly (readonly ApplicationNode[])[],
|
||||
seed: ApplicationFeatureSeed,
|
||||
): ApplicationFeatureSeedMatch[] => {
|
||||
const mode = featureSeedMatchMode(seed);
|
||||
const caseSensitive = seed.case_sensitive;
|
||||
const query = normalizeFeatureSeedText(seed.value, caseSensitive);
|
||||
if (!kindMatches(node, seed.kind)) return [];
|
||||
const requestedEntryPath =
|
||||
seed.kind === "api" && "entry_path" in seed ? seed.entry_path : undefined;
|
||||
if (
|
||||
seed.kind === "api" &&
|
||||
requestedEntryPath !== undefined &&
|
||||
!node.observations.some(({ properties }) => {
|
||||
const entryPath = properties.entry_path;
|
||||
return (
|
||||
Array.isArray(entryPath) &&
|
||||
entryPath.length === requestedEntryPath.length &&
|
||||
entryPath.every(
|
||||
(segment, index) => segment === requestedEntryPath[index],
|
||||
)
|
||||
const matches: ApplicationFeatureSeedMatch[] = [];
|
||||
for (const nodes of buckets) {
|
||||
for (const node of nodes) {
|
||||
if (!kindMatches(node, seed.kind)) continue;
|
||||
if (
|
||||
seed.kind === "api" &&
|
||||
requestedEntryPath !== undefined &&
|
||||
!hasMatchingEntryPath(node, requestedEntryPath)
|
||||
)
|
||||
continue;
|
||||
const match = firstMatchingCandidate(
|
||||
node,
|
||||
seed.kind,
|
||||
query,
|
||||
mode,
|
||||
caseSensitive,
|
||||
);
|
||||
})
|
||||
)
|
||||
return [];
|
||||
const match = candidateFields(node, seed.kind).find((candidate) => {
|
||||
const value = normalizeFeatureSeedText(candidate.value, caseSensitive);
|
||||
return mode === "exact" ? value === query : value.includes(query);
|
||||
});
|
||||
return match === undefined
|
||||
? []
|
||||
: [
|
||||
{
|
||||
if (match !== undefined)
|
||||
matches.push({
|
||||
node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
basis: match.basis,
|
||||
field: match.field,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
if (matches.length > 1)
|
||||
matches.sort((left, right) =>
|
||||
compareUnicodeCodePoints(
|
||||
`${left.node_id}\0${left.basis}\0${left.field}`,
|
||||
`${right.node_id}\0${right.basis}\0${right.field}`,
|
||||
),
|
||||
);
|
||||
return matches;
|
||||
};
|
||||
|
||||
const hasMatchingEntryPath = (
|
||||
node: ApplicationNode,
|
||||
requestedEntryPath: readonly string[],
|
||||
): boolean =>
|
||||
node.observations.some(({ properties }) => {
|
||||
const entryPath = properties.entry_path;
|
||||
return (
|
||||
Array.isArray(entryPath) &&
|
||||
entryPath.length === requestedEntryPath.length &&
|
||||
entryPath.every((segment, index) => segment === requestedEntryPath[index])
|
||||
);
|
||||
});
|
||||
|
||||
const kindMatches = (
|
||||
node: ApplicationNode,
|
||||
kind: ApplicationFeatureSeed["kind"],
|
||||
@@ -101,173 +212,229 @@ const kindMatches = (
|
||||
return node.kind === "native-export";
|
||||
};
|
||||
|
||||
const candidateFields = (
|
||||
const textMatches = (
|
||||
candidate: string,
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): boolean => {
|
||||
const normalized = normalizeFeatureSeedText(candidate, caseSensitive);
|
||||
return mode === "exact" ? normalized === query : normalized.includes(query);
|
||||
};
|
||||
|
||||
interface MatchedField {
|
||||
readonly basis: ApplicationFeatureSeedMatch["basis"];
|
||||
readonly field: string;
|
||||
}
|
||||
|
||||
const firstMatchingCandidate = (
|
||||
node: ApplicationNode,
|
||||
seedKind: ApplicationFeatureSeed["kind"],
|
||||
): CandidateField[] => {
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): MatchedField | undefined => {
|
||||
if (seedKind === "node-id")
|
||||
return [{ basis: "node-id", field: "node_id", value: node.node_id }];
|
||||
return textMatches(node.node_id, query, mode, caseSensitive)
|
||||
? { basis: "node-id", field: "node_id" }
|
||||
: undefined;
|
||||
if (seedKind === "route")
|
||||
return node.observations.flatMap((observation, index) =>
|
||||
(["value", "path"] as const).flatMap((key) => {
|
||||
const value = observation.properties[key];
|
||||
return typeof value === "string"
|
||||
? [
|
||||
{
|
||||
basis: "property" as const,
|
||||
field: `observations[${String(index)}].properties.${key}`,
|
||||
value,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
const fields: CandidateField[] = [
|
||||
...identityFields(node),
|
||||
...node.observations.flatMap((observation, index) => [
|
||||
...(observation.label === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
basis: "label" as const,
|
||||
field: `observations[${String(index)}].label`,
|
||||
value: observation.label,
|
||||
},
|
||||
]),
|
||||
...(observation.source_map_reference !== null &&
|
||||
observation.source_map_reference.resolution.kind !== "unresolved"
|
||||
? [
|
||||
{
|
||||
basis: "property" as const,
|
||||
field: `observations[${String(index)}].source_map_reference.resolution.path`,
|
||||
value: observation.source_map_reference.resolution.path,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...propertyFields(
|
||||
observation.properties,
|
||||
`observations[${String(index)}].properties`,
|
||||
),
|
||||
]),
|
||||
];
|
||||
if (seedKind === "string") return fields;
|
||||
const names = relevantFields[seedKind];
|
||||
return fields.filter(({ field, selectionPath = field }) =>
|
||||
names.some((name) => {
|
||||
const path = memberFieldSuffixes.has(name) ? selectionPath : field;
|
||||
return path === "identity" || path.endsWith(name);
|
||||
}),
|
||||
return firstMatchingRouteField(node, query, mode, caseSensitive);
|
||||
const identityMatch = firstMatchingIdentityField(
|
||||
node,
|
||||
seedKind,
|
||||
query,
|
||||
mode,
|
||||
caseSensitive,
|
||||
);
|
||||
if (identityMatch !== undefined) return identityMatch;
|
||||
for (let index = 0; index < node.observations.length; index += 1) {
|
||||
const observation = node.observations[index]!;
|
||||
if (
|
||||
observation.label !== null &&
|
||||
textMatches(observation.label, query, mode, caseSensitive)
|
||||
)
|
||||
return { basis: "label", field: `observations[${String(index)}].label` };
|
||||
if (
|
||||
(seedKind === "string" || seedKind === "module") &&
|
||||
observation.source_map_reference !== null &&
|
||||
observation.source_map_reference.resolution.kind !== "unresolved" &&
|
||||
textMatches(
|
||||
observation.source_map_reference.resolution.path,
|
||||
query,
|
||||
mode,
|
||||
caseSensitive,
|
||||
)
|
||||
)
|
||||
return {
|
||||
basis: "property",
|
||||
field: `observations[${String(index)}].source_map_reference.resolution.path`,
|
||||
};
|
||||
const propertyMatch = firstMatchingPropertyField(
|
||||
observation.properties,
|
||||
`observations[${String(index)}].properties`,
|
||||
seedKind,
|
||||
query,
|
||||
mode,
|
||||
caseSensitive,
|
||||
);
|
||||
if (propertyMatch !== undefined)
|
||||
return { basis: "property", field: propertyMatch };
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const memberFieldSuffixes = new Set([
|
||||
".members",
|
||||
".methods",
|
||||
".exports",
|
||||
".requested_members",
|
||||
]);
|
||||
const firstMatchingRouteField = (
|
||||
node: ApplicationNode,
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): MatchedField | undefined => {
|
||||
for (let index = 0; index < node.observations.length; index += 1) {
|
||||
const { properties } = node.observations[index]!;
|
||||
for (const key of ["value", "path"] as const) {
|
||||
const value = properties[key];
|
||||
if (
|
||||
typeof value === "string" &&
|
||||
textMatches(value, query, mode, caseSensitive)
|
||||
)
|
||||
return {
|
||||
basis: "property",
|
||||
field: `observations[${String(index)}].properties.${key}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const relevantFields = {
|
||||
route: [".label", ".value", ".path"],
|
||||
api: [".label", ".api_name", ".api_key", ".key", ".methods", ".members"],
|
||||
channel: [".label", ".channel", ".key"],
|
||||
module: [
|
||||
".label",
|
||||
".module_key",
|
||||
".path",
|
||||
".source",
|
||||
".original_source",
|
||||
".source_root",
|
||||
".exports",
|
||||
],
|
||||
"native-export": [".label", ".key", ".requested_members", ".members"],
|
||||
} as const;
|
||||
|
||||
const identityFields = (node: ApplicationNode): CandidateField[] => {
|
||||
const identity = node.identity;
|
||||
const firstMatchingIdentityField = (
|
||||
node: ApplicationNode,
|
||||
seedKind: "string" | TypedSeedKind,
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): MatchedField | undefined => {
|
||||
const { identity } = node;
|
||||
if (identity.strategy === "content-digest")
|
||||
return [{ basis: "identity", field: "identity", value: identity.sha256 }];
|
||||
if (identity.strategy === "source-map-original")
|
||||
return [
|
||||
{
|
||||
basis: "identity",
|
||||
field: "identity.original_source",
|
||||
value: identity.original_source,
|
||||
},
|
||||
...(identity.source_root === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
basis: "identity" as const,
|
||||
field: "identity.source_root",
|
||||
value: identity.source_root,
|
||||
},
|
||||
]),
|
||||
];
|
||||
return textMatches(identity.sha256, query, mode, caseSensitive)
|
||||
? { basis: "identity", field: "identity" }
|
||||
: undefined;
|
||||
if (identity.strategy === "source-map-original") {
|
||||
if (seedKind !== "string" && seedKind !== "module") return undefined;
|
||||
if (textMatches(identity.original_source, query, mode, caseSensitive))
|
||||
return { basis: "identity", field: "identity.original_source" };
|
||||
if (
|
||||
identity.source_root !== null &&
|
||||
textMatches(identity.source_root, query, mode, caseSensitive)
|
||||
)
|
||||
return { basis: "identity", field: "identity.source_root" };
|
||||
return undefined;
|
||||
}
|
||||
if (identity.strategy === "canonical-path")
|
||||
return [
|
||||
{ basis: "identity", field: "identity.path", value: identity.path },
|
||||
];
|
||||
return (seedKind === "string" || seedKind === "module") &&
|
||||
textMatches(identity.path, query, mode, caseSensitive)
|
||||
? { basis: "identity", field: "identity.path" }
|
||||
: undefined;
|
||||
if (identity.strategy === "artifact-local-key")
|
||||
return [{ basis: "identity", field: "identity.key", value: identity.key }];
|
||||
return seedKind !== "module" &&
|
||||
textMatches(identity.key, query, mode, caseSensitive)
|
||||
? { basis: "identity", field: "identity.key" }
|
||||
: undefined;
|
||||
if (identity.strategy === "runtime-instance")
|
||||
return [
|
||||
{
|
||||
basis: "identity",
|
||||
field: "identity.runtime_key",
|
||||
value: identity.runtime_key,
|
||||
},
|
||||
];
|
||||
return [];
|
||||
return seedKind === "string" &&
|
||||
textMatches(identity.runtime_key, query, mode, caseSensitive)
|
||||
? { basis: "identity", field: "identity.runtime_key" }
|
||||
: undefined;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const propertyFields = (
|
||||
interface PropertyFrame {
|
||||
readonly current: JsonValue;
|
||||
readonly path: string;
|
||||
readonly inMemberArray: boolean;
|
||||
}
|
||||
|
||||
const firstMatchingPropertyField = (
|
||||
value: Readonly<Record<string, JsonValue>>,
|
||||
prefix: string,
|
||||
): CandidateField[] => {
|
||||
const output: CandidateField[] = [];
|
||||
const pending: {
|
||||
readonly current: JsonValue;
|
||||
readonly path: string;
|
||||
readonly selectionPath: string;
|
||||
}[] = [{ current: value, path: prefix, selectionPath: prefix }];
|
||||
seedKind: "string" | TypedSeedKind,
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): string | undefined => {
|
||||
const pending: PropertyFrame[] = [
|
||||
{ current: value, path: prefix, inMemberArray: false },
|
||||
];
|
||||
const scalarPatterns =
|
||||
seedKind === "string" ? null : SCALAR_PATTERNS[seedKind];
|
||||
const memberPatterns =
|
||||
seedKind === "string" ? null : MEMBER_PATTERNS[seedKind];
|
||||
while (pending.length > 0) {
|
||||
const next = pending.pop();
|
||||
if (next === undefined) continue;
|
||||
const { current, path, selectionPath } = next;
|
||||
const { current, path, inMemberArray } = next;
|
||||
if (typeof current === "string") {
|
||||
output.push({
|
||||
basis: "property",
|
||||
field: path,
|
||||
selectionPath,
|
||||
value: current,
|
||||
});
|
||||
if (textMatches(current, query, mode, caseSensitive)) return path;
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(current)) {
|
||||
for (let index = current.length - 1; index >= 0; index -= 1) {
|
||||
const item = current[index];
|
||||
if (item !== undefined)
|
||||
if (item === null || item === undefined) continue;
|
||||
if (typeof item === "string") {
|
||||
if (seedKind === "string" || inMemberArray)
|
||||
pending.push({
|
||||
current: item,
|
||||
path: `${path}[${String(index)}]`,
|
||||
inMemberArray,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (typeof item === "object")
|
||||
pending.push({
|
||||
current: item,
|
||||
path: `${path}[${String(index)}]`,
|
||||
selectionPath,
|
||||
inMemberArray,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (current !== null && typeof current === "object") {
|
||||
for (const key of Object.keys(current)
|
||||
.sort(compareUnicodeCodePoints)
|
||||
.reverse())
|
||||
pending.push({
|
||||
current: current[key] ?? null,
|
||||
path: `${path}.${key}`,
|
||||
selectionPath: `${selectionPath}.${key}`,
|
||||
});
|
||||
const keys = Object.keys(current);
|
||||
if (keys.length > 1) keys.sort(compareUnicodeCodePoints);
|
||||
for (let index = keys.length - 1; index >= 0; index -= 1) {
|
||||
const key = keys[index]!;
|
||||
const child = current[key];
|
||||
if (child === null || child === undefined) continue;
|
||||
if (typeof child === "string") {
|
||||
if (scalarPatterns === null || keyMatchesAny(key, scalarPatterns))
|
||||
pending.push({
|
||||
current: child,
|
||||
path: `${path}.${key}`,
|
||||
inMemberArray: false,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(child)) {
|
||||
if (child.length === 0) continue;
|
||||
pending.push({
|
||||
current: child,
|
||||
path: `${path}.${key}`,
|
||||
inMemberArray:
|
||||
memberPatterns !== null && keyMatchesAny(key, memberPatterns),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (typeof child === "object")
|
||||
pending.push({
|
||||
current: child,
|
||||
path: `${path}.${key}`,
|
||||
inMemberArray: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Normalize literal matching identically across application and semantic labels. */
|
||||
@@ -275,8 +442,16 @@ export const normalizeFeatureSeedText = (
|
||||
value: string,
|
||||
caseSensitive: boolean,
|
||||
): string => {
|
||||
const normalizedValue = value.normalize(caseSensitive ? "NFC" : "NFKC");
|
||||
return caseSensitive
|
||||
? normalizedValue
|
||||
: normalizedValue.toLocaleLowerCase("en-US");
|
||||
let hasUpper = false;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index);
|
||||
if (code > 0x7f) {
|
||||
const normalizedValue = value.normalize(caseSensitive ? "NFC" : "NFKC");
|
||||
return caseSensitive
|
||||
? normalizedValue
|
||||
: normalizedValue.toLocaleLowerCase("en-US");
|
||||
}
|
||||
if (code >= 65 && code <= 90) hasUpper = true;
|
||||
}
|
||||
return caseSensitive || !hasUpper ? value : value.toLowerCase();
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isImmutableJsonSnapshot } from "../immutableJson.js";
|
||||
import { digestCanonicalValue } from "../canonicalDigest.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
@@ -18,11 +19,12 @@ import {
|
||||
type TraceApplicationFeatureInput,
|
||||
} from "./javascriptFeatureTraceSchemas.js";
|
||||
import {
|
||||
findApplicationFeatureSeeds,
|
||||
findApplicationFeatureSeedsInGraph,
|
||||
normalizeFeatureSeedText,
|
||||
type ApplicationFeatureSeedMatch,
|
||||
} from "./javascriptFeatureSeed.js";
|
||||
import type { JavaScriptSemanticGraph } from "./javascriptSemanticGraph.js";
|
||||
import type { JavaScriptSemanticGraphNode } from "./javascriptSemanticGraphSchemas.js";
|
||||
import { semanticCallLiteralValues } from "./javascriptSemanticCallLiterals.js";
|
||||
import {
|
||||
traverseApplicationFeature,
|
||||
@@ -45,8 +47,8 @@ export interface ApplicationFeatureTraceProjectionInput {
|
||||
export const traceApplicationFeature = (
|
||||
input: ApplicationFeatureTraceProjectionInput,
|
||||
): ApplicationFeatureTraceResult => {
|
||||
const seedMatches = findApplicationFeatureSeeds(
|
||||
input.graph.nodes,
|
||||
const seedMatches = findApplicationFeatureSeedsInGraph(
|
||||
input.graph,
|
||||
input.seed,
|
||||
);
|
||||
if (seedMatches.length === 0) return noMatchResult(input);
|
||||
@@ -57,15 +59,19 @@ export const traceApplicationFeature = (
|
||||
);
|
||||
const graph = traceGraph(input, seedMatches, traversal);
|
||||
const paths = terminalPaths(traversal, seedMatches);
|
||||
const nativeHandoffs = buildJavaScriptNativeHandoffs(
|
||||
input.graph,
|
||||
new Set(
|
||||
traversal.nodes
|
||||
.filter(({ kind }) => kind === "native-addon")
|
||||
.map(({ node_id }) => node_id),
|
||||
),
|
||||
input.nativeEvidence,
|
||||
const nativeAddonIds = new Set(
|
||||
traversal.nodes
|
||||
.filter(({ kind }) => kind === "native-addon")
|
||||
.map(({ node_id }) => node_id),
|
||||
);
|
||||
const nativeHandoffs =
|
||||
nativeAddonIds.size === 0
|
||||
? []
|
||||
: buildJavaScriptNativeHandoffs(
|
||||
input.graph,
|
||||
nativeAddonIds,
|
||||
input.nativeEvidence,
|
||||
);
|
||||
const evidenceLinks = uniqueSorted([
|
||||
input.sourceEvidenceId,
|
||||
...nativeHandoffs.flatMap(({ evidence_ids: ids }) => ids),
|
||||
@@ -148,6 +154,99 @@ const noMatchResult = (
|
||||
});
|
||||
};
|
||||
|
||||
type SemanticDiscoveryMatch = NonNullable<
|
||||
ApplicationFeatureTraceResult["semantic_discovery"]
|
||||
>["matches"][number];
|
||||
|
||||
interface IndexedSemanticNodeLabels {
|
||||
readonly match: SemanticDiscoveryMatch;
|
||||
readonly rawTexts: readonly string[];
|
||||
}
|
||||
|
||||
interface SemanticLabelCaseCache {
|
||||
readonly normalizedEntries: readonly {
|
||||
readonly match: SemanticDiscoveryMatch;
|
||||
readonly texts: readonly string[];
|
||||
}[];
|
||||
readonly byExact: ReadonlyMap<string, readonly SemanticDiscoveryMatch[]>;
|
||||
}
|
||||
|
||||
interface SemanticLabelIndex {
|
||||
readonly entries: readonly IndexedSemanticNodeLabels[];
|
||||
sensitive?: SemanticLabelCaseCache;
|
||||
insensitive?: SemanticLabelCaseCache;
|
||||
}
|
||||
|
||||
const semanticLabelIndexes = new WeakMap<
|
||||
JavaScriptSemanticGraph,
|
||||
SemanticLabelIndex
|
||||
>();
|
||||
|
||||
const extractNodeLabelTexts = (node: JavaScriptSemanticGraphNode): string[] => {
|
||||
const texts: string[] = [];
|
||||
if (node.label !== null) texts.push(node.label);
|
||||
for (const literal of semanticCallLiteralValues(node))
|
||||
if (typeof literal === "string") texts.push(literal);
|
||||
return texts;
|
||||
};
|
||||
|
||||
const getSemanticLabelIndex = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
): SemanticLabelIndex | undefined => {
|
||||
if (!isImmutableJsonSnapshot(graph)) return undefined;
|
||||
let index = semanticLabelIndexes.get(graph);
|
||||
if (index === undefined) {
|
||||
const entries: IndexedSemanticNodeLabels[] = [];
|
||||
for (const node of graph.nodes) {
|
||||
const rawTexts = extractNodeLabelTexts(node);
|
||||
if (rawTexts.length === 0) continue;
|
||||
entries.push({
|
||||
match: {
|
||||
node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
trace_seed: { kind: "semantic-node", node_id: node.node_id },
|
||||
},
|
||||
rawTexts,
|
||||
});
|
||||
}
|
||||
index = { entries };
|
||||
semanticLabelIndexes.set(graph, index);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
const getSemanticLabelCaseCache = (
|
||||
index: SemanticLabelIndex,
|
||||
caseSensitive: boolean,
|
||||
): SemanticLabelCaseCache => {
|
||||
const existing = caseSensitive ? index.sensitive : index.insensitive;
|
||||
if (existing !== undefined) return existing;
|
||||
const normalizedEntries: {
|
||||
readonly match: SemanticDiscoveryMatch;
|
||||
readonly texts: readonly string[];
|
||||
}[] = [];
|
||||
const byExact = new Map<string, SemanticDiscoveryMatch[]>();
|
||||
for (const entry of index.entries) {
|
||||
const texts: string[] = [];
|
||||
const seenTexts = new Set<string>();
|
||||
for (const raw of entry.rawTexts) {
|
||||
const normalized = normalizeFeatureSeedText(raw, caseSensitive);
|
||||
texts.push(normalized);
|
||||
if (!seenTexts.has(normalized)) {
|
||||
seenTexts.add(normalized);
|
||||
const bucket = byExact.get(normalized);
|
||||
if (bucket === undefined) byExact.set(normalized, [entry.match]);
|
||||
else bucket.push(entry.match);
|
||||
}
|
||||
}
|
||||
normalizedEntries.push({ match: entry.match, texts });
|
||||
}
|
||||
const built: SemanticLabelCaseCache = { normalizedEntries, byExact };
|
||||
if (caseSensitive) index.sensitive = built;
|
||||
else index.insensitive = built;
|
||||
return built;
|
||||
};
|
||||
|
||||
/** Semantic discovery is independent of the application graph traversal. */
|
||||
const discoverSemanticLabels = (
|
||||
input: ApplicationFeatureTraceProjectionInput,
|
||||
@@ -159,30 +258,51 @@ const discoverSemanticLabels = (
|
||||
const query = normalizeFeatureSeedText(seed.value, seed.case_sensitive);
|
||||
const mode = featureSeedMatchMode(seed);
|
||||
const { offset, limit } = input.semanticPage ?? { offset: 0, limit: 64 };
|
||||
const matches: NonNullable<
|
||||
ApplicationFeatureTraceResult["semantic_discovery"]
|
||||
>["matches"] = [];
|
||||
const indexed = getSemanticLabelIndex(graph);
|
||||
if (indexed !== undefined) {
|
||||
const cache = getSemanticLabelCaseCache(indexed, seed.case_sensitive);
|
||||
if (mode === "exact") {
|
||||
const all = cache.byExact.get(query) ?? [];
|
||||
const matches = all.slice(offset, offset + limit);
|
||||
return {
|
||||
source_graph_id: graph.graph_id,
|
||||
source_coverage: graph.coverage.status,
|
||||
total: all.length,
|
||||
offset,
|
||||
limit,
|
||||
next_offset:
|
||||
offset + matches.length < all.length ? offset + matches.length : null,
|
||||
matches,
|
||||
};
|
||||
}
|
||||
const matches: SemanticDiscoveryMatch[] = [];
|
||||
let total = 0;
|
||||
for (const entry of cache.normalizedEntries) {
|
||||
if (!entry.texts.some((value) => value.includes(query))) continue;
|
||||
if (total >= offset && matches.length < limit) matches.push(entry.match);
|
||||
total += 1;
|
||||
}
|
||||
return {
|
||||
source_graph_id: graph.graph_id,
|
||||
source_coverage: graph.coverage.status,
|
||||
total,
|
||||
offset,
|
||||
limit,
|
||||
next_offset:
|
||||
offset + matches.length < total ? offset + matches.length : null,
|
||||
matches,
|
||||
};
|
||||
}
|
||||
const matches: SemanticDiscoveryMatch[] = [];
|
||||
let total = 0;
|
||||
for (const node of graph.nodes) {
|
||||
const { label, node_id, kind } = node;
|
||||
const values = [
|
||||
...(label === null ? [] : [label]),
|
||||
...semanticCallLiteralValues(node).filter(
|
||||
(value): value is string => typeof value === "string",
|
||||
),
|
||||
];
|
||||
if (
|
||||
!values.some((entry) => {
|
||||
const value = normalizeFeatureSeedText(entry, seed.case_sensitive);
|
||||
return mode === "exact" ? value === query : value.includes(query);
|
||||
})
|
||||
)
|
||||
if (!nodeMatchesSemanticLabel(node, query, mode, seed.case_sensitive))
|
||||
continue;
|
||||
if (total >= offset && matches.length < limit)
|
||||
matches.push({
|
||||
node_id,
|
||||
kind,
|
||||
trace_seed: { kind: "semantic-node", node_id },
|
||||
node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
trace_seed: { kind: "semantic-node", node_id: node.node_id },
|
||||
});
|
||||
total += 1;
|
||||
}
|
||||
@@ -198,6 +318,26 @@ const discoverSemanticLabels = (
|
||||
};
|
||||
};
|
||||
|
||||
const nodeMatchesSemanticLabel = (
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
query: string,
|
||||
mode: "exact" | "contains",
|
||||
caseSensitive: boolean,
|
||||
): boolean => {
|
||||
if (node.label !== null) {
|
||||
const normalized = normalizeFeatureSeedText(node.label, caseSensitive);
|
||||
if (mode === "exact" ? normalized === query : normalized.includes(query))
|
||||
return true;
|
||||
}
|
||||
for (const literal of semanticCallLiteralValues(node)) {
|
||||
if (typeof literal !== "string") continue;
|
||||
const normalized = normalizeFeatureSeedText(literal, caseSensitive);
|
||||
if (mode === "exact" ? normalized === query : normalized.includes(query))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const traceGraph = (
|
||||
input: ApplicationFeatureTraceProjectionInput,
|
||||
seedMatches: readonly ApplicationFeatureSeedMatch[],
|
||||
@@ -297,17 +437,24 @@ const factSummary = (
|
||||
nodes: readonly ApplicationNode[],
|
||||
edges: readonly ApplicationEdge[],
|
||||
) => {
|
||||
const states = [
|
||||
...nodes.flatMap(({ observations }) =>
|
||||
observations.map(({ evidence }) => evidence.state),
|
||||
),
|
||||
...edges.map(({ evidence }) => evidence.state),
|
||||
];
|
||||
let observed = 0;
|
||||
let inferred = 0;
|
||||
let unknown = 0;
|
||||
let unavailable = 0;
|
||||
const countState = (state: ApplicationEdge["evidence"]["state"]): void => {
|
||||
if (state === "observed") observed += 1;
|
||||
else if (state === "inferred") inferred += 1;
|
||||
else if (state === "unknown") unknown += 1;
|
||||
else unavailable += 1;
|
||||
};
|
||||
for (const { observations } of nodes)
|
||||
for (const { evidence } of observations) countState(evidence.state);
|
||||
for (const { evidence } of edges) countState(evidence.state);
|
||||
return {
|
||||
observed_facts: states.filter((state) => state === "observed").length,
|
||||
inferred_facts: states.filter((state) => state === "inferred").length,
|
||||
unknown_facts: states.filter((state) => state === "unknown").length,
|
||||
unavailable_facts: states.filter((state) => state === "unavailable").length,
|
||||
observed_facts: observed,
|
||||
inferred_facts: inferred,
|
||||
unknown_facts: unknown,
|
||||
unavailable_facts: unavailable,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -4,13 +4,10 @@ import type {
|
||||
} from "./javascriptApplicationGraphSchemas.js";
|
||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
|
||||
interface AdjacencyEntry {
|
||||
readonly edge: ApplicationEdge;
|
||||
readonly nextNodeId: string;
|
||||
/** In "both", the step goes from a contained node up to its container. */
|
||||
readonly ascends: boolean;
|
||||
}
|
||||
import {
|
||||
buildFeatureAdjacency,
|
||||
getFeatureGraphIndex,
|
||||
} from "./javascriptFeatureGraphIndex.js";
|
||||
|
||||
interface Predecessor {
|
||||
readonly previousNodeId: string;
|
||||
@@ -30,8 +27,13 @@ export const traverseApplicationFeature = (
|
||||
seedNodeIds: readonly string[],
|
||||
direction: "outgoing" | "incoming" | "both",
|
||||
): ApplicationFeatureTraversal => {
|
||||
const nodeById = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const adjacency = buildAdjacency(graph.edges, direction);
|
||||
const index = getFeatureGraphIndex(graph);
|
||||
const nodeById =
|
||||
index?.nodesById ??
|
||||
new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const adjacency =
|
||||
index?.adjacency(direction) ??
|
||||
buildFeatureAdjacency(graph.edges, direction);
|
||||
const visited = new Set(seedNodeIds);
|
||||
const retainedEdges = new Map<string, ApplicationEdge>();
|
||||
const predecessors = new Map<string, Predecessor>();
|
||||
@@ -67,55 +69,23 @@ export const traverseApplicationFeature = (
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
return {
|
||||
nodes: [...visited]
|
||||
.map((nodeId) => nodeById.get(nodeId))
|
||||
.filter((node): node is ApplicationNode => node !== undefined)
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.node_id, right.node_id),
|
||||
),
|
||||
edges: [...retainedEdges.values()].sort((left, right) =>
|
||||
const nodes: ApplicationNode[] = [];
|
||||
for (const nodeId of visited) {
|
||||
const node = nodeById.get(nodeId);
|
||||
if (node !== undefined) nodes.push(node);
|
||||
}
|
||||
if (nodes.length > 1)
|
||||
nodes.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.node_id, right.node_id),
|
||||
);
|
||||
const edges = [...retainedEdges.values()];
|
||||
if (edges.length > 1)
|
||||
edges.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.edge_id, right.edge_id),
|
||||
),
|
||||
);
|
||||
return {
|
||||
nodes,
|
||||
edges,
|
||||
predecessors,
|
||||
};
|
||||
};
|
||||
|
||||
const buildAdjacency = (
|
||||
edges: readonly ApplicationEdge[],
|
||||
direction: "outgoing" | "incoming" | "both",
|
||||
): ReadonlyMap<string, AdjacencyEntry[]> => {
|
||||
const adjacency = new Map<string, AdjacencyEntry[]>();
|
||||
for (const edge of edges) {
|
||||
if (direction !== "incoming")
|
||||
addAdjacency(adjacency, edge.source_node_id, {
|
||||
edge,
|
||||
nextNodeId: edge.target_node_id,
|
||||
ascends: false,
|
||||
});
|
||||
if (direction !== "outgoing")
|
||||
addAdjacency(adjacency, edge.target_node_id, {
|
||||
edge,
|
||||
nextNodeId: edge.source_node_id,
|
||||
ascends: direction === "both" && edge.relation === "contains",
|
||||
});
|
||||
}
|
||||
for (const entries of adjacency.values())
|
||||
entries.sort((left, right) =>
|
||||
compareUnicodeCodePoints(
|
||||
`${left.edge.edge_id}\0${left.nextNodeId}`,
|
||||
`${right.edge.edge_id}\0${right.nextNodeId}`,
|
||||
),
|
||||
);
|
||||
return adjacency;
|
||||
};
|
||||
|
||||
const addAdjacency = (
|
||||
adjacency: Map<string, AdjacencyEntry[]>,
|
||||
nodeId: string,
|
||||
entry: AdjacencyEntry,
|
||||
): void => {
|
||||
const entries = adjacency.get(nodeId);
|
||||
if (entries === undefined) adjacency.set(nodeId, [entry]);
|
||||
else entries.push(entry);
|
||||
};
|
||||
@@ -0,0 +1,326 @@
|
||||
import { isImmutableJsonSnapshot } from "../immutableJson.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptSemanticGraph } from "./javascriptSemanticGraph.js";
|
||||
import type {
|
||||
JavaScriptSemanticEvidenceContext,
|
||||
JavaScriptSemanticGraphNode,
|
||||
JavaScriptSemanticGraphRelation,
|
||||
JavaScriptSemanticGraphUnknown,
|
||||
} from "./javascriptSemanticGraphSchemas.js";
|
||||
import { semanticCallLiteralValues } from "./javascriptSemanticCallLiterals.js";
|
||||
|
||||
export type SemanticLiteralPrimitive = string | number | boolean | null;
|
||||
|
||||
/** Directed relation lists grouped by endpoint node ID. */
|
||||
export interface SemanticAdjacency {
|
||||
readonly outgoingByNode: ReadonlyMap<
|
||||
string,
|
||||
readonly JavaScriptSemanticGraphRelation[]
|
||||
>;
|
||||
readonly incomingByNode: ReadonlyMap<
|
||||
string,
|
||||
readonly JavaScriptSemanticGraphRelation[]
|
||||
>;
|
||||
}
|
||||
|
||||
/** Unknown frontiers split into node-bound and graph-wide records. */
|
||||
export interface SemanticUnknownIndex {
|
||||
readonly byNodeId: ReadonlyMap<
|
||||
string,
|
||||
readonly JavaScriptSemanticGraphUnknown[]
|
||||
>;
|
||||
readonly global: readonly JavaScriptSemanticGraphUnknown[];
|
||||
}
|
||||
|
||||
/** Pre-indexed seed candidate node IDs (sorted by Unicode code point). */
|
||||
export interface SemanticSeedIndex {
|
||||
readonly byApplicationNodeId: ReadonlyMap<string, readonly string[]>;
|
||||
readonly byFingerprint: ReadonlyMap<string, readonly string[]>;
|
||||
readonly byLiteral: ReadonlyMap<SemanticLiteralPrimitive, readonly string[]>;
|
||||
readonly byProperty: ReadonlyMap<string, readonly string[]>;
|
||||
readonly byEndpoint: ReadonlyMap<string, readonly string[]>;
|
||||
readonly byEvent: ReadonlyMap<string, readonly string[]>;
|
||||
readonly byBoundaryField: ReadonlyMap<string, readonly string[]>;
|
||||
}
|
||||
|
||||
/** Lazily populated lookup indexes for an immutable JavaScriptSemanticGraph. */
|
||||
export interface SemanticGraphIndex {
|
||||
getNodesById(): ReadonlyMap<string, JavaScriptSemanticGraphNode>;
|
||||
getContextsById(): ReadonlyMap<string, JavaScriptSemanticEvidenceContext>;
|
||||
getAdjacency(): SemanticAdjacency;
|
||||
getUnknowns(): SemanticUnknownIndex;
|
||||
getGlobalUnknowns(): readonly JavaScriptSemanticGraphUnknown[];
|
||||
getSeedIndex(): SemanticSeedIndex;
|
||||
}
|
||||
|
||||
const semanticGraphIndexes = new WeakMap<
|
||||
JavaScriptSemanticGraph,
|
||||
SemanticGraphIndex
|
||||
>();
|
||||
|
||||
/** Return a cached structural index when `graph` is an authenticated immutable snapshot. */
|
||||
export const getSemanticGraphIndex = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
): SemanticGraphIndex | undefined => {
|
||||
if (!isImmutableJsonSnapshot(graph)) return undefined;
|
||||
let index = semanticGraphIndexes.get(graph);
|
||||
if (index === undefined) {
|
||||
index = createSemanticGraphIndex(graph);
|
||||
semanticGraphIndexes.set(graph, index);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
/** Build outgoing and incoming relation adjacency lists in a single pass. */
|
||||
export const buildSemanticAdjacency = (
|
||||
relations: readonly JavaScriptSemanticGraphRelation[],
|
||||
): SemanticAdjacency => {
|
||||
const outgoingByNode = new Map<string, JavaScriptSemanticGraphRelation[]>();
|
||||
const incomingByNode = new Map<string, JavaScriptSemanticGraphRelation[]>();
|
||||
for (const relation of relations) {
|
||||
pushBucket(outgoingByNode, relation.source_node_id, relation);
|
||||
pushBucket(incomingByNode, relation.target_node_id, relation);
|
||||
}
|
||||
return { outgoingByNode, incomingByNode };
|
||||
};
|
||||
|
||||
const createSemanticGraphIndex = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
): SemanticGraphIndex => {
|
||||
let nodesById: ReadonlyMap<string, JavaScriptSemanticGraphNode> | undefined;
|
||||
let contextsById:
|
||||
| ReadonlyMap<string, JavaScriptSemanticEvidenceContext>
|
||||
| undefined;
|
||||
let adjacency: SemanticAdjacency | undefined;
|
||||
let unknownsIndex: SemanticUnknownIndex | undefined;
|
||||
let globalUnknowns: readonly JavaScriptSemanticGraphUnknown[] | undefined;
|
||||
let seedIndex: SemanticSeedIndex | undefined;
|
||||
|
||||
const getNodesById = (): ReadonlyMap<string, JavaScriptSemanticGraphNode> => {
|
||||
if (nodesById === undefined)
|
||||
nodesById = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
return nodesById;
|
||||
};
|
||||
|
||||
return {
|
||||
getNodesById,
|
||||
getContextsById: () => {
|
||||
if (contextsById === undefined)
|
||||
contextsById = new Map(
|
||||
graph.evidence_contexts.map((context) => [
|
||||
context.context_id,
|
||||
context,
|
||||
]),
|
||||
);
|
||||
return contextsById;
|
||||
},
|
||||
getAdjacency: () => {
|
||||
if (adjacency === undefined)
|
||||
adjacency = buildSemanticAdjacency(graph.relations);
|
||||
return adjacency;
|
||||
},
|
||||
getUnknowns: () => {
|
||||
if (unknownsIndex === undefined) {
|
||||
unknownsIndex = buildUnknownIndex(graph.unknowns);
|
||||
globalUnknowns = unknownsIndex.global;
|
||||
}
|
||||
return unknownsIndex;
|
||||
},
|
||||
getGlobalUnknowns: () => {
|
||||
if (globalUnknowns === undefined)
|
||||
globalUnknowns = graph.unknowns.filter(
|
||||
(unknown) => unknown.node_id === null,
|
||||
);
|
||||
return globalUnknowns;
|
||||
},
|
||||
getSeedIndex: () => {
|
||||
if (seedIndex === undefined)
|
||||
seedIndex = buildSeedIndex(graph, getNodesById());
|
||||
return seedIndex;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const buildUnknownIndex = (
|
||||
unknowns: readonly JavaScriptSemanticGraphUnknown[],
|
||||
): SemanticUnknownIndex => {
|
||||
const byNodeId = new Map<string, JavaScriptSemanticGraphUnknown[]>();
|
||||
const global: JavaScriptSemanticGraphUnknown[] = [];
|
||||
for (const unknown of unknowns) {
|
||||
if (unknown.node_id === null) global.push(unknown);
|
||||
else pushBucket(byNodeId, unknown.node_id, unknown);
|
||||
}
|
||||
return { byNodeId, global };
|
||||
};
|
||||
|
||||
const buildSeedIndex = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
nodesById: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
|
||||
): SemanticSeedIndex => {
|
||||
const byApplicationNodeId = new Map<string, string[]>();
|
||||
const byFingerprintSets = new Map<string, Set<string>>();
|
||||
const byLiteralSets = new Map<SemanticLiteralPrimitive, Set<string>>();
|
||||
const representedCalls = new Map<SemanticLiteralPrimitive, Set<string>>();
|
||||
const callSitesWithLiterals: JavaScriptSemanticGraphNode[] = [];
|
||||
const byProperty = new Map<string, string[]>();
|
||||
const byEndpoint = new Map<string, string[]>();
|
||||
const byEvent = new Map<string, string[]>();
|
||||
const byBoundaryField = new Map<string, string[]>();
|
||||
|
||||
const unresolvedAccesses = new Set<string>();
|
||||
for (const { family, node_id } of graph.unknowns)
|
||||
if (family === "object-flow" && node_id !== null)
|
||||
unresolvedAccesses.add(node_id);
|
||||
|
||||
for (const { fingerprint_sha256, function_node_id } of graph.fingerprints) {
|
||||
if (!nodesById.has(function_node_id)) continue;
|
||||
pushSetBucket(byFingerprintSets, fingerprint_sha256, function_node_id);
|
||||
}
|
||||
|
||||
for (const node of graph.nodes) {
|
||||
for (const appNodeId of node.application_node_ids)
|
||||
pushBucket(byApplicationNodeId, appNodeId, node.node_id);
|
||||
indexNodeByKind(node, {
|
||||
byLiteralSets,
|
||||
representedCalls,
|
||||
callSitesWithLiterals,
|
||||
byProperty,
|
||||
unresolvedAccesses,
|
||||
byEndpoint,
|
||||
byEvent,
|
||||
byBoundaryField,
|
||||
});
|
||||
}
|
||||
|
||||
for (const node of callSitesWithLiterals) {
|
||||
for (const value of semanticCallLiteralValues(node)) {
|
||||
if (representedCalls.get(value)?.has(node.node_id) === true) continue;
|
||||
pushSetBucket(byLiteralSets, value, node.node_id);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
byApplicationNodeId: sortStringBuckets(byApplicationNodeId),
|
||||
byFingerprint: sortSetBuckets(byFingerprintSets),
|
||||
byLiteral: sortSetBuckets(byLiteralSets),
|
||||
byProperty: sortStringBuckets(byProperty),
|
||||
byEndpoint: sortStringBuckets(byEndpoint),
|
||||
byEvent: sortStringBuckets(byEvent),
|
||||
byBoundaryField: sortStringBuckets(byBoundaryField),
|
||||
};
|
||||
};
|
||||
|
||||
interface KindIndexState {
|
||||
readonly byLiteralSets: Map<SemanticLiteralPrimitive, Set<string>>;
|
||||
readonly representedCalls: Map<SemanticLiteralPrimitive, Set<string>>;
|
||||
readonly callSitesWithLiterals: JavaScriptSemanticGraphNode[];
|
||||
readonly byProperty: Map<string, string[]>;
|
||||
readonly unresolvedAccesses: ReadonlySet<string>;
|
||||
readonly byEndpoint: Map<string, string[]>;
|
||||
readonly byEvent: Map<string, string[]>;
|
||||
readonly byBoundaryField: Map<string, string[]>;
|
||||
}
|
||||
|
||||
const indexNodeByKind = (
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
state: KindIndexState,
|
||||
): void => {
|
||||
if (node.kind === "literal") {
|
||||
const value = node.properties.value;
|
||||
if (isLiteralPrimitive(value))
|
||||
pushSetBucket(state.byLiteralSets, value, node.node_id);
|
||||
return;
|
||||
}
|
||||
if (node.kind === "expression") {
|
||||
const callSiteId = node.properties.literal_argument_call_site_node_id;
|
||||
const literalArg = node.properties.literal_argument_value;
|
||||
if (typeof callSiteId === "string" && isLiteralPrimitive(literalArg)) {
|
||||
pushSetBucket(state.representedCalls, literalArg, callSiteId);
|
||||
pushSetBucket(state.byLiteralSets, literalArg, node.node_id);
|
||||
}
|
||||
const path = node.properties.property_path;
|
||||
const slotless =
|
||||
node.properties.property_slot_resolution === "unresolved" ||
|
||||
(node.properties.property_slot_resolution === undefined &&
|
||||
state.unresolvedAccesses.has(node.node_id));
|
||||
if (slotless && Array.isArray(path)) {
|
||||
const last = path.at(-1);
|
||||
if (typeof last === "string")
|
||||
pushBucket(state.byProperty, last, node.node_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.kind === "call-site") {
|
||||
if (Array.isArray(node.properties.arguments))
|
||||
state.callSitesWithLiterals.push(node);
|
||||
return;
|
||||
}
|
||||
if (node.kind === "property-slot") {
|
||||
if (typeof node.properties.name === "string")
|
||||
pushBucket(state.byProperty, node.properties.name, node.node_id);
|
||||
return;
|
||||
}
|
||||
if (node.kind === "request" || node.kind === "response") {
|
||||
if (typeof node.properties.endpoint === "string")
|
||||
pushBucket(state.byEndpoint, node.properties.endpoint, node.node_id);
|
||||
return;
|
||||
}
|
||||
if (node.kind === "event" || node.kind === "listener") {
|
||||
if (typeof node.properties.event_name === "string")
|
||||
pushBucket(state.byEvent, node.properties.event_name, node.node_id);
|
||||
return;
|
||||
}
|
||||
if (node.kind === "boundary" && typeof node.properties.field === "string")
|
||||
pushBucket(state.byBoundaryField, node.properties.field, node.node_id);
|
||||
};
|
||||
|
||||
const isLiteralPrimitive = (
|
||||
value: unknown,
|
||||
): value is SemanticLiteralPrimitive =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean";
|
||||
|
||||
const pushBucket = <Key, Value>(
|
||||
map: Map<Key, Value[]>,
|
||||
key: Key,
|
||||
value: Value,
|
||||
): void => {
|
||||
const bucket = map.get(key);
|
||||
if (bucket === undefined) map.set(key, [value]);
|
||||
else bucket.push(value);
|
||||
};
|
||||
|
||||
const pushSetBucket = <Key>(
|
||||
map: Map<Key, Set<string>>,
|
||||
key: Key,
|
||||
value: string,
|
||||
): void => {
|
||||
let bucket = map.get(key);
|
||||
if (bucket === undefined) {
|
||||
bucket = new Set();
|
||||
map.set(key, bucket);
|
||||
}
|
||||
bucket.add(value);
|
||||
};
|
||||
|
||||
const sortStringBuckets = (
|
||||
buckets: Map<string, string[]>,
|
||||
): ReadonlyMap<string, readonly string[]> => {
|
||||
for (const list of buckets.values())
|
||||
if (list.length > 1) list.sort(compareUnicodeCodePoints);
|
||||
return buckets;
|
||||
};
|
||||
|
||||
const sortSetBuckets = <Key>(
|
||||
buckets: Map<Key, Set<string>>,
|
||||
): ReadonlyMap<Key, readonly string[]> => {
|
||||
const sorted = new Map<Key, readonly string[]>();
|
||||
for (const [key, set] of buckets) {
|
||||
const list = [...set];
|
||||
if (list.length > 1) list.sort(compareUnicodeCodePoints);
|
||||
sorted.set(key, list);
|
||||
}
|
||||
return sorted;
|
||||
};
|
||||
@@ -4,7 +4,8 @@ import {
|
||||
semanticGraphTestEvidence,
|
||||
unknownSemanticGraphTestEvidence,
|
||||
} from "../../../tests/support/javascriptSemanticGraphFixture.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { freezeJsonSnapshot } from "../immutableJson.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
@@ -559,3 +560,113 @@ it("keeps candidate uncertainty at the end of a long reachable path", () => {
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
describe("immutable SemanticGraphIndex parity and empty seed fast-exit", () => {
|
||||
it("matches mutable query results across seed kinds and directions", () => {
|
||||
const mutable = graphWithCandidateEdge();
|
||||
const immutable = freezeJsonSnapshot(structuredClone(mutable));
|
||||
const seedNode = mutable.nodes[0];
|
||||
const literalNode = mutable.nodes.find(({ kind }) => kind === "literal");
|
||||
if (seedNode === undefined || literalNode === undefined)
|
||||
throw new TypeError("Missing fixture nodes");
|
||||
|
||||
const queries = [
|
||||
{ kind: "semantic-node", node_id: seedNode.node_id },
|
||||
{
|
||||
kind: "literal",
|
||||
value: literalNode.properties.value ?? literalNode.label ?? "",
|
||||
},
|
||||
{ kind: "property", name: "token" },
|
||||
{ kind: "endpoint", value: "https://example.invalid" },
|
||||
{ kind: "boundary-field", field: "authorization" },
|
||||
] as const;
|
||||
|
||||
for (const seed of queries)
|
||||
for (const direction of [
|
||||
"backward-provenance",
|
||||
"forward-influence",
|
||||
"callers",
|
||||
"ownership",
|
||||
] as const) {
|
||||
const input = javaScriptSemanticQueryInputSchema.parse({
|
||||
seed,
|
||||
direction,
|
||||
include_ambiguous_dynamic_edges: true,
|
||||
});
|
||||
const expected = queryJavaScriptSemanticGraph(mutable, input);
|
||||
expect(queryJavaScriptSemanticGraph(immutable, input)).toEqual(
|
||||
expected,
|
||||
);
|
||||
expect(queryJavaScriptSemanticGraph(immutable, input)).toEqual(
|
||||
expected,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("fast-exits on empty seed match while retaining only graph-wide unknowns", () => {
|
||||
const original = semanticFixtureGraph(true);
|
||||
const evidenceContexts = registryForGraph(original);
|
||||
const existing = original.nodes[0];
|
||||
const baseUnknown = original.unknowns[0];
|
||||
if (existing === undefined || baseUnknown === undefined)
|
||||
throw new TypeError("Missing fixture node or unknown");
|
||||
const nodeUnknown = createJavaScriptSemanticGraphUnknown(
|
||||
{
|
||||
family: baseUnknown.family,
|
||||
relation_kinds: baseUnknown.relation_kinds,
|
||||
reason: baseUnknown.reason,
|
||||
detail: "Scoped to node",
|
||||
node_id: existing.node_id,
|
||||
candidate_node_ids: [],
|
||||
evidence: unknownSemanticGraphTestEvidence(),
|
||||
},
|
||||
evidenceContexts,
|
||||
);
|
||||
const globalUnknown = createJavaScriptSemanticGraphUnknown(
|
||||
{
|
||||
family: baseUnknown.family,
|
||||
relation_kinds: baseUnknown.relation_kinds,
|
||||
reason: baseUnknown.reason,
|
||||
detail: "Graph-wide unknown",
|
||||
node_id: null,
|
||||
candidate_node_ids: [],
|
||||
evidence: unknownSemanticGraphTestEvidence(),
|
||||
},
|
||||
evidenceContexts,
|
||||
);
|
||||
const mutable = createJavaScriptSemanticGraph({
|
||||
...constructionInput(original),
|
||||
unknowns: [...original.unknowns, nodeUnknown, globalUnknown],
|
||||
coverage: {
|
||||
...original.coverage,
|
||||
families: original.coverage.families.map((family) =>
|
||||
family.family === baseUnknown.family
|
||||
? {
|
||||
...family,
|
||||
unknown_ids: [
|
||||
...family.unknown_ids,
|
||||
nodeUnknown.unknown_id,
|
||||
globalUnknown.unknown_id,
|
||||
],
|
||||
}
|
||||
: family,
|
||||
),
|
||||
},
|
||||
evidence_contexts: evidenceContexts.contexts,
|
||||
});
|
||||
const immutable = freezeJsonSnapshot(structuredClone(mutable));
|
||||
const missInput = javaScriptSemanticQueryInputSchema.parse({
|
||||
seed: {
|
||||
kind: "semantic-node",
|
||||
node_id: `jsrg_node_${"f".repeat(64)}`,
|
||||
},
|
||||
direction: "forward-influence",
|
||||
});
|
||||
const mutableRes = queryJavaScriptSemanticGraph(mutable, missInput);
|
||||
const immutableRes = queryJavaScriptSemanticGraph(immutable, missInput);
|
||||
expect(immutableRes).toEqual(mutableRes);
|
||||
const ids = immutableRes.unknowns.map((u) => u.unknown_id);
|
||||
expect(ids).toContain(globalUnknown.unknown_id);
|
||||
expect(ids).not.toContain(nodeUnknown.unknown_id);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,13 @@
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptSemanticGraph } from "./javascriptSemanticGraph.js";
|
||||
import {
|
||||
buildSemanticAdjacency,
|
||||
getSemanticGraphIndex,
|
||||
type SemanticAdjacency,
|
||||
type SemanticGraphIndex,
|
||||
} from "./javascriptSemanticGraphIndex.js";
|
||||
import type {
|
||||
JavaScriptSemanticEvidenceContext,
|
||||
JavaScriptSemanticGraphNode,
|
||||
JavaScriptSemanticGraphRelation,
|
||||
JavaScriptSemanticGraphUnknown,
|
||||
@@ -16,21 +24,13 @@ import {
|
||||
resolveJavaScriptSemanticQuerySeeds as resolveSeeds,
|
||||
} from "./javascriptSemanticQueryIdentity.js";
|
||||
|
||||
interface TraversalEntry {
|
||||
readonly relation: JavaScriptSemanticGraphRelation;
|
||||
readonly nextNodeId: string;
|
||||
}
|
||||
|
||||
interface Traversal {
|
||||
readonly nodeIds: Set<string>;
|
||||
readonly relationIds: Set<string>;
|
||||
readonly functionIds: Set<string>;
|
||||
readonly modules: Set<string>;
|
||||
}
|
||||
|
||||
interface QueryResult {
|
||||
readonly retainedNodes: JavaScriptSemanticGraphNode[];
|
||||
readonly retainedRelations: JavaScriptSemanticGraphRelation[];
|
||||
readonly functionIds: Set<string>;
|
||||
readonly modules: Set<string>;
|
||||
readonly candidateRelations: number;
|
||||
}
|
||||
|
||||
/** Run a query already parsed by its owning request boundary. */
|
||||
@@ -40,37 +40,52 @@ export const queryJavaScriptSemanticGraph = (
|
||||
): JavaScriptSemanticQueryResult => {
|
||||
const queryId = queryIdentifier(graph, input);
|
||||
const seeds = resolveSeeds(graph, input);
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const adjacency = buildAdjacency(graph.relations, input);
|
||||
const traversal = traverse(nodes, seeds, adjacency);
|
||||
const result = createQueryResult(graph, traversal);
|
||||
const index = getSemanticGraphIndex(graph);
|
||||
const allowed =
|
||||
input.allowed_relations === undefined
|
||||
? null
|
||||
: new Set(input.allowed_relations);
|
||||
if (seeds.length === 0)
|
||||
return buildEmptySeedQueryResult(graph, input, queryId, index, allowed);
|
||||
|
||||
const nodes =
|
||||
index !== undefined
|
||||
? index.getNodesById()
|
||||
: new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const adjacency =
|
||||
index !== undefined
|
||||
? index.getAdjacency()
|
||||
: buildSemanticAdjacency(graph.relations);
|
||||
const traversal = traverse(nodes, seeds, adjacency, input, allowed);
|
||||
const relevantUnknowns = relevantUnknownFrontiers(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
input,
|
||||
);
|
||||
const candidateRelations = relevantCandidateRelationCount(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
input,
|
||||
input.direction,
|
||||
allowed,
|
||||
index,
|
||||
);
|
||||
const expectedMatches = expectedMatchesFor(
|
||||
result.retainedNodes,
|
||||
result.retainedRelations,
|
||||
traversal.retainedNodes,
|
||||
traversal.retainedRelations,
|
||||
input,
|
||||
);
|
||||
const retainedContextIds = new Set([
|
||||
...result.retainedNodes.map(({ evidence }) => evidence.context_id),
|
||||
...result.retainedRelations.map(({ evidence }) => evidence.context_id),
|
||||
...relevantUnknowns.map(({ evidence }) => evidence.context_id),
|
||||
]);
|
||||
const retainedContextIds = collectContextIds(
|
||||
traversal.retainedNodes,
|
||||
traversal.retainedRelations,
|
||||
relevantUnknowns,
|
||||
);
|
||||
const evidenceContexts = selectEvidenceContexts(
|
||||
graph,
|
||||
retainedContextIds,
|
||||
index,
|
||||
);
|
||||
const assessment = assessJavaScriptSemanticQuery({
|
||||
graph,
|
||||
totalSeeds: seeds.length,
|
||||
expectedMatches: expectedMatches.length,
|
||||
hasExpectation: input.expected !== null,
|
||||
unknowns: relevantUnknowns,
|
||||
candidateRelations,
|
||||
candidateRelations: traversal.candidateRelations,
|
||||
});
|
||||
return javaScriptSemanticQueryResultSchema.parse({
|
||||
query_id: queryId,
|
||||
@@ -79,17 +94,15 @@ export const queryJavaScriptSemanticGraph = (
|
||||
direction: input.direction,
|
||||
status: assessment.status,
|
||||
seed_node_ids: seeds,
|
||||
evidence_contexts: graph.evidence_contexts.filter(({ context_id }) =>
|
||||
retainedContextIds.has(context_id),
|
||||
),
|
||||
nodes: result.retainedNodes,
|
||||
relations: result.retainedRelations,
|
||||
evidence_contexts: evidenceContexts,
|
||||
nodes: traversal.retainedNodes,
|
||||
relations: traversal.retainedRelations,
|
||||
unknowns: relevantUnknowns,
|
||||
expected_match_node_ids: expectedMatches.map(({ node_id }) => node_id),
|
||||
summary: {
|
||||
total_seed_matches: seeds.length,
|
||||
traversed_nodes: traversal.nodeIds.size,
|
||||
traversed_relations: traversal.relationIds.size,
|
||||
traversed_relations: traversal.retainedRelations.length,
|
||||
traversed_functions: traversal.functionIds.size,
|
||||
traversed_modules: traversal.modules.size,
|
||||
relevant_unknowns: relevantUnknowns.length,
|
||||
@@ -99,161 +112,205 @@ export const queryJavaScriptSemanticGraph = (
|
||||
});
|
||||
};
|
||||
|
||||
const createQueryResult = (
|
||||
const buildEmptySeedQueryResult = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
traversal: Traversal,
|
||||
): QueryResult => {
|
||||
const retainedNodes = graph.nodes.filter(({ node_id }) =>
|
||||
traversal.nodeIds.has(node_id),
|
||||
);
|
||||
const retainedRelations = graph.relations.filter(({ relation_id }) =>
|
||||
traversal.relationIds.has(relation_id),
|
||||
);
|
||||
return { retainedNodes, retainedRelations };
|
||||
};
|
||||
|
||||
const buildAdjacency = (
|
||||
relations: readonly JavaScriptSemanticGraphRelation[],
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): ReadonlyMap<string, TraversalEntry[]> => {
|
||||
const adjacency = new Map<string, TraversalEntry[]>();
|
||||
const allowed =
|
||||
input.allowed_relations === undefined
|
||||
? null
|
||||
: new Set(input.allowed_relations);
|
||||
for (const relation of relations) {
|
||||
if (allowed !== null && !allowed.has(relation.relation)) continue;
|
||||
if (
|
||||
relation.resolution === "candidate" &&
|
||||
!input.include_ambiguous_dynamic_edges
|
||||
)
|
||||
continue;
|
||||
addDirectedEntries(adjacency, relation, input.direction);
|
||||
}
|
||||
return adjacency;
|
||||
};
|
||||
|
||||
const addDirectedEntries = (
|
||||
adjacency: Map<string, TraversalEntry[]>,
|
||||
relation: JavaScriptSemanticGraphRelation,
|
||||
direction: JavaScriptSemanticQueryInput["direction"],
|
||||
): void => {
|
||||
if (direction === "callers") {
|
||||
if (relation.relation === "calls")
|
||||
addEntry(
|
||||
adjacency,
|
||||
relation.target_node_id,
|
||||
relation.source_node_id,
|
||||
relation,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (direction === "ownership") {
|
||||
if (!ownershipRelation(relation.relation)) return;
|
||||
addEntry(
|
||||
adjacency,
|
||||
relation.source_node_id,
|
||||
relation.target_node_id,
|
||||
relation,
|
||||
);
|
||||
addEntry(
|
||||
adjacency,
|
||||
relation.target_node_id,
|
||||
relation.source_node_id,
|
||||
relation,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (direction === "backward-provenance")
|
||||
addEntry(
|
||||
adjacency,
|
||||
relation.target_node_id,
|
||||
relation.source_node_id,
|
||||
relation,
|
||||
);
|
||||
else
|
||||
addEntry(
|
||||
adjacency,
|
||||
relation.source_node_id,
|
||||
relation.target_node_id,
|
||||
relation,
|
||||
);
|
||||
};
|
||||
|
||||
const addEntry = (
|
||||
adjacency: Map<string, TraversalEntry[]>,
|
||||
from: string,
|
||||
nextNodeId: string,
|
||||
relation: JavaScriptSemanticGraphRelation,
|
||||
): void => {
|
||||
const entries = adjacency.get(from) ?? [];
|
||||
entries.push({ relation, nextNodeId });
|
||||
adjacency.set(from, entries);
|
||||
queryId: string,
|
||||
index: SemanticGraphIndex | undefined,
|
||||
allowed: ReadonlySet<JavaScriptSemanticGraphRelation["relation"]> | null,
|
||||
): JavaScriptSemanticQueryResult => {
|
||||
const globalUnknowns =
|
||||
index !== undefined
|
||||
? index.getGlobalUnknowns()
|
||||
: graph.unknowns.filter((unknown) => unknown.node_id === null);
|
||||
const relevantUnknowns = globalUnknowns.filter((unknown) =>
|
||||
unknownMatchesFilter(unknown, input.direction, allowed),
|
||||
);
|
||||
const evidenceContexts =
|
||||
relevantUnknowns.length === 0
|
||||
? []
|
||||
: selectEvidenceContexts(
|
||||
graph,
|
||||
collectContextIds([], [], relevantUnknowns),
|
||||
index,
|
||||
);
|
||||
const assessment = assessJavaScriptSemanticQuery({
|
||||
graph,
|
||||
totalSeeds: 0,
|
||||
expectedMatches: 0,
|
||||
hasExpectation: input.expected !== null,
|
||||
unknowns: relevantUnknowns,
|
||||
candidateRelations: 0,
|
||||
});
|
||||
return javaScriptSemanticQueryResultSchema.parse({
|
||||
query_id: queryId,
|
||||
source_graph_id: graph.graph_id,
|
||||
seed: input.seed,
|
||||
direction: input.direction,
|
||||
status: assessment.status,
|
||||
seed_node_ids: [],
|
||||
evidence_contexts: evidenceContexts,
|
||||
nodes: [],
|
||||
relations: [],
|
||||
unknowns: relevantUnknowns,
|
||||
expected_match_node_ids: [],
|
||||
summary: {
|
||||
total_seed_matches: 0,
|
||||
traversed_nodes: 0,
|
||||
traversed_relations: 0,
|
||||
traversed_functions: 0,
|
||||
traversed_modules: 0,
|
||||
relevant_unknowns: relevantUnknowns.length,
|
||||
},
|
||||
coverage: assessment.coverage,
|
||||
limitations: assessment.limitations,
|
||||
});
|
||||
};
|
||||
|
||||
const traverse = (
|
||||
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
|
||||
seeds: readonly string[],
|
||||
adjacency: ReadonlyMap<string, TraversalEntry[]>,
|
||||
adjacency: SemanticAdjacency,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
allowed: ReadonlySet<JavaScriptSemanticGraphRelation["relation"]> | null,
|
||||
): Traversal => {
|
||||
const nodeIds = new Set(seeds);
|
||||
const relationIds = new Set<string>();
|
||||
const retainedNodes: JavaScriptSemanticGraphNode[] = [];
|
||||
const retainedRelationsMap = new Map<
|
||||
string,
|
||||
JavaScriptSemanticGraphRelation
|
||||
>();
|
||||
const functionIds = new Set<string>();
|
||||
const modules = new Set<string>();
|
||||
const queue = [...nodeIds];
|
||||
for (const nodeId of nodeIds)
|
||||
retainOwners(nodes.get(nodeId), functionIds, modules);
|
||||
for (const nodeId of nodeIds) {
|
||||
const node = nodes.get(nodeId);
|
||||
if (node !== undefined) {
|
||||
retainedNodes.push(node);
|
||||
retainOwners(node, functionIds, modules);
|
||||
}
|
||||
}
|
||||
const direction = input.direction;
|
||||
const includeCandidates = input.include_ambiguous_dynamic_edges;
|
||||
const seenCandidateIds =
|
||||
direction === "ownership" ? new Set<string>() : undefined;
|
||||
let candidateRelations = 0;
|
||||
|
||||
const visitIncident = (
|
||||
relation: JavaScriptSemanticGraphRelation,
|
||||
nextNodeId: string,
|
||||
): void => {
|
||||
if (allowed !== null && !allowed.has(relation.relation)) return;
|
||||
if (relation.resolution === "candidate") {
|
||||
if (seenCandidateIds === undefined) candidateRelations += 1;
|
||||
else if (!seenCandidateIds.has(relation.relation_id)) {
|
||||
seenCandidateIds.add(relation.relation_id);
|
||||
candidateRelations += 1;
|
||||
}
|
||||
if (!includeCandidates) return;
|
||||
}
|
||||
retainedRelationsMap.set(relation.relation_id, relation);
|
||||
if (nodeIds.has(nextNodeId)) return;
|
||||
const nextNode = nodes.get(nextNodeId);
|
||||
if (nextNode === undefined) return;
|
||||
nodeIds.add(nextNodeId);
|
||||
retainedNodes.push(nextNode);
|
||||
retainOwners(nextNode, functionIds, modules);
|
||||
queue.push(nextNodeId);
|
||||
};
|
||||
|
||||
for (let offset = 0; offset < queue.length; offset += 1) {
|
||||
const current = queue[offset];
|
||||
if (current === undefined) continue;
|
||||
for (const entry of adjacency.get(current) ?? []) {
|
||||
relationIds.add(entry.relation.relation_id);
|
||||
if (nodeIds.has(entry.nextNodeId)) continue;
|
||||
const node = nodes.get(entry.nextNodeId);
|
||||
if (node === undefined) continue;
|
||||
nodeIds.add(entry.nextNodeId);
|
||||
retainOwners(node, functionIds, modules);
|
||||
queue.push(entry.nextNodeId);
|
||||
if (direction === "forward-influence") {
|
||||
for (const relation of adjacency.outgoingByNode.get(current) ?? [])
|
||||
visitIncident(relation, relation.target_node_id);
|
||||
} else if (direction === "backward-provenance") {
|
||||
for (const relation of adjacency.incomingByNode.get(current) ?? [])
|
||||
visitIncident(relation, relation.source_node_id);
|
||||
} else if (direction === "callers") {
|
||||
for (const relation of adjacency.incomingByNode.get(current) ?? [])
|
||||
if (relation.relation === "calls")
|
||||
visitIncident(relation, relation.source_node_id);
|
||||
} else {
|
||||
for (const relation of adjacency.outgoingByNode.get(current) ?? [])
|
||||
if (ownershipRelation(relation.relation))
|
||||
visitIncident(relation, relation.target_node_id);
|
||||
for (const relation of adjacency.incomingByNode.get(current) ?? [])
|
||||
if (ownershipRelation(relation.relation))
|
||||
visitIncident(relation, relation.source_node_id);
|
||||
}
|
||||
}
|
||||
|
||||
if (retainedNodes.length > 1)
|
||||
retainedNodes.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.node_id, right.node_id),
|
||||
);
|
||||
const retainedRelations = [...retainedRelationsMap.values()];
|
||||
if (retainedRelations.length > 1)
|
||||
retainedRelations.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.relation_id, right.relation_id),
|
||||
);
|
||||
return {
|
||||
nodeIds,
|
||||
relationIds,
|
||||
retainedNodes,
|
||||
retainedRelations,
|
||||
functionIds,
|
||||
modules,
|
||||
candidateRelations,
|
||||
};
|
||||
};
|
||||
|
||||
const retainOwners = (
|
||||
node: JavaScriptSemanticGraphNode | undefined,
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
functions: Set<string>,
|
||||
modules: Set<string>,
|
||||
): void => {
|
||||
if (node === undefined) return;
|
||||
const functionId =
|
||||
node.kind === "function" ? node.node_id : node.function_node_id;
|
||||
if (functionId !== null) functions.add(functionId);
|
||||
modules.add(node.identity.module_path);
|
||||
};
|
||||
|
||||
const unknownMatchesFilter = (
|
||||
unknown: JavaScriptSemanticGraphUnknown,
|
||||
direction: JavaScriptSemanticQueryInput["direction"],
|
||||
allowed: ReadonlySet<JavaScriptSemanticGraphRelation["relation"]> | null,
|
||||
): boolean =>
|
||||
unknown.relation_kinds.some(
|
||||
(relation) =>
|
||||
directionAllowsRelation(direction, relation) &&
|
||||
(allowed === null || allowed.has(relation)),
|
||||
);
|
||||
|
||||
const relevantUnknownFrontiers = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
nodeIds: ReadonlySet<string>,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
direction: JavaScriptSemanticQueryInput["direction"],
|
||||
allowed: ReadonlySet<JavaScriptSemanticGraphRelation["relation"]> | null,
|
||||
index: SemanticGraphIndex | undefined,
|
||||
): JavaScriptSemanticGraphUnknown[] => {
|
||||
const allowed =
|
||||
input.allowed_relations === undefined
|
||||
? null
|
||||
: new Set(input.allowed_relations);
|
||||
return graph.unknowns.filter(
|
||||
(unknown) =>
|
||||
(unknown.node_id === null || nodeIds.has(unknown.node_id)) &&
|
||||
unknown.relation_kinds.some(
|
||||
(relation) =>
|
||||
directionAllowsRelation(input.direction, relation) &&
|
||||
(allowed === null || allowed.has(relation)),
|
||||
),
|
||||
);
|
||||
if (index === undefined)
|
||||
return graph.unknowns.filter(
|
||||
(unknown) =>
|
||||
(unknown.node_id === null || nodeIds.has(unknown.node_id)) &&
|
||||
unknownMatchesFilter(unknown, direction, allowed),
|
||||
);
|
||||
const unknownsIndex = index.getUnknowns();
|
||||
const retained: JavaScriptSemanticGraphUnknown[] = [];
|
||||
for (const unknown of unknownsIndex.global)
|
||||
if (unknownMatchesFilter(unknown, direction, allowed))
|
||||
retained.push(unknown);
|
||||
for (const nodeId of nodeIds) {
|
||||
for (const unknown of unknownsIndex.byNodeId.get(nodeId) ?? [])
|
||||
if (unknownMatchesFilter(unknown, direction, allowed))
|
||||
retained.push(unknown);
|
||||
}
|
||||
if (retained.length > 1)
|
||||
retained.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
|
||||
);
|
||||
return retained;
|
||||
};
|
||||
|
||||
const directionAllowsRelation = (
|
||||
@@ -266,37 +323,39 @@ const directionAllowsRelation = (
|
||||
? ownershipRelation(relation)
|
||||
: true;
|
||||
|
||||
const relevantCandidateRelationCount = (
|
||||
const collectContextIds = (
|
||||
nodes: readonly JavaScriptSemanticGraphNode[],
|
||||
relations: readonly JavaScriptSemanticGraphRelation[],
|
||||
unknowns: readonly JavaScriptSemanticGraphUnknown[],
|
||||
): Set<string> => {
|
||||
const ids = new Set<string>();
|
||||
for (const node of nodes) ids.add(node.evidence.context_id);
|
||||
for (const relation of relations) ids.add(relation.evidence.context_id);
|
||||
for (const unknown of unknowns) ids.add(unknown.evidence.context_id);
|
||||
return ids;
|
||||
};
|
||||
|
||||
const selectEvidenceContexts = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
nodeIds: ReadonlySet<string>,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): number => {
|
||||
const allowed =
|
||||
input.allowed_relations === undefined
|
||||
? null
|
||||
: new Set(input.allowed_relations);
|
||||
let relevant = 0;
|
||||
for (const relation of graph.relations) {
|
||||
if (
|
||||
relation.resolution !== "candidate" ||
|
||||
(allowed !== null && !allowed.has(relation.relation))
|
||||
)
|
||||
continue;
|
||||
const sourceIsRelevant = nodeIds.has(relation.source_node_id);
|
||||
const targetIsRelevant = nodeIds.has(relation.target_node_id);
|
||||
if (
|
||||
(input.direction === "callers" &&
|
||||
relation.relation === "calls" &&
|
||||
targetIsRelevant) ||
|
||||
(input.direction === "ownership" &&
|
||||
ownershipRelation(relation.relation) &&
|
||||
(sourceIsRelevant || targetIsRelevant)) ||
|
||||
(input.direction === "backward-provenance" && targetIsRelevant) ||
|
||||
(input.direction === "forward-influence" && sourceIsRelevant)
|
||||
)
|
||||
relevant += 1;
|
||||
contextIds: ReadonlySet<string>,
|
||||
index: SemanticGraphIndex | undefined,
|
||||
): JavaScriptSemanticEvidenceContext[] => {
|
||||
if (contextIds.size === 0) return [];
|
||||
if (index === undefined)
|
||||
return graph.evidence_contexts.filter(({ context_id }) =>
|
||||
contextIds.has(context_id),
|
||||
);
|
||||
const contextsById = index.getContextsById();
|
||||
const retained: JavaScriptSemanticEvidenceContext[] = [];
|
||||
for (const contextId of contextIds) {
|
||||
const context = contextsById.get(contextId);
|
||||
if (context !== undefined) retained.push(context);
|
||||
}
|
||||
return relevant;
|
||||
if (retained.length > 1)
|
||||
retained.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.context_id, right.context_id),
|
||||
);
|
||||
return retained;
|
||||
};
|
||||
|
||||
const expectedMatchesFor = (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { digestCanonicalValue } from "../canonicalDigest.js";
|
||||
|
||||
import type { JavaScriptSemanticGraph } from "./javascriptSemanticGraph.js";
|
||||
import type { JavaScriptSemanticGraphNode } from "./javascriptSemanticGraphSchemas.js";
|
||||
import { getSemanticGraphIndex } from "./javascriptSemanticGraphIndex.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptSemanticQueryInput } from "./javascriptSemanticQuerySchemas.js";
|
||||
@@ -38,6 +39,8 @@ export const resolveJavaScriptSemanticQuerySeeds = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): string[] => {
|
||||
const index = getSemanticGraphIndex(graph);
|
||||
if (index !== undefined) return resolveIndexedSeeds(index, input.seed);
|
||||
const fingerprintFunctions = new Set(
|
||||
input.seed.kind === "function"
|
||||
? graph.fingerprints
|
||||
@@ -82,6 +85,29 @@ export const resolveJavaScriptSemanticQuerySeeds = (
|
||||
.sort(compareUnicodeCodePoints);
|
||||
};
|
||||
|
||||
const resolveIndexedSeeds = (
|
||||
index: NonNullable<ReturnType<typeof getSemanticGraphIndex>>,
|
||||
seed: JavaScriptSemanticQueryInput["seed"],
|
||||
): string[] => {
|
||||
if (seed.kind === "semantic-node") {
|
||||
const node = index.getNodesById().get(seed.node_id);
|
||||
return node === undefined ? [] : [node.node_id];
|
||||
}
|
||||
const seeds = index.getSeedIndex();
|
||||
if (seed.kind === "application-node")
|
||||
return [...(seeds.byApplicationNodeId.get(seed.node_id) ?? [])];
|
||||
if (seed.kind === "function")
|
||||
return [...(seeds.byFingerprint.get(seed.fingerprint_sha256) ?? [])];
|
||||
if (seed.kind === "literal")
|
||||
return [...(seeds.byLiteral.get(seed.value) ?? [])];
|
||||
if (seed.kind === "property")
|
||||
return [...(seeds.byProperty.get(seed.name) ?? [])];
|
||||
if (seed.kind === "endpoint")
|
||||
return [...(seeds.byEndpoint.get(seed.value) ?? [])];
|
||||
if (seed.kind === "event") return [...(seeds.byEvent.get(seed.name) ?? [])];
|
||||
return [...(seeds.byBoundaryField.get(seed.field) ?? [])];
|
||||
};
|
||||
|
||||
const seedMatches = (
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
|
||||
@@ -364,3 +364,46 @@ it.each(["ggggggEAAA", "gggggggBAAA"])(
|
||||
).toThrow(/32-bit/u);
|
||||
},
|
||||
);
|
||||
|
||||
describe("binary search on dense single-line source maps", () => {
|
||||
it("resolves exact, gap, tail, duplicate, and prior-line fallback positions", () => {
|
||||
const denseMappings = `AAAA,${Array.from({ length: 1999 }, () => "EAAE").join(",")};UAAA`;
|
||||
const denseMap = {
|
||||
version: 3,
|
||||
sources: ["dense.ts"],
|
||||
names: [],
|
||||
mappings: denseMappings,
|
||||
};
|
||||
expect(trace(denseMap, { line: 1, column: 2469 }).matches[0]).toMatchObject(
|
||||
{
|
||||
reported_source: "dense.ts",
|
||||
original_position: { line: 1, column: 2468 },
|
||||
},
|
||||
);
|
||||
expect(trace(denseMap, { line: 1, column: 5000 }).matches[0]).toMatchObject(
|
||||
{
|
||||
original_position: { line: 1, column: 3998 },
|
||||
},
|
||||
);
|
||||
expect(trace(denseMap, { line: 2, column: 1 }).matches[0]).toMatchObject({
|
||||
original_position: { line: 1, column: 3998 },
|
||||
});
|
||||
const duplicateColumnMap = {
|
||||
version: 3,
|
||||
sources: ["dup.ts"],
|
||||
names: [],
|
||||
mappings: "AAAA,AAEC,AAAC",
|
||||
};
|
||||
expect(
|
||||
trace(duplicateColumnMap, { line: 1, column: 0 }).matches.map((m) =>
|
||||
m.state === "mapped"
|
||||
? [m.original_position.line, m.original_position.column]
|
||||
: null,
|
||||
),
|
||||
).toEqual([
|
||||
[1, 0],
|
||||
[3, 1],
|
||||
[3, 2],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,12 @@ import {
|
||||
import { decodeValidatedSourceMapLeaves } from "../../domain/decodedSourceMap.js";
|
||||
import { sha256Hex } from "../../kernel/sha256Hex.js";
|
||||
|
||||
const traceMappingVersion = z
|
||||
.object({ version: z.string().min(1) })
|
||||
.parse(
|
||||
createRequire(import.meta.url)("@jridgewell/trace-mapping/package.json"),
|
||||
).version;
|
||||
|
||||
/** Decode with the pinned upstream codec; preserve every equal-position candidate. */
|
||||
export const traceSourceMap = (
|
||||
text: string,
|
||||
@@ -42,38 +48,39 @@ export const traceSourceMap = (
|
||||
if (matched !== null) {
|
||||
const line = matched.line - leaf.offset.line - 1;
|
||||
const column = matched.column - (line === 0 ? leaf.offset.column : 0);
|
||||
for (const segment of rows[line] ?? []) {
|
||||
if (segment[0] !== column) continue;
|
||||
const match = originalMatch(
|
||||
segment,
|
||||
map,
|
||||
url,
|
||||
inspected.declarations,
|
||||
sourceBase,
|
||||
);
|
||||
bytes += Buffer.byteLength(JSON.stringify(match)) + 1;
|
||||
if (bytes > limits.outputBytes)
|
||||
throw sourceMapLimitFailure(
|
||||
`Complete source-map point evidence exceeds output admission; no partial evidence was returned.`,
|
||||
"output_bytes",
|
||||
limits.outputBytes,
|
||||
);
|
||||
matches.push(match);
|
||||
const row = line >= 0 ? rows[line] : undefined;
|
||||
if (row !== undefined && row.length > 0) {
|
||||
const start = firstSegmentIndexAt(row, column);
|
||||
if (start !== -1) {
|
||||
for (let index = start; index < row.length; index += 1) {
|
||||
const segment = row[index]!;
|
||||
if (segment[0] !== column) break;
|
||||
const match = originalMatch(
|
||||
segment,
|
||||
map,
|
||||
url,
|
||||
inspected.declarations,
|
||||
sourceBase,
|
||||
);
|
||||
bytes += Buffer.byteLength(JSON.stringify(match)) + 1;
|
||||
if (bytes > limits.outputBytes)
|
||||
throw sourceMapLimitFailure(
|
||||
`Complete source-map point evidence exceeds output admission; no partial evidence was returned.`,
|
||||
"output_bytes",
|
||||
limits.outputBytes,
|
||||
);
|
||||
matches.push(match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sourceBase += leaf.map.sources.length;
|
||||
}
|
||||
const metadata: unknown = createRequire(import.meta.url)(
|
||||
"@jridgewell/trace-mapping/package.json",
|
||||
);
|
||||
const version = z
|
||||
.object({ version: z.string().min(1) })
|
||||
.parse(metadata).version;
|
||||
const runtime = javaScriptRuntime(process.versions);
|
||||
return webSourceMapReportSchema.parse({
|
||||
source_map_sha256: sha256Hex(text),
|
||||
url_context: url,
|
||||
engine: { id: "jridgewell-trace-mapping", version },
|
||||
engine: { id: "jridgewell-trace-mapping", version: traceMappingVersion },
|
||||
// Bun reports V8-shaped heap statistics but ignores the codec's heap flags.
|
||||
// Its launcher applies the same runtime policy, and the parent verifies it.
|
||||
runtime:
|
||||
@@ -115,12 +122,19 @@ const greatestPosition = (
|
||||
for (const { leaf, rows } of leaves) {
|
||||
const localLine = position.line - leaf.offset.line - 1;
|
||||
for (let line = Math.min(localLine, rows.length - 1); line >= 0; line--) {
|
||||
const row = rows[line];
|
||||
if (row === undefined || row.length === 0) continue;
|
||||
const lineOffset = line === 0 ? leaf.offset.column : 0;
|
||||
let column: number | undefined;
|
||||
for (const segment of rows[line] ?? []) {
|
||||
const absoluteColumn =
|
||||
segment[0] + (line === 0 ? leaf.offset.column : 0);
|
||||
if (line < localLine || absoluteColumn <= position.column)
|
||||
column = absoluteColumn;
|
||||
if (line < localLine) {
|
||||
// Rows from @jridgewell/trace-mapping are sorted by column; the last entry is greatest.
|
||||
column = row[row.length - 1]![0] + lineOffset;
|
||||
} else {
|
||||
const index = greatestSegmentIndexAtOrBefore(
|
||||
row,
|
||||
position.column - lineOffset,
|
||||
);
|
||||
if (index >= 0) column = row[index]![0] + lineOffset;
|
||||
}
|
||||
if (column === undefined) continue;
|
||||
const absoluteLine = leaf.offset.line + line + 1;
|
||||
@@ -135,6 +149,49 @@ const greatestPosition = (
|
||||
}
|
||||
return matched;
|
||||
};
|
||||
|
||||
/** Largest index in column-sorted `row` with `segment[0] <= targetColumn`, or `-1`. */
|
||||
const greatestSegmentIndexAtOrBefore = (
|
||||
row: readonly SourceMapSegment[],
|
||||
targetColumn: number,
|
||||
): number => {
|
||||
let low = 0;
|
||||
let high = row.length - 1;
|
||||
let best = -1;
|
||||
while (low <= high) {
|
||||
const mid = low + ((high - low) >> 1);
|
||||
if (row[mid]![0] <= targetColumn) {
|
||||
best = mid;
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
};
|
||||
|
||||
/** First index in column-sorted `row` with `segment[0] === column`, or `-1`. */
|
||||
const firstSegmentIndexAt = (
|
||||
row: readonly SourceMapSegment[],
|
||||
column: number,
|
||||
): number => {
|
||||
let low = 0;
|
||||
let high = row.length - 1;
|
||||
let first = -1;
|
||||
while (low <= high) {
|
||||
const mid = low + ((high - low) >> 1);
|
||||
const value = row[mid]![0];
|
||||
if (value === column) {
|
||||
first = mid;
|
||||
high = mid - 1;
|
||||
} else if (value < column) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
};
|
||||
const originalMatch = (
|
||||
segment: Readonly<SourceMapSegment>,
|
||||
map: TraceMap,
|
||||
|
||||
Reference in new issue
Block a user