forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-dynamic-import-warts.mjs
More file actions
198 lines (176 loc) · 5.46 KB
/
Copy pathcheck-dynamic-import-warts.mjs
File metadata and controls
198 lines (176 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import path from "node:path";
import ts from "typescript";
import {
collectTypeScriptFilesFromRoots,
resolveRepoRoot,
runAsScript,
toLine,
} from "./lib/ts-guard-utils.mjs";
const repoRoot = resolveRepoRoot(import.meta.url);
const defaultRoots = [path.join(repoRoot, "src"), path.join(repoRoot, "extensions")];
function readStringLiteral(node) {
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
return node.text;
}
return null;
}
function isTypeOnlyImportDeclaration(node) {
const clause = node.importClause;
if (!clause) {
return false;
}
if (clause.isTypeOnly) {
return true;
}
if (clause.name) {
return false;
}
const bindings = clause.namedBindings;
return (
Boolean(bindings) &&
ts.isNamedImports(bindings) &&
bindings.elements.length > 0 &&
bindings.elements.every((element) => element.isTypeOnly)
);
}
function readDeclarationName(node) {
if (
(ts.isFunctionDeclaration(node) ||
ts.isMethodDeclaration(node) ||
ts.isVariableDeclaration(node)) &&
node.name &&
ts.isIdentifier(node.name)
) {
return node.name.text;
}
if (ts.isPropertyAssignment(node)) {
if (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) {
return node.name.text;
}
}
return null;
}
function isIgnoredTestHelperContent(content) {
return /\bfrom\s+["']vitest["']/.test(content) || /\bfrom\s+["']@vitest\//.test(content);
}
function isIgnoredTestHelperPath(filePath) {
const normalized = filePath.split(path.sep).join("/");
const base = path.basename(filePath);
return (
normalized.includes("/test/") ||
/(?:^|[./-])test(?:[./-]|$)/.test(base) ||
base.includes("test-support") ||
base.includes("test-harness") ||
base.includes("test-helper") ||
base.includes("test-mocks")
);
}
export function findDynamicImportAdvisories(content, fileName = "source.ts") {
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true);
const staticRuntimeImports = new Map();
const dynamicImports = new Map();
const directExecuteImports = [];
const declarationStack = [];
const addLine = (map, specifier, line) => {
const lines = map.get(specifier) ?? [];
lines.push(line);
map.set(specifier, lines);
};
const visit = (node) => {
const declarationName = readDeclarationName(node);
if (declarationName) {
declarationStack.push(declarationName);
}
if (
ts.isImportDeclaration(node) &&
ts.isStringLiteral(node.moduleSpecifier) &&
!isTypeOnlyImportDeclaration(node)
) {
addLine(staticRuntimeImports, node.moduleSpecifier.text, toLine(sourceFile, node));
}
if (
ts.isCallExpression(node) &&
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
node.arguments.length > 0
) {
const specifier = readStringLiteral(node.arguments[0]);
if (specifier) {
const line = toLine(sourceFile, node);
addLine(dynamicImports, specifier, line);
if (declarationStack.includes("execute")) {
directExecuteImports.push({
line,
reason: `direct dynamic import of "${specifier}" inside execute path; move it behind a cached loader`,
});
}
}
}
ts.forEachChild(node, visit);
if (declarationName) {
declarationStack.pop();
}
};
visit(sourceFile);
const advisories = [...directExecuteImports];
for (const [specifier, dynamicLines] of dynamicImports) {
const staticLines = staticRuntimeImports.get(specifier);
if (staticLines?.length) {
advisories.push({
line: dynamicLines[0],
reason: `runtime static + dynamic import of "${specifier}" (static line ${staticLines[0]})`,
});
}
if (dynamicLines.length > 1) {
advisories.push({
line: dynamicLines[0],
reason: `repeated direct dynamic import of "${specifier}" (${dynamicLines.length} callsites: ${dynamicLines.join(", ")})`,
});
}
}
return advisories;
}
export async function collectDynamicImportAdvisories(options = {}) {
const roots = options.roots ?? defaultRoots;
const files = await collectTypeScriptFilesFromRoots(roots, {
extraTestSuffixes: [".suite.ts"],
});
const advisories = [];
for (const filePath of files) {
if (isIgnoredTestHelperPath(filePath)) {
continue;
}
const content = await fs.readFile(filePath, "utf8");
if (isIgnoredTestHelperContent(content)) {
continue;
}
for (const advisory of findDynamicImportAdvisories(content, filePath)) {
advisories.push({
path: path.relative(repoRoot, filePath),
...advisory,
});
}
}
return advisories;
}
export async function main(argv = process.argv.slice(2)) {
const fail = argv.includes("--fail");
const json = argv.includes("--json");
const advisories = await collectDynamicImportAdvisories();
if (json) {
console.log(JSON.stringify({ advisories }, null, 2));
} else if (advisories.length === 0) {
console.log("No dynamic import advisories found.");
} else {
console.log(`Dynamic import advisories (${advisories.length}):`);
for (const advisory of advisories) {
console.log(`- ${advisory.path}:${advisory.line} ${advisory.reason}`);
}
console.log("Advisory only. Use --fail when ratcheting this into a hard check.");
}
if (fail && advisories.length > 0) {
process.exit(1);
}
}
runAsScript(import.meta.url, main);