@itarrshia/bati 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -2
- package/assets/bati-mark.svg +26 -0
- package/dist/api.ts +0 -0
- package/dist/bati-db.png +0 -0
- package/dist/bati-openapi.json +8 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +174 -0
- package/dist/core/api-generate.d.ts +9 -0
- package/dist/core/api-generate.js +74 -0
- package/dist/core/api.d.ts +44 -0
- package/dist/core/api.js +292 -0
- package/dist/core/config.d.ts +40 -0
- package/dist/core/config.js +53 -0
- package/dist/core/dashboard.d.ts +37 -0
- package/dist/core/dashboard.js +95 -0
- package/dist/core/db.d.ts +31 -0
- package/dist/core/db.js +392 -0
- package/dist/core/deps.d.ts +35 -0
- package/dist/core/deps.js +242 -0
- package/dist/core/diagram.d.ts +4 -0
- package/dist/core/diagram.js +151 -0
- package/dist/core/doctor.d.ts +23 -0
- package/dist/core/doctor.js +148 -0
- package/dist/core/files.d.ts +5 -0
- package/dist/core/files.js +69 -0
- package/dist/core/format.d.ts +13 -0
- package/dist/core/format.js +54 -0
- package/dist/core/graph-view.d.ts +2 -0
- package/dist/core/graph-view.js +65 -0
- package/dist/core/mcp-install.d.ts +19 -0
- package/dist/core/mcp-install.js +105 -0
- package/dist/core/mcp.d.ts +12 -0
- package/dist/core/mcp.js +244 -0
- package/dist/core/openapi.d.ts +16 -0
- package/dist/core/openapi.js +270 -0
- package/dist/core/pack.d.ts +8 -0
- package/dist/core/pack.js +101 -0
- package/dist/core/php.d.ts +6 -0
- package/dist/core/php.js +50 -0
- package/dist/core/preview.d.ts +9 -0
- package/dist/core/preview.js +89 -0
- package/dist/core/probe.d.ts +21 -0
- package/dist/core/probe.js +119 -0
- package/dist/core/routes.d.ts +37 -0
- package/dist/core/routes.js +343 -0
- package/dist/core/scan.d.ts +13 -0
- package/dist/core/scan.js +395 -0
- package/dist/core/tasks.d.ts +34 -0
- package/dist/core/tasks.js +88 -0
- package/dist/core/types.d.ts +46 -0
- package/dist/core/types.js +1 -0
- package/dist/openapi.json +8 -0
- package/dist/theme.d.ts +12 -0
- package/dist/theme.js +32 -0
- package/dist/ui/App.d.ts +5 -0
- package/dist/ui/App.js +247 -0
- package/dist/ui/Banner.d.ts +5 -0
- package/dist/ui/Banner.js +9 -0
- package/dist/ui/Dashboard.d.ts +26 -0
- package/dist/ui/Dashboard.js +52 -0
- package/dist/ui/MapView.d.ts +5 -0
- package/dist/ui/MapView.js +47 -0
- package/dist/ui/Wizard.d.ts +17 -0
- package/dist/ui/Wizard.js +112 -0
- package/dist/ui/presentation.d.ts +24 -0
- package/dist/ui/presentation.js +15 -0
- package/package.json +80 -4
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { configuredOutput, loadConfig } from './config.js';
|
|
4
|
+
import { listFiles, writeOutput } from './files.js';
|
|
5
|
+
export const codePattern = '**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,php}';
|
|
6
|
+
function cycleGroups(paths, edges) {
|
|
7
|
+
const adjacency = new Map(paths.map((file) => [file, []]));
|
|
8
|
+
const reverse = new Map(paths.map((file) => [file, []]));
|
|
9
|
+
for (const { from, to } of edges) {
|
|
10
|
+
adjacency.get(from).push(to);
|
|
11
|
+
reverse.get(to).push(from);
|
|
12
|
+
}
|
|
13
|
+
const visited = new Set();
|
|
14
|
+
const order = [];
|
|
15
|
+
for (const start of paths) {
|
|
16
|
+
if (visited.has(start))
|
|
17
|
+
continue;
|
|
18
|
+
const stack = [[start, 0]];
|
|
19
|
+
visited.add(start);
|
|
20
|
+
while (stack.length) {
|
|
21
|
+
const current = stack.at(-1);
|
|
22
|
+
const next = adjacency.get(current[0])[current[1]++];
|
|
23
|
+
if (next === undefined)
|
|
24
|
+
order.push(stack.pop()[0]);
|
|
25
|
+
else if (!visited.has(next)) {
|
|
26
|
+
visited.add(next);
|
|
27
|
+
stack.push([next, 0]);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
visited.clear();
|
|
32
|
+
const result = [];
|
|
33
|
+
for (const start of order.reverse()) {
|
|
34
|
+
if (visited.has(start))
|
|
35
|
+
continue;
|
|
36
|
+
const stack = [start];
|
|
37
|
+
const group = [start];
|
|
38
|
+
visited.add(start);
|
|
39
|
+
while (stack.length) {
|
|
40
|
+
for (const next of reverse.get(stack.pop())) {
|
|
41
|
+
if (visited.has(next))
|
|
42
|
+
continue;
|
|
43
|
+
visited.add(next);
|
|
44
|
+
stack.push(next);
|
|
45
|
+
group.push(next);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (group.length > 1 || adjacency.get(start).includes(start))
|
|
49
|
+
result.push(group.sort());
|
|
50
|
+
}
|
|
51
|
+
return result.sort((a, b) => a[0].localeCompare(b[0]));
|
|
52
|
+
}
|
|
53
|
+
function entrypoint(file) {
|
|
54
|
+
return /(?:^|\/)(?:index|main|cli|server|middleware|page|layout|route|loading|error|not-found|instrumentation)\.[^.]+$|(?:^|\/)(?:pages|routes|migrations|tests?)\/|(?:\.config|\.test|\.spec)\.[^.]+$/i.test(file);
|
|
55
|
+
}
|
|
56
|
+
export async function analyzeDeps(dir) {
|
|
57
|
+
const root = path.resolve(dir);
|
|
58
|
+
const paths = (await listFiles(root, codePattern)).filter((file) => !/\.d\.[cm]?ts$/.test(file));
|
|
59
|
+
const known = new Set(paths);
|
|
60
|
+
const [{ default: ts }, php] = await Promise.all([import('typescript'), import('./php.js')]);
|
|
61
|
+
const resolvePhp = paths.some((file) => file.endsWith('.php')) ? await php.phpResolver(root, known) : () => undefined;
|
|
62
|
+
const compilerSettings = new Map();
|
|
63
|
+
const moduleCaches = new Map();
|
|
64
|
+
const edges = new Map();
|
|
65
|
+
const files = [];
|
|
66
|
+
const add = (from, to, names, line) => {
|
|
67
|
+
if (!to || !known.has(to))
|
|
68
|
+
return;
|
|
69
|
+
const key = JSON.stringify([from, to]);
|
|
70
|
+
const edge = edges.get(key) ?? { from, to, imports: [], lines: [] };
|
|
71
|
+
edge.lines = [...new Set([...edge.lines, line])];
|
|
72
|
+
edge.imports = [...new Set([...edge.imports, ...names])];
|
|
73
|
+
edges.set(key, edge);
|
|
74
|
+
};
|
|
75
|
+
const host = { ...ts.sys, directoryExists: ts.sys.directoryExists, realpath: ts.sys.realpath };
|
|
76
|
+
const configFor = (abs) => {
|
|
77
|
+
const start = path.dirname(abs);
|
|
78
|
+
const cached = compilerSettings.get(start);
|
|
79
|
+
if (cached)
|
|
80
|
+
return cached;
|
|
81
|
+
const config = ts.findConfigFile(start, (file) => !path.relative(root, file).startsWith('..') && ts.sys.fileExists(file)) ??
|
|
82
|
+
ts.findConfigFile(start, (file) => !path.relative(root, file).startsWith('..') && ts.sys.fileExists(file), 'jsconfig.json');
|
|
83
|
+
let compilerOptions = { allowJs: true, moduleResolution: ts.ModuleResolutionKind.Bundler };
|
|
84
|
+
if (config) {
|
|
85
|
+
const loaded = ts.readConfigFile(config, ts.sys.readFile);
|
|
86
|
+
if (loaded.error)
|
|
87
|
+
throw new Error(ts.flattenDiagnosticMessageText(loaded.error.messageText, '\n'));
|
|
88
|
+
compilerOptions = { ...compilerOptions, ...ts.parseJsonConfigFileContent(loaded.config, ts.sys, path.dirname(config), undefined, config).options };
|
|
89
|
+
}
|
|
90
|
+
compilerSettings.set(start, compilerOptions);
|
|
91
|
+
moduleCaches.set(compilerOptions, ts.createModuleResolutionCache(root, (value) => value, compilerOptions));
|
|
92
|
+
return compilerOptions;
|
|
93
|
+
};
|
|
94
|
+
for (const file of paths) {
|
|
95
|
+
const abs = path.join(root, file);
|
|
96
|
+
const code = await readFile(abs, 'utf8');
|
|
97
|
+
const exports = new Set();
|
|
98
|
+
let complexity = 1;
|
|
99
|
+
if (file.endsWith('.php')) {
|
|
100
|
+
const phpTarget = (node) => {
|
|
101
|
+
if (node?.kind === 'magic' && node.value === '__DIR__')
|
|
102
|
+
return path.dirname(abs);
|
|
103
|
+
if (node?.kind === 'magic' && node.value === '__FILE__')
|
|
104
|
+
return abs;
|
|
105
|
+
if (node?.kind === 'bin' && node.type === '.') {
|
|
106
|
+
const left = phpTarget(node.left);
|
|
107
|
+
const right = phpTarget(node.right);
|
|
108
|
+
if (left !== undefined && right !== undefined)
|
|
109
|
+
return left + right;
|
|
110
|
+
}
|
|
111
|
+
return php.phpString(node);
|
|
112
|
+
};
|
|
113
|
+
for (const node of php.walkPhp(php.parsePhpSource(code, file))) {
|
|
114
|
+
const line = node.loc?.start.line ?? 1;
|
|
115
|
+
if (['if', 'while', 'for', 'foreach', 'case', 'catch', 'retif', 'matcharm'].includes(node.kind))
|
|
116
|
+
complexity++;
|
|
117
|
+
if (node.kind === 'usegroup')
|
|
118
|
+
for (const item of node.items) {
|
|
119
|
+
const name = [node.name, item.name].filter(Boolean).join('\\');
|
|
120
|
+
add(file, resolvePhp(name), ['*'], line);
|
|
121
|
+
}
|
|
122
|
+
if (node.kind === 'include') {
|
|
123
|
+
const target = phpTarget(node.target);
|
|
124
|
+
if (target)
|
|
125
|
+
add(file, path.relative(root, path.resolve(path.dirname(abs), target)).split(path.sep).join('/'), [], line);
|
|
126
|
+
}
|
|
127
|
+
if (node.kind === 'name' && node.name.includes('\\'))
|
|
128
|
+
add(file, resolvePhp(node.name), ['*'], line);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
const compilerOptions = configFor(abs);
|
|
133
|
+
const source = ts.createSourceFile(abs, code, ts.ScriptTarget.Latest, true);
|
|
134
|
+
const ref = (specifier, names, node) => {
|
|
135
|
+
const resolved = ts.resolveModuleName(specifier, abs, compilerOptions, host, moduleCaches.get(compilerOptions)).resolvedModule?.resolvedFileName;
|
|
136
|
+
const to = resolved ? path.relative(root, resolved).split(path.sep).join('/') : undefined;
|
|
137
|
+
add(file, to, names, source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1);
|
|
138
|
+
};
|
|
139
|
+
const bindings = (name) => {
|
|
140
|
+
if (ts.isIdentifier(name))
|
|
141
|
+
exports.add(name.text);
|
|
142
|
+
else
|
|
143
|
+
for (const element of name.elements)
|
|
144
|
+
if (ts.isBindingElement(element))
|
|
145
|
+
bindings(element.name);
|
|
146
|
+
};
|
|
147
|
+
const visit = (node) => {
|
|
148
|
+
if (ts.isIfStatement(node) || ts.isIterationStatement(node, false) || ts.isCatchClause(node) || ts.isCaseClause(node) || ts.isConditionalExpression(node))
|
|
149
|
+
complexity++;
|
|
150
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
151
|
+
const clause = node.importClause;
|
|
152
|
+
const names = clause?.name ? ['default'] : [];
|
|
153
|
+
const named = clause?.namedBindings;
|
|
154
|
+
if (named && ts.isNamespaceImport(named))
|
|
155
|
+
names.push('*');
|
|
156
|
+
else
|
|
157
|
+
named?.elements.forEach((element) => names.push((element.propertyName ?? element.name).text));
|
|
158
|
+
ref(node.moduleSpecifier.text, names, node);
|
|
159
|
+
}
|
|
160
|
+
if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression && ts.isStringLiteral(node.moduleReference.expression))
|
|
161
|
+
ref(node.moduleReference.expression.text, ['*'], node);
|
|
162
|
+
if (ts.isExportDeclaration(node)) {
|
|
163
|
+
const clause = node.exportClause;
|
|
164
|
+
if (clause && ts.isNamedExports(clause))
|
|
165
|
+
clause.elements.forEach((element) => exports.add(element.name.text));
|
|
166
|
+
else if (clause)
|
|
167
|
+
exports.add(clause.name.text);
|
|
168
|
+
if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
169
|
+
ref(node.moduleSpecifier.text, clause && ts.isNamedExports(clause) ? clause.elements.map((element) => (element.propertyName ?? element.name).text) : ['*'], node);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (ts.isExportAssignment(node))
|
|
173
|
+
exports.add('default');
|
|
174
|
+
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
|
|
175
|
+
if (modifiers?.some((item) => item.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
176
|
+
if (modifiers.some((item) => item.kind === ts.SyntaxKind.DefaultKeyword))
|
|
177
|
+
exports.add('default');
|
|
178
|
+
else if (ts.isVariableStatement(node))
|
|
179
|
+
node.declarationList.declarations.forEach((item) => bindings(item.name));
|
|
180
|
+
else if ((ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node)) && node.name)
|
|
181
|
+
exports.add(node.name.text);
|
|
182
|
+
}
|
|
183
|
+
if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {
|
|
184
|
+
const target = node.arguments[0];
|
|
185
|
+
if (target && ts.isStringLiteralLike(target))
|
|
186
|
+
ref(target.text, ['*'], node);
|
|
187
|
+
}
|
|
188
|
+
ts.forEachChild(node, visit);
|
|
189
|
+
};
|
|
190
|
+
visit(source);
|
|
191
|
+
}
|
|
192
|
+
files.push({ path: file, lines: code.split(/\r?\n/).length, complexity, exports: [...exports].sort(), importedBy: 0, imports: 0 });
|
|
193
|
+
}
|
|
194
|
+
const byPath = new Map(files.map((file) => [file.path, file]));
|
|
195
|
+
const used = new Map();
|
|
196
|
+
for (const edge of edges.values()) {
|
|
197
|
+
byPath.get(edge.from).imports++;
|
|
198
|
+
byPath.get(edge.to).importedBy++;
|
|
199
|
+
const names = used.get(edge.to) ?? new Set();
|
|
200
|
+
edge.imports.forEach((name) => names.add(name));
|
|
201
|
+
used.set(edge.to, names);
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
root,
|
|
205
|
+
files,
|
|
206
|
+
edges: [...edges.values()],
|
|
207
|
+
cycles: cycleGroups(paths, [...edges.values()]),
|
|
208
|
+
orphans: files.filter((file) => !file.importedBy && !entrypoint(file.path)).map((file) => file.path),
|
|
209
|
+
unusedExports: files.flatMap((file) => entrypoint(file.path) || used.get(file.path)?.has('*') ? [] :
|
|
210
|
+
file.exports.filter((name) => !used.get(file.path)?.has(name)).map((name) => ({ file: file.path, name }))),
|
|
211
|
+
godModules: files.filter((file) => file.imports >= 15 || (file.lines >= 500 && file.complexity >= 35)).map((file) => file.path)
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
export async function deps(options) {
|
|
215
|
+
const graph = await analyzeDeps(options.dir);
|
|
216
|
+
const format = options.format;
|
|
217
|
+
let output;
|
|
218
|
+
if (format || options.out) {
|
|
219
|
+
const extension = format ?? path.extname(options.out).slice(1);
|
|
220
|
+
if (!['svg', 'png', 'html', 'json'].includes(extension))
|
|
221
|
+
throw new Error('Dependency graph format must be svg, png, html, or json');
|
|
222
|
+
const file = configuredOutput(graph.root, await loadConfig(graph.root), 'deps', `bati-deps.${extension}`, options.out);
|
|
223
|
+
if (extension === 'json')
|
|
224
|
+
output = await writeOutput(file, JSON.stringify(graph, null, 2));
|
|
225
|
+
else {
|
|
226
|
+
const { dependencyGraphic } = await import('./graph-view.js');
|
|
227
|
+
output = await writeOutput(file, await dependencyGraphic(graph, extension));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
title: 'File dependencies',
|
|
232
|
+
output,
|
|
233
|
+
exitCode: options.check && graph.cycles.length > 0 ? 1 : 0,
|
|
234
|
+
lines: [
|
|
235
|
+
`${graph.files.length} files · ${graph.edges.length} imports · ${graph.cycles.length} circular groups`,
|
|
236
|
+
...graph.cycles.map((group) => `Cycle: ${group.join(', ')}`),
|
|
237
|
+
`${graph.orphans.length} orphan files · ${graph.unusedExports.length} unused exports · ${graph.godModules.length} god modules`,
|
|
238
|
+
...(output ? [output] : [])
|
|
239
|
+
],
|
|
240
|
+
data: graph
|
|
241
|
+
};
|
|
242
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ProjectModel } from './types.js';
|
|
2
|
+
export declare const renderSvg: (model: ProjectModel, maxNodes?: number, label?: string, nodeLabel?: string) => string;
|
|
3
|
+
export declare const toPng: (svg: string, scale?: number) => Buffer;
|
|
4
|
+
export declare const toMermaid: (model: ProjectModel) => string;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import dagre from '@dagrejs/dagre';
|
|
2
|
+
import { Resvg } from '@resvg/resvg-js';
|
|
3
|
+
const KIND_COLOR = {
|
|
4
|
+
class: ['#7C5CFF', '#4F3BD1'],
|
|
5
|
+
interface: ['#00E5C7', '#00A58F'],
|
|
6
|
+
trait: ['#FFB547', '#D98616'],
|
|
7
|
+
enum: ['#FF5CAA', '#C93A80']
|
|
8
|
+
};
|
|
9
|
+
const CHAR = 7.3;
|
|
10
|
+
const HEAD = 44;
|
|
11
|
+
const ROW = 19;
|
|
12
|
+
const MAX_ROWS = 7;
|
|
13
|
+
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
14
|
+
const sym = (v) => (v === 'private' ? '-' : v === 'protected' ? '#' : '+');
|
|
15
|
+
const propLine = (p) => `${sym(p.visibility)} ${p.name}${p.type ? ': ' + p.type : ''}`;
|
|
16
|
+
const methLine = (m) => `${sym(m.visibility)} ${m.name}(${m.params ?? ''})${m.returns ? ': ' + m.returns : ''}`;
|
|
17
|
+
const clip = (s, n = 46) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
|
|
18
|
+
const prepare = (c) => {
|
|
19
|
+
const take = (arr) => arr.length > MAX_ROWS ? [...arr.slice(0, MAX_ROWS), `… +${arr.length - MAX_ROWS} more`] : arr;
|
|
20
|
+
const props = take(c.props.map((p) => clip(propLine(p))));
|
|
21
|
+
const methods = take(c.methods.map((m) => clip(methLine(m))));
|
|
22
|
+
const longest = Math.max(c.name.length + 6, ...props.map((s) => s.length), ...methods.map((s) => s.length));
|
|
23
|
+
const w = Math.max(190, Math.ceil(longest * CHAR + 36));
|
|
24
|
+
const sections = (props.length ? props.length * ROW + 14 : 8) + (methods.length ? methods.length * ROW + 14 : 8);
|
|
25
|
+
return { c, props, methods, w, h: HEAD + sections };
|
|
26
|
+
};
|
|
27
|
+
const smooth = (pts) => {
|
|
28
|
+
if (pts.length < 2)
|
|
29
|
+
return '';
|
|
30
|
+
const mid = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
|
|
31
|
+
let d = `M${pts[0].x},${pts[0].y}`;
|
|
32
|
+
for (let i = 1; i < pts.length - 1; i++) {
|
|
33
|
+
const m = mid(pts[i], pts[i + 1]);
|
|
34
|
+
d += ` L${mid(pts[i - 1], pts[i]).x},${mid(pts[i - 1], pts[i]).y} Q${pts[i].x},${pts[i].y} ${m.x},${m.y}`;
|
|
35
|
+
}
|
|
36
|
+
const last = pts[pts.length - 1];
|
|
37
|
+
return d + ` L${last.x},${last.y}`;
|
|
38
|
+
};
|
|
39
|
+
export const renderSvg = (model, maxNodes = 150, label, nodeLabel = 'types') => {
|
|
40
|
+
const classes = model.classes.slice(0, maxNodes);
|
|
41
|
+
const ids = new Set(classes.map((c) => c.id));
|
|
42
|
+
const boxes = new Map(classes.map((c) => [c.id, prepare(c)]));
|
|
43
|
+
const g = new dagre.graphlib.Graph({ multigraph: true });
|
|
44
|
+
g.setGraph({ rankdir: 'BT', nodesep: 56, ranksep: 90, marginx: 60, marginy: 90 });
|
|
45
|
+
g.setDefaultEdgeLabel(() => ({}));
|
|
46
|
+
boxes.forEach((b, id) => g.setNode(id, { width: b.w, height: b.h }));
|
|
47
|
+
const edges = model.edges.filter((e) => ids.has(e.from) && ids.has(e.to));
|
|
48
|
+
edges.forEach((e, i) => g.setEdge(e.from, e.to, {}, String(i)));
|
|
49
|
+
dagre.layout(g);
|
|
50
|
+
const graph = g.graph();
|
|
51
|
+
const W = Math.max(640, Math.ceil(graph.width ?? 640));
|
|
52
|
+
const H = Math.max(360, Math.ceil(graph.height ?? 360)) + 40;
|
|
53
|
+
const defs = `
|
|
54
|
+
<defs>
|
|
55
|
+
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#090912"/><stop offset="0.6" stop-color="#110d26"/><stop offset="1" stop-color="#0a1620"/></linearGradient>
|
|
56
|
+
<radialGradient id="glow1" cx="0.15" cy="0.1" r="0.6"><stop offset="0" stop-color="#7C5CFF" stop-opacity="0.22"/><stop offset="1" stop-color="#7C5CFF" stop-opacity="0"/></radialGradient>
|
|
57
|
+
<radialGradient id="glow2" cx="0.9" cy="0.95" r="0.6"><stop offset="0" stop-color="#00E5C7" stop-opacity="0.16"/><stop offset="1" stop-color="#00E5C7" stop-opacity="0"/></radialGradient>
|
|
58
|
+
<pattern id="dots" width="26" height="26" patternUnits="userSpaceOnUse"><circle cx="1.5" cy="1.5" r="1.1" fill="#ffffff" fill-opacity="0.07"/></pattern>
|
|
59
|
+
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%"><feDropShadow dx="0" dy="8" stdDeviation="9" flood-color="#000" flood-opacity="0.55"/></filter>
|
|
60
|
+
${Object.entries(KIND_COLOR)
|
|
61
|
+
.map(([k, [a, b]]) => `<linearGradient id="h-${k}" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${b}"/></linearGradient>`)
|
|
62
|
+
.join('')}
|
|
63
|
+
<marker id="m-extends" viewBox="0 0 14 14" refX="13" refY="7" markerWidth="14" markerHeight="14" orient="auto"><path d="M1 1.5 L13 7 L1 12.5 Z" fill="#0b0b18" stroke="#B9AEFF" stroke-width="1.5" stroke-linejoin="round"/></marker>
|
|
64
|
+
<marker id="m-implements" viewBox="0 0 14 14" refX="13" refY="7" markerWidth="14" markerHeight="14" orient="auto"><path d="M1 1.5 L13 7 L1 12.5 Z" fill="#0b0b18" stroke="#5CF2DC" stroke-width="1.5" stroke-linejoin="round"/></marker>
|
|
65
|
+
<marker id="m-uses" viewBox="0 0 12 12" refX="11" refY="6" markerWidth="11" markerHeight="11" orient="auto"><path d="M1 1 L11 6 L1 11" fill="none" stroke="#8A93A6" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></marker>
|
|
66
|
+
</defs>`;
|
|
67
|
+
const edgeSvg = edges
|
|
68
|
+
.map((e, i) => {
|
|
69
|
+
const pts = g.edge({ v: e.from, w: e.to, name: String(i) }).points;
|
|
70
|
+
const color = e.kind === 'extends' ? '#B9AEFF' : e.kind === 'implements' ? '#5CF2DC' : '#8A93A6';
|
|
71
|
+
const dash = e.kind === 'extends' ? '' : e.kind === 'implements' ? ' stroke-dasharray="7 5"' : ' stroke-dasharray="2 5"';
|
|
72
|
+
return `<path d="${smooth(pts)}" fill="none" stroke="${color}" stroke-width="1.8" stroke-linecap="round"${dash} marker-end="url(#m-${e.kind})" opacity="0.9"/>`;
|
|
73
|
+
})
|
|
74
|
+
.join('\n');
|
|
75
|
+
const nodeSvg = [...boxes.entries()]
|
|
76
|
+
.map(([id, b]) => {
|
|
77
|
+
const n = g.node(id);
|
|
78
|
+
const x = n.x - b.w / 2;
|
|
79
|
+
const y = n.y - b.h / 2;
|
|
80
|
+
const [accent] = KIND_COLOR[b.c.kind] ?? KIND_COLOR.class;
|
|
81
|
+
let cy = HEAD;
|
|
82
|
+
const propRows = b.props
|
|
83
|
+
.map((t, i) => `<text x="${x + 16}" y="${y + cy + 22 + i * ROW - 6}" class="m">${esc(t)}</text>`)
|
|
84
|
+
.join('');
|
|
85
|
+
cy += b.props.length ? b.props.length * ROW + 14 : 8;
|
|
86
|
+
const sepY = y + cy - 2;
|
|
87
|
+
const methRows = b.methods
|
|
88
|
+
.map((t, i) => `<text x="${x + 16}" y="${y + cy + 22 + i * ROW - 6}" class="m">${esc(t)}</text>`)
|
|
89
|
+
.join('');
|
|
90
|
+
return `<g filter="url(#shadow)">
|
|
91
|
+
<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="14" fill="#13131f" stroke="${accent}" stroke-opacity="0.55" stroke-width="1.4"/>
|
|
92
|
+
<path d="M${x},${y + 14} a14,14 0 0 1 14,-14 h${b.w - 28} a14,14 0 0 1 14,14 v${HEAD - 14} h-${b.w} z" fill="url(#h-${b.c.kind})"/>
|
|
93
|
+
<text x="${x + 16}" y="${y + 19}" class="k">${esc(label ?? b.c.kind.toUpperCase())}</text>
|
|
94
|
+
<text x="${x + 16}" y="${y + 37}" class="t">${esc(b.c.name)}</text>
|
|
95
|
+
<line x1="${x + 10}" y1="${sepY}" x2="${x + b.w - 10}" y2="${sepY}" stroke="#ffffff" stroke-opacity="0.09"/>
|
|
96
|
+
${propRows}${methRows}
|
|
97
|
+
</g>`;
|
|
98
|
+
})
|
|
99
|
+
.join('\n');
|
|
100
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
|
|
101
|
+
<style>
|
|
102
|
+
.t{font:700 15px 'JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,monospace;fill:#fff}
|
|
103
|
+
.k{font:600 9px 'JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,monospace;fill:#fff;fill-opacity:.7;letter-spacing:1.6px}
|
|
104
|
+
.m{font:400 12px 'JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,monospace;fill:#C9CEDB}
|
|
105
|
+
.h{font:700 22px 'JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,monospace;fill:#fff}
|
|
106
|
+
.s{font:400 11px 'JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,monospace;fill:#8A93A6}
|
|
107
|
+
</style>
|
|
108
|
+
${defs}
|
|
109
|
+
<rect width="100%" height="100%" fill="url(#bg)"/>
|
|
110
|
+
<rect width="100%" height="100%" fill="url(#glow1)"/>
|
|
111
|
+
<rect width="100%" height="100%" fill="url(#glow2)"/>
|
|
112
|
+
<rect width="100%" height="100%" fill="url(#dots)"/>
|
|
113
|
+
<text x="40" y="52" class="h">bati</text>
|
|
114
|
+
<text x="104" y="52" class="s">${classes.length} ${esc(nodeLabel)} · ${edges.length} relations</text>
|
|
115
|
+
${edgeSvg}
|
|
116
|
+
${nodeSvg}
|
|
117
|
+
</svg>`;
|
|
118
|
+
};
|
|
119
|
+
export const toPng = (svg, scale = 2) => {
|
|
120
|
+
const resvg = new Resvg(svg, {
|
|
121
|
+
fitTo: { mode: 'zoom', value: scale },
|
|
122
|
+
font: { loadSystemFonts: true, defaultFontFamily: 'DejaVu Sans Mono' }
|
|
123
|
+
});
|
|
124
|
+
return Buffer.from(resvg.render().asPng());
|
|
125
|
+
};
|
|
126
|
+
const mid = (s) => s.replace(/[^A-Za-z0-9_]/g, '_');
|
|
127
|
+
export const toMermaid = (model) => {
|
|
128
|
+
const idOf = new Map(model.classes.map((c) => [c.id, mid(c.name)]));
|
|
129
|
+
const lines = ['classDiagram'];
|
|
130
|
+
for (const c of model.classes) {
|
|
131
|
+
lines.push(` class ${mid(c.name)} {`);
|
|
132
|
+
if (c.kind !== 'class')
|
|
133
|
+
lines.push(` <<${c.kind}>>`);
|
|
134
|
+
c.props.slice(0, 10).forEach((p) => lines.push(` ${sym(p.visibility)}${p.name}${p.type ? ' ' + mid(p.type) : ''}`));
|
|
135
|
+
c.methods.slice(0, 10).forEach((m) => lines.push(` ${sym(m.visibility)}${m.name}()`));
|
|
136
|
+
lines.push(' }');
|
|
137
|
+
}
|
|
138
|
+
for (const e of model.edges) {
|
|
139
|
+
const a = idOf.get(e.from);
|
|
140
|
+
const b = idOf.get(e.to);
|
|
141
|
+
if (!a || !b)
|
|
142
|
+
continue;
|
|
143
|
+
if (e.kind === 'extends')
|
|
144
|
+
lines.push(` ${b} <|-- ${a}`);
|
|
145
|
+
else if (e.kind === 'implements')
|
|
146
|
+
lines.push(` ${b} <|.. ${a}`);
|
|
147
|
+
else
|
|
148
|
+
lines.push(` ${a} --> ${b}`);
|
|
149
|
+
}
|
|
150
|
+
return lines.join('\n');
|
|
151
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { TaskResult } from './types.js';
|
|
2
|
+
type Severity = 'error' | 'warning' | 'notice';
|
|
3
|
+
export interface Finding {
|
|
4
|
+
severity: Severity;
|
|
5
|
+
rule: string;
|
|
6
|
+
message: string;
|
|
7
|
+
file?: string;
|
|
8
|
+
line?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function scanSecrets(source: string, file: string): Finding[];
|
|
11
|
+
export declare function parseEnv(source: string): Map<string, {
|
|
12
|
+
value: string;
|
|
13
|
+
line: number;
|
|
14
|
+
}>;
|
|
15
|
+
export declare function typedEnv(keys: ReturnType<typeof parseEnv>): string;
|
|
16
|
+
export declare function doctor(options: {
|
|
17
|
+
dir: string;
|
|
18
|
+
out?: string;
|
|
19
|
+
envSchema?: boolean;
|
|
20
|
+
offline?: boolean;
|
|
21
|
+
check?: boolean;
|
|
22
|
+
}): Promise<TaskResult>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { configuredOutput, loadConfig } from './config.js';
|
|
6
|
+
import { gitChurn, listFiles, writeOutput } from './files.js';
|
|
7
|
+
import { hotspots } from './dashboard.js';
|
|
8
|
+
const execute = promisify(execFile);
|
|
9
|
+
const signatures = [
|
|
10
|
+
['Private key', /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/],
|
|
11
|
+
['AWS access key', /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/],
|
|
12
|
+
['GitHub token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{40,255})\b/],
|
|
13
|
+
['Slack token', /\bxox[baprs]-[A-Za-z0-9-]{15,}\b/],
|
|
14
|
+
['Stripe live key', /\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/],
|
|
15
|
+
['Google API key', /\bAIza[A-Za-z0-9_-]{35}\b/],
|
|
16
|
+
['OpenAI API key', /\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}\b/],
|
|
17
|
+
['Connection string with credentials', /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\/[^\s:/]+:[^\s@]+@[^\s/'"]+/i]
|
|
18
|
+
];
|
|
19
|
+
export function scanSecrets(source, file) {
|
|
20
|
+
return source.split(/\r?\n/).flatMap((line, index) => {
|
|
21
|
+
const matches = signatures.filter(([, pattern]) => pattern.test(line)).map(([rule]) => rule);
|
|
22
|
+
const assignment = line.match(/\b([\w-]*(?:secret|token|password|api[_-]?key|private[_-]?key)[\w-]*)\s*['"]?\s*[:=]\s*(?:"([^"]+)"|'([^']+)'|([^\s,;]+))/i);
|
|
23
|
+
const value = assignment && (assignment[2] ?? assignment[3] ?? assignment[4]);
|
|
24
|
+
if (value && value.length >= 16 && /[a-z]/i.test(value) && /\d/.test(value) && new Set(value).size >= 9 &&
|
|
25
|
+
!/^(?:test|sample|example|dummy|placeholder|your[_-]|process\.env|\$|\{|<)/i.test(value) && !matches.length)
|
|
26
|
+
matches.push('Possible hardcoded credential');
|
|
27
|
+
return matches.map((rule) => ({ severity: rule.startsWith('Possible') ? 'warning' : 'error', rule, message: `${rule} detected`, file, line: index + 1 }));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
export function parseEnv(source) {
|
|
31
|
+
const values = new Map();
|
|
32
|
+
const entries = /^(?:\s*export\s+|[ \t]*)([A-Za-z_][\w.]*)[ \t]*=[ \t]*(?:"((?:\\.|[^"\\])*)"|'([^']*)'|([^\r\n#]*))/gm;
|
|
33
|
+
const lines = source.split(/\r?\n/);
|
|
34
|
+
let index = 0;
|
|
35
|
+
let offset = 0;
|
|
36
|
+
for (const match of source.matchAll(entries)) {
|
|
37
|
+
while (index < lines.length - 1 && offset + lines[index].length + 1 <= match.index) {
|
|
38
|
+
offset += lines[index].length + (source[offset + lines[index].length] === '\r' ? 2 : 1);
|
|
39
|
+
index++;
|
|
40
|
+
}
|
|
41
|
+
values.set(match[1], { value: match[2] ?? match[3] ?? match[4]?.trim() ?? '', line: index + 1 });
|
|
42
|
+
}
|
|
43
|
+
return values;
|
|
44
|
+
}
|
|
45
|
+
export function typedEnv(keys) {
|
|
46
|
+
const validators = [...keys].sort(([a], [b]) => a.localeCompare(b)).map(([key, { value }]) => {
|
|
47
|
+
const type = /^(?:true|false)$/i.test(value)
|
|
48
|
+
? "z.enum(['true', 'false']).transform((value) => value === 'true')"
|
|
49
|
+
: /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value)
|
|
50
|
+
? "z.string().regex(/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/).transform(Number)"
|
|
51
|
+
: /^https?:\/\//i.test(value) ? 'z.string().url()' : 'z.string().min(1)';
|
|
52
|
+
return ` [${JSON.stringify(key)}]: ${type},`;
|
|
53
|
+
});
|
|
54
|
+
return ["import { z } from 'zod';", '', 'export const envSchema = z.object({', ...validators, '});',
|
|
55
|
+
'', 'export type Env = z.infer<typeof envSchema>;', ''].join('\n');
|
|
56
|
+
}
|
|
57
|
+
function dependencyResults(manager, operation, json) {
|
|
58
|
+
if (manager === 'npm' && operation === 'audit')
|
|
59
|
+
return Object.entries(json.vulnerabilities ?? {}).map(([name, value]) => ({ name, severity: String(value.severity ?? 'unknown') }));
|
|
60
|
+
if (manager === 'composer' && operation === 'audit')
|
|
61
|
+
return Object.entries(json.advisories ?? {}).flatMap(([name, values]) => (Array.isArray(values) ? values : Object.values(values)).map((value) => ({ name, severity: String(value.severity ?? 'unknown') })));
|
|
62
|
+
if (manager === 'composer')
|
|
63
|
+
return (json.installed ?? []).map((value) => ({ name: String(value.name), current: value.version, latest: value.latest }));
|
|
64
|
+
return Object.entries(json).map(([name, value]) => ({ name, current: value.current, latest: value.latest ?? value.wanted }));
|
|
65
|
+
}
|
|
66
|
+
async function dependencyReport(root, manager, operation, enabled) {
|
|
67
|
+
const empty = { manager, operation, status: 'skipped', findings: [] };
|
|
68
|
+
if (!enabled)
|
|
69
|
+
return empty;
|
|
70
|
+
let output;
|
|
71
|
+
const args = manager === 'npm'
|
|
72
|
+
? [operation, '--json', '--ignore-scripts', '--no-fund', '--fetch-retries=0', '--fetch-timeout=10000']
|
|
73
|
+
: [operation, '--format=json', '--no-interaction', '--no-plugins', '--no-scripts'];
|
|
74
|
+
try {
|
|
75
|
+
({ stdout: output } = await execute(manager, args, { cwd: root, timeout: 20_000, maxBuffer: 8 * 1024 * 1024 }));
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
output = error.stdout ?? '';
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const json = JSON.parse(output);
|
|
82
|
+
if (!json || json.error || (operation === 'audit' && manager === 'npm' && !json.vulnerabilities))
|
|
83
|
+
return { ...empty, status: 'unavailable' };
|
|
84
|
+
return { ...empty, status: 'ok', findings: dependencyResults(manager, operation, json) };
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return { ...empty, status: 'unavailable' };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const optionalText = async (file) => {
|
|
91
|
+
try {
|
|
92
|
+
return await readFile(file, 'utf8');
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error.code === 'ENOENT')
|
|
96
|
+
return undefined;
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
export async function doctor(options) {
|
|
101
|
+
const root = path.resolve(options.dir);
|
|
102
|
+
const { analyzeDeps } = await import('./deps.js');
|
|
103
|
+
const [inventory, graph, churn, config, envSource, sampleSource, manifests] = await Promise.all([
|
|
104
|
+
listFiles(root), analyzeDeps(root), gitChurn(root), loadConfig(root), optionalText(path.join(root, '.env')), optionalText(path.join(root, '.env.example')),
|
|
105
|
+
listFiles(root, ['package.json', 'composer.json'], true)
|
|
106
|
+
]);
|
|
107
|
+
const knownText = /(?:\.(?:[cm]?[jt]sx?|php|py|rb|sh|ya?ml|toml|json|xml|md|ini|conf|properties|pem|key|sql)$|(?:^|\/)\.(?:env(?:\.[\w.-]+)?|npmrc|netrc)$)/i;
|
|
108
|
+
const secrets = [];
|
|
109
|
+
for (const file of inventory) {
|
|
110
|
+
if (!knownText.test(file) || /(?:lock\.json|(?:^|\/)bati-pack\.)/.test(file))
|
|
111
|
+
continue;
|
|
112
|
+
const target = path.join(root, file);
|
|
113
|
+
if ((await stat(target)).size > 1024 * 1024)
|
|
114
|
+
continue;
|
|
115
|
+
const text = await readFile(target, 'utf8');
|
|
116
|
+
if (!text.includes('\0'))
|
|
117
|
+
secrets.push(...scanSecrets(text, file));
|
|
118
|
+
}
|
|
119
|
+
const actual = parseEnv(envSource ?? '');
|
|
120
|
+
const sample = parseEnv(sampleSource ?? '');
|
|
121
|
+
const missing = envSource === undefined ? [] : [...sample.keys()].filter((key) => !actual.has(key));
|
|
122
|
+
const undocumented = [...actual.keys()].filter((key) => !sample.has(key));
|
|
123
|
+
const env = { missing, undocumented, hasEnv: envSource !== undefined, hasExample: sampleSource !== undefined };
|
|
124
|
+
const reports = await Promise.all(manifests.flatMap((file) => {
|
|
125
|
+
const manager = file === 'package.json' ? 'npm' : 'composer';
|
|
126
|
+
return [dependencyReport(root, manager, 'audit', !options.offline), dependencyReport(root, manager, 'outdated', !options.offline)];
|
|
127
|
+
}));
|
|
128
|
+
const hotspotRows = hotspots(graph, churn);
|
|
129
|
+
const findings = [
|
|
130
|
+
...secrets,
|
|
131
|
+
...missing.map((name) => ({ severity: 'warning', rule: 'env-missing', message: `Missing environment variable ${name}`, file: '.env.example', line: sample.get(name)?.line })),
|
|
132
|
+
...undocumented.map((name) => ({ severity: 'notice', rule: 'env-undocumented', message: `Undocumented environment variable ${name}`, file: '.env', line: actual.get(name)?.line })),
|
|
133
|
+
...graph.cycles.map((group) => ({ severity: 'warning', rule: 'dependency-cycle', message: `Circular imports among ${group.join(', ')}`, file: group[0] })),
|
|
134
|
+
...reports.flatMap((report) => report.findings.map((item) => ({
|
|
135
|
+
severity: report.operation === 'audit' && /^(critical|high)$/i.test(item.severity ?? '') ? 'error' : report.operation === 'audit' ? 'warning' : 'notice',
|
|
136
|
+
rule: `${report.manager}-${report.operation}`, message: `${item.name} · ${item.severity ?? [item.current, item.latest].filter(Boolean).join(' → ')}`,
|
|
137
|
+
file: report.manager === 'npm' ? 'package.json' : 'composer.json'
|
|
138
|
+
})))
|
|
139
|
+
];
|
|
140
|
+
const score = Math.max(0, 100 - findings.reduce((sum, item) => sum + (item.severity === 'error' ? 12 : item.severity === 'warning' ? 4 : 1), 0));
|
|
141
|
+
const incomplete = reports.some((report) => report.status === 'unavailable');
|
|
142
|
+
const output = options.envSchema || options.out ? await writeOutput(configuredOutput(root, config, 'env', 'bati-env.ts', options.out), typedEnv(sample)) : undefined;
|
|
143
|
+
return { title: 'Project health', output, exitCode: options.check && findings.some((item) => item.severity === 'error') ? 1 : options.check && incomplete ? 2 : 0,
|
|
144
|
+
lines: [`Health score ${score}/100${incomplete ? ' · dependency data incomplete' : ''}`, ...findings.map((finding) => `${finding.severity.toUpperCase()} ${finding.file ?? ''}${finding.line ? ':' + finding.line : ''} ${finding.message}`),
|
|
145
|
+
...reports.map((report) => `${report.manager} ${report.operation} · ${report.status} · ${report.findings.length} findings`),
|
|
146
|
+
...hotspotRows.slice(0, 10).map((item) => `Hotspot ${item.score} · ${item.file} · ${item.churn} changes × ${item.complexity} complexity`),
|
|
147
|
+
...(output ? [output] : [])], data: { score, findings, env, dependencies: reports, hotspots: hotspotRows } };
|
|
148
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
export declare const runGit: typeof execFile.__promisify__;
|
|
3
|
+
export declare function listFiles(dir: string, patterns?: string | string[], includeIgnored?: boolean): Promise<string[]>;
|
|
4
|
+
export declare function gitChurn(root: string): Promise<Map<string, number>>;
|
|
5
|
+
export declare function writeOutput(file: string, data: string | Buffer, mode?: number): Promise<string>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readFile, stat, mkdir, rename, writeFile, rm } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import fg from 'fast-glob';
|
|
8
|
+
import { loadConfig } from './config.js';
|
|
9
|
+
const makeIgnore = createRequire(import.meta.url)('ignore');
|
|
10
|
+
export const runGit = promisify(execFile);
|
|
11
|
+
export async function listFiles(dir, patterns = '**/*', includeIgnored = false) {
|
|
12
|
+
const root = path.resolve(dir);
|
|
13
|
+
if (!(await stat(root)).isDirectory())
|
|
14
|
+
throw new Error(`Not a directory: ${root}`);
|
|
15
|
+
const config = await loadConfig(root);
|
|
16
|
+
const excludes = ['**/node_modules/**', '**/vendor/**', '**/.git/**', '**/.next/**', '**/dist/**', '**/coverage/**', '**/build/**', '**/storage/**', ...config.ignore];
|
|
17
|
+
const options = { cwd: root, dot: true, followSymbolicLinks: false, ignore: excludes };
|
|
18
|
+
const entries = (await fg(patterns, options)).sort();
|
|
19
|
+
if (includeIgnored)
|
|
20
|
+
return entries;
|
|
21
|
+
const rules = new Map();
|
|
22
|
+
for (const file of await fg('**/.gitignore', options)) {
|
|
23
|
+
const parent = path.posix.dirname(file);
|
|
24
|
+
rules.set(parent === '.' ? '' : parent, makeIgnore().add(await readFile(path.join(root, file), 'utf8')));
|
|
25
|
+
}
|
|
26
|
+
return entries.filter((file) => {
|
|
27
|
+
const parts = file.split('/');
|
|
28
|
+
for (let depth = 1; depth <= parts.length; depth++) {
|
|
29
|
+
let ignored = false;
|
|
30
|
+
for (let parent = 0; parent < depth; parent++) {
|
|
31
|
+
const match = rules.get(parts.slice(0, parent).join('/'))?.test(parts.slice(parent, depth).join('/') + (depth === parts.length ? '' : '/'));
|
|
32
|
+
if (match?.ignored || match?.unignored)
|
|
33
|
+
ignored = match.ignored;
|
|
34
|
+
}
|
|
35
|
+
if (ignored)
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
return true;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export async function gitChurn(root) {
|
|
42
|
+
const counts = new Map();
|
|
43
|
+
try {
|
|
44
|
+
const { stdout } = await runGit('git', ['log', '-n', '500', '--format=', '--name-only', '-z', '--relative', '--', '.'], { cwd: root, maxBuffer: 32 * 1024 * 1024 });
|
|
45
|
+
for (const item of stdout.split('\0')) {
|
|
46
|
+
const file = item.replace(/^\n+/, '');
|
|
47
|
+
if (file)
|
|
48
|
+
counts.set(file, (counts.get(file) ?? 0) + 1);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (!error.message.includes('not a git repository') && !error.message.includes('does not have any commits') && error.code !== 'ENOENT')
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
return counts;
|
|
56
|
+
}
|
|
57
|
+
export async function writeOutput(file, data, mode) {
|
|
58
|
+
const target = path.resolve(file);
|
|
59
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
60
|
+
const temp = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`);
|
|
61
|
+
try {
|
|
62
|
+
await writeFile(temp, data, { flag: 'wx', mode });
|
|
63
|
+
await rename(temp, target);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await rm(temp, { force: true });
|
|
67
|
+
}
|
|
68
|
+
return target;
|
|
69
|
+
}
|