Files
reverse-engineering-anything/src/domain/javascript/javascriptFeatureSeed.ts
T
908d9c0726 fix(javascript): keep export bindings out of module views (#9486)
* fix(javascript): keep export bindings out of module views

Exported symbol bindings reuse the javascript-module node kind, so the modules collection counted one row per export alongside the owning module. On a CommonJS or ESM file with N exports, inspect_analysis_view reported N+1 module units, module pages listed indistinguishable rows sharing the module path, and item selection by selector.path failed with "Multiple modules have path".

Treat a node whose observations carry semantic_role export-binding as an export of its owning module, not a module unit, and exclude it from module entries. Export bindings remain distinct graph entities for export-shape comparison and version matching.

Validation: a domain regression in analysisView.test.ts and a CLI acceptance regression over a real CommonJS analysis both fail on main and pass with this change. Also ran the analysis view, MCP boundary, CLI boundary and JavaScript acceptance suites (125 tests), npm run check:fast, and the MCP catalog schema test after regenerating .cache/mcp-tool-catalog.json.

* test(javascript): run the export-binding view case on the shared CLI

The case starts a compiled CLI process for each of its three commands,
paying startup and tool registration three times per run. The fixture
already provides a file-scoped process for calls with no stdin or explicit
timeout, so use it.

* style(javascript): format the constructed-evidence type in the module-view case

The acceptance case's inline graph type did not match what oxfmt emits for the
80-column limit, so `format:check` refused the tree. Reflow only; the assertions
are unchanged.

* style(cli): wrap the native data type path description

The `inspect-native-data-type` argument description line is 82 columns, over the repository's 80-column `.oxfmtrc.json` limit, so `npm run format:check` fails on main and on every branch merged from it. It came in with #9465 and the following commits to this file did not touch it. Reformat the one call the formatter objects to; no behaviour change.

---------

Co-authored-by: 2SinceJuly <202121119+2SinceJuly@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-09 19:42:47 +08:00

283 lines
8.5 KiB
TypeScript

import { isJavaScriptModuleUnit } from "./javascriptModuleUnits.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import {
featureSeedMatchMode,
type ApplicationFeatureSeed,
} from "./javascriptFeatureTraceSchemas.js";
import type { JsonValue } from "../jsonValue.js";
/** One explicit field that matched a feature seed. */
export interface ApplicationFeatureSeedMatch {
readonly node_id: string;
readonly kind: ApplicationNode["kind"];
readonly basis: "node-id" | "label" | "identity" | "property";
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;
}
/** 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}`,
),
);
const seedMatch = (
node: 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],
)
);
})
)
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
? []
: [
{
node_id: node.node_id,
kind: node.kind,
basis: match.basis,
field: match.field,
},
];
};
const kindMatches = (
node: ApplicationNode,
kind: ApplicationFeatureSeed["kind"],
): boolean => {
if (kind === "string" || kind === "node-id") return true;
if (kind === "route")
return (
node.kind === "endpoint" &&
node.observations.some(
({ properties }) => properties.endpoint_kind === "route",
)
);
if (kind === "api")
return (
node.kind === "context-bridge-api" ||
(node.kind === "javascript-expression" &&
node.observations.some((o) => o.properties.step_kind === "exposure"))
);
if (kind === "channel") return node.kind === "ipc-channel";
if (kind === "module") return isJavaScriptModuleUnit(node);
return node.kind === "native-export";
};
const candidateFields = (
node: ApplicationNode,
seedKind: ApplicationFeatureSeed["kind"],
): CandidateField[] => {
if (seedKind === "node-id")
return [{ basis: "node-id", field: "node_id", value: node.node_id }];
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);
}),
);
};
const memberFieldSuffixes = new Set([
".members",
".methods",
".exports",
".requested_members",
]);
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;
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,
},
]),
];
if (identity.strategy === "canonical-path")
return [
{ basis: "identity", field: "identity.path", value: identity.path },
];
if (identity.strategy === "artifact-local-key")
return [{ basis: "identity", field: "identity.key", value: identity.key }];
if (identity.strategy === "runtime-instance")
return [
{
basis: "identity",
field: "identity.runtime_key",
value: identity.runtime_key,
},
];
return [];
};
const propertyFields = (
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 }];
while (pending.length > 0) {
const next = pending.pop();
if (next === undefined) continue;
const { current, path, selectionPath } = next;
if (typeof current === "string") {
output.push({
basis: "property",
field: path,
selectionPath,
value: current,
});
continue;
}
if (Array.isArray(current)) {
for (let index = current.length - 1; index >= 0; index -= 1) {
const item = current[index];
if (item !== undefined)
pending.push({
current: item,
path: `${path}[${String(index)}]`,
selectionPath,
});
}
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}`,
});
}
}
return output;
};
/** Normalize literal matching identically across application and semantic labels. */
export const normalizeFeatureSeedText = (
value: string,
caseSensitive: boolean,
): string => {
const normalizedValue = value.normalize(caseSensitive ? "NFC" : "NFKC");
return caseSensitive
? normalizedValue
: normalizedValue.toLocaleLowerCase("en-US");
};