Skip to content

Commit e4532b5

Browse files
committed
fix(javascript): preserve TypeScript loader and dependency semantics
Share loader selection across static findings and module relationships: CTS static imports and re-exports use CommonJS lookup while dynamic imports retain ESM lookup. Retain runtime import-equals dependencies, bindings, and exported names; do not resolve require file-URL strings as local artifacts. Restore import-map descriptions in CLI help. Validated resolver and semantic tests, application reconstruction boundaries, and CLI help. Installed TypeScript NodeNext emission and Node require behavior were checked independently. Refs #2056, #2057, #2058, #2053.
1 parent 966f7cc commit e4532b5

8 files changed

Lines changed: 242 additions & 13 deletions

‎src/application/javascript/JavaScriptArtifactGraphFindings.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ import {
2222
astObservationEvidence,
2323
staticInferenceEvidence,
2424
} from "./JavaScriptArtifactGraphEvidence.js";
25-
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
25+
import {
26+
moduleKindForJavaScriptReference,
27+
resolveArtifactPathByContext,
28+
} from "./JavaScriptArtifactPathResolution.js";
2629

2730
type StaticReference = JavaScriptStaticAnalysis["references"][number];
2831
type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number];
@@ -400,12 +403,11 @@ const resolveReference = (
400403
specifier,
401404
sourcePath,
402405
context.filesByPath,
403-
reference.kind === "require"
404-
? "require"
405-
: reference.kind === "static-import" ||
406-
reference.kind === "dynamic-import"
407-
? "import"
408-
: undefined,
406+
reference.kind === "require" ||
407+
reference.kind === "static-import" ||
408+
reference.kind === "dynamic-import"
409+
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
410+
: undefined,
409411
);
410412
if (path === null) return null;
411413
const file = context.filesByPath.get(path);

‎src/application/javascript/JavaScriptArtifactPathResolution.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,27 @@ describe("contextual JavaScript artifact path resolution", () => {
576576
});
577577
});
578578

579+
describe("CommonJS file URL resolution", () => {
580+
it("keeps file URL resolution specific to the import loader", () => {
581+
const files = fileMap([file("entry.cjs", "root"), file("dep.cjs", "root")]);
582+
const input = {
583+
declaredPath: "file:///dep.cjs",
584+
sourcePath: "entry.cjs",
585+
context: "module-specifier" as const,
586+
files,
587+
};
588+
589+
expect(resolve({ ...input, moduleKind: "require" })).toMatchObject({
590+
resolution_status: "external",
591+
resolved_path: null,
592+
});
593+
expect(resolve({ ...input, moduleKind: "import" })).toMatchObject({
594+
resolution_status: "resolved",
595+
resolved_path: "dep.cjs",
596+
});
597+
});
598+
});
599+
579600
describe("contextual JavaScript package path resolution", () => {
580601
it("follows package entrypoints beyond the former recursion ceiling", () => {
581602
const files = fileMap([

‎src/application/javascript/JavaScriptArtifactPathResolution.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,17 @@ export interface ResolveArtifactPathInput {
6464
readonly moduleKind?: "import" | "require";
6565
}
6666

67+
/** Loader selected by a source-level JavaScript module reference. */
68+
export const moduleKindForJavaScriptReference = (
69+
sourcePath: string,
70+
referenceKind: "static-import" | "dynamic-import" | "require",
71+
): "import" | "require" =>
72+
referenceKind === "require" ||
73+
(referenceKind === "static-import" &&
74+
posix.extname(sourcePath).toLowerCase() === ".cts")
75+
? "require"
76+
: "import";
77+
6778
const EXTENSIONS = [
6879
".js",
6980
".cjs",
@@ -189,7 +200,12 @@ const contextualCandidate = (
189200
if (context === "html-reference") return htmlCandidate(input);
190201
if (context === "module-specifier") {
191202
const fileUrl = fileUrlPath(declared);
192-
if (fileUrl !== undefined) return fileUrl;
203+
if (fileUrl !== undefined)
204+
return input.moduleKind === "require"
205+
? unresolvedCandidate("external", [
206+
"Node CommonJS require specifiers do not resolve file URLs as local artifacts.",
207+
])
208+
: fileUrl;
193209
if (hasScheme(declared))
194210
return unresolvedCandidate("external", [
195211
"URL and Node builtin schemes are outside static artifact module resolution.",

‎src/application/javascript/JavaScriptModuleRelationships.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
staticInferenceEvidence,
3131
} from "./JavaScriptArtifactGraphEvidence.js";
3232
import {
33+
moduleKindForJavaScriptReference,
3334
resolveArtifactPathByContext,
3435
type ArtifactPathResolution,
3536
} from "./JavaScriptArtifactPathResolution.js";
@@ -275,10 +276,12 @@ const resolveModuleTarget = (
275276
sourcePath: input.file.path,
276277
context: "module-specifier",
277278
files: input.context.filesByPath,
278-
moduleKind:
279+
moduleKind: moduleKindForJavaScriptReference(
280+
input.file.path,
279281
input.link.kind === "require" || input.link.kind === "commonjs-export"
280282
? "require"
281-
: "import",
283+
: "static-import",
284+
),
282285
});
283286
if (resolution.resolution_status !== "resolved")
284287
return {
@@ -423,8 +426,8 @@ const moduleFormat = (
423426
ir: JavaScriptModuleSemanticIr,
424427
): "commonjs" | "esm" | "mixed" | "unknown" => {
425428
const extension = posix.extname(path).toLowerCase();
426-
if (extension === ".mjs") return "esm";
427-
if (extension === ".cjs") return "commonjs";
429+
if (extension === ".mjs" || extension === ".mts") return "esm";
430+
if (extension === ".cjs" || extension === ".cts") return "commonjs";
428431
const esm = ir.moduleLinks.some(({ kind }) =>
429432
["import", "export", "re-export"].includes(kind),
430433
);

‎src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,51 @@ import {
66
topLevelBinding,
77
} from "./javascriptSemanticAnalysis.fixture.js";
88

9+
describe("TypeScript import-equals links", () => {
10+
it("retains runtime external import-equals as a require dependency", () => {
11+
const links = analyzeJavaScriptSemantics(`
12+
import dependency = require("./dependency.cjs");
13+
import type types = require("./types");
14+
import alias = Namespace.Dependency;
15+
`).moduleLinks;
16+
17+
expect(links).toEqual([
18+
expect.objectContaining({
19+
kind: "require",
20+
specifier: "./dependency.cjs",
21+
importedName: null,
22+
localName: "dependency",
23+
exportedName: null,
24+
}),
25+
]);
26+
});
27+
28+
it("keeps the exported binding for exported import-equals", () => {
29+
const source = 'export import dependency = require("./dependency");';
30+
const links = analyzeJavaScriptSemantics(source).moduleLinks;
31+
32+
expect(links).toEqual(
33+
expect.arrayContaining([
34+
expect.objectContaining({
35+
kind: "require",
36+
specifier: "./dependency",
37+
localName: "dependency",
38+
exportedName: null,
39+
}),
40+
expect.objectContaining({
41+
kind: "export",
42+
specifier: null,
43+
localName: "dependency",
44+
exportedName: "dependency",
45+
}),
46+
]),
47+
);
48+
expect(
49+
links.find(({ kind }) => kind === "require")?.location.start,
50+
).toEqual({ line: 1, column: 7 });
51+
});
52+
});
53+
954
describe("CommonJS dependency links", () => {
1055
it.each([
1156
'require("dependency");',

‎src/domain/javascript/javascriptSemanticAnalysis.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import {
1111
collectSemanticModuleLink,
1212
collectSemanticCallable,
13+
semanticImportEqualsSpecifier,
1314
collectSemanticReferences,
1415
collectSemanticReferencesSteps,
1516
immutableSemanticBindings,
@@ -752,6 +753,8 @@ const bindInnerDeclaration = (
752753
state: JavaScriptSemanticAnalysisState,
753754
): void => {
754755
if (t.isImportDeclaration(node)) bindImports(node, scope, state);
756+
else if (t.isTSImportEqualsDeclaration(node))
757+
bindImportEquals(node, scope, state);
755758
else if (t.isVariableDeclarator(node))
756759
bindPattern({
757760
pattern: node.id,
@@ -785,6 +788,25 @@ const bindInnerDeclaration = (
785788
});
786789
};
787790

791+
const bindImportEquals = (
792+
node: t.TSImportEqualsDeclaration,
793+
scope: JavaScriptSemanticScopeState,
794+
state: JavaScriptSemanticAnalysisState,
795+
): void => {
796+
const specifier = semanticImportEqualsSpecifier(node);
797+
if (specifier === null) return;
798+
addBinding({
799+
state,
800+
scope,
801+
name: node.id.name,
802+
kind: "import",
803+
mutable: false,
804+
definitionNode: node.id,
805+
initializer: null,
806+
directOrigin: { specifier, importedPath: [] },
807+
});
808+
};
809+
788810
const bindAssignment = (
789811
node: t.Node,
790812
scope: JavaScriptSemanticScopeState,

‎src/domain/javascript/javascriptSemanticProjection.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ export const collectSemanticModuleLink = (
6969
node: t.Node,
7070
state: JavaScriptSemanticAnalysisState,
7171
): void => {
72-
if (t.isImportDeclaration(node)) collectImports(node, state);
72+
if (t.isTSImportEqualsDeclaration(node)) collectImportEquals(node, state);
73+
else if (t.isImportDeclaration(node)) collectImports(node, state);
7374
else if (t.isExportAllDeclaration(node))
7475
addModuleLink(
7576
state,
@@ -103,6 +104,36 @@ export const collectSemanticModuleLink = (
103104
else if (t.isCallExpression(node)) collectUnboundRequireLink(node, state);
104105
};
105106

107+
const collectImportEquals = (
108+
node: t.TSImportEqualsDeclaration,
109+
state: JavaScriptSemanticAnalysisState,
110+
): void => {
111+
const specifier = semanticImportEqualsSpecifier(node);
112+
if (specifier === null) return;
113+
addModuleLink(
114+
state,
115+
{
116+
kind: "require",
117+
specifier,
118+
importedName: null,
119+
localName: node.id.name,
120+
exportedName: null,
121+
location: range(node),
122+
},
123+
node,
124+
);
125+
};
126+
127+
/** Runtime external-module target for a value import-equals declaration. */
128+
export const semanticImportEqualsSpecifier = (
129+
node: t.TSImportEqualsDeclaration,
130+
): string | null =>
131+
node.importKind !== "type" &&
132+
t.isTSExternalModuleReference(node.moduleReference) &&
133+
t.isStringLiteral(node.moduleReference.expression)
134+
? node.moduleReference.expression.value
135+
: null;
136+
106137
/** Collect lexical references after definitions exist, optionally for one name. */
107138
export const collectSemanticReferences = (
108139
program: t.Program,
@@ -707,6 +738,11 @@ const declarationNames = (declaration: t.Declaration): string[] => {
707738
t.isIdentifier(declaration.id)
708739
)
709740
return [declaration.id.name];
741+
if (
742+
t.isTSImportEqualsDeclaration(declaration) &&
743+
semanticImportEqualsSpecifier(declaration) !== null
744+
)
745+
return [declaration.id.name];
710746
return [];
711747
};
712748

‎tests/boundary/filesystem/javascript-applications/javascriptModuleRelationships.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,90 @@ import {
1414
writeFixtureFiles,
1515
} from "../../../support/javascriptApplicationFixture.js";
1616

17+
describe("TypeScript source module loader semantics", () => {
18+
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
19+
const root = await createTestTempDirectory("rea-cts-module-loader-");
20+
await writeFixtureFiles(root, {
21+
"package.json": '{"type":"module"}',
22+
"main.cts": `
23+
import local = require("./local");
24+
import selected from "conditional";
25+
export { retained } from "conditional";
26+
void import("conditional");
27+
void local;
28+
void selected;
29+
`,
30+
"consumer.mts": `
31+
import local = require("./local");
32+
export { local };
33+
`,
34+
"local.js": "module.exports = 42;",
35+
"node_modules/conditional/package.json": JSON.stringify({
36+
exports: {
37+
".": {
38+
import: "./esm.mjs",
39+
require: "./cjs.cjs",
40+
},
41+
},
42+
}),
43+
"node_modules/conditional/esm.mjs": "export const retained = 'esm';",
44+
"node_modules/conditional/cjs.cjs": "exports.retained = 'cjs';",
45+
});
46+
47+
const { graph } = await reconstructJavaScriptFixture(root);
48+
const localRequireEdge = (sourcePath: string) => {
49+
const source = findSourceModule(graph, sourcePath);
50+
return graph.edges.find(
51+
({ source_node_id, relation, properties }) =>
52+
source_node_id === source?.node_id &&
53+
relation === "imports" &&
54+
properties.module_link_kind === "require" &&
55+
properties.specifier === "./local",
56+
);
57+
};
58+
59+
expect(
60+
findSourceModule(graph, "main.cts")?.observations[0]?.properties,
61+
).toMatchObject({ module_format: "commonjs" });
62+
expect(localRequireEdge("main.cts")).toMatchObject({
63+
properties: { resolved_path: "local.js", local_name: "local" },
64+
});
65+
expect(
66+
findRelationshipEdge(graph, {
67+
kind: "import",
68+
specifier: "conditional",
69+
resolvedPath: "node_modules/conditional/cjs.cjs",
70+
localName: "selected",
71+
}),
72+
).toBeDefined();
73+
expect(
74+
findRelationshipEdge(graph, {
75+
kind: "re-export",
76+
specifier: "conditional",
77+
resolvedPath: "node_modules/conditional/cjs.cjs",
78+
}),
79+
).toBeDefined();
80+
expect(
81+
graph.edges.find(
82+
({ relation, properties }) =>
83+
relation === "imports" &&
84+
properties.kind === "dynamic-import" &&
85+
properties.specifier === "conditional",
86+
),
87+
).toMatchObject({
88+
properties: {
89+
resolved_path: "node_modules/conditional/esm.mjs",
90+
},
91+
});
92+
expect(
93+
findSourceModule(graph, "consumer.mts")?.observations[0]?.properties,
94+
).toMatchObject({ module_format: "esm" });
95+
expect(localRequireEdge("consumer.mts")).toMatchObject({
96+
properties: { resolved_path: "local.js", local_name: "local" },
97+
});
98+
});
99+
});
100+
17101
describe("CommonJS and ESM module relationships", () => {
18102
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
19103
const root = await moduleFixture();

0 commit comments

Comments
 (0)