@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,13 @@
|
|
|
1
|
+
export interface FormatReport {
|
|
2
|
+
changed: string[];
|
|
3
|
+
unchanged: number;
|
|
4
|
+
failed: Array<{
|
|
5
|
+
file: string;
|
|
6
|
+
error: string;
|
|
7
|
+
}>;
|
|
8
|
+
}
|
|
9
|
+
export declare const formatSource: (code: string, filepath: string) => Promise<string>;
|
|
10
|
+
export declare const formatPaths: (targets: string[], opts?: {
|
|
11
|
+
check?: boolean;
|
|
12
|
+
onFile?: (file: string, changed: boolean) => void;
|
|
13
|
+
}) => Promise<FormatReport>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import fg from 'fast-glob';
|
|
2
|
+
import * as prettier from 'prettier';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { loadConfig } from './config.js';
|
|
7
|
+
import { IGNORE } from './scan.js';
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
const phpPlugin = require.resolve('@prettier/plugin-php');
|
|
10
|
+
const GLOB = '**/*.{ts,tsx,js,jsx,mjs,cjs,json,css,scss,less,md,yml,yaml,html,vue,php}';
|
|
11
|
+
export const formatSource = async (code, filepath) => {
|
|
12
|
+
const config = (await prettier.resolveConfig(filepath)) ?? {};
|
|
13
|
+
const isPhp = filepath.endsWith('.php');
|
|
14
|
+
return prettier.format(code, {
|
|
15
|
+
singleQuote: true,
|
|
16
|
+
printWidth: 100,
|
|
17
|
+
...config,
|
|
18
|
+
filepath,
|
|
19
|
+
plugins: isPhp ? [phpPlugin] : config.plugins
|
|
20
|
+
});
|
|
21
|
+
};
|
|
22
|
+
export const formatPaths = async (targets, opts = {}) => {
|
|
23
|
+
const report = { changed: [], unchanged: 0, failed: [] };
|
|
24
|
+
const files = [];
|
|
25
|
+
for (const t of targets.length ? targets : ['.']) {
|
|
26
|
+
const abs = path.resolve(t);
|
|
27
|
+
if (statSync(abs).isFile())
|
|
28
|
+
files.push(abs);
|
|
29
|
+
else {
|
|
30
|
+
const config = await loadConfig(abs);
|
|
31
|
+
const found = await fg(GLOB, { cwd: abs, followSymbolicLinks: false, ignore: [...IGNORE, ...config.ignore, '**/package-lock.json', '**/composer.lock'], absolute: true });
|
|
32
|
+
files.push(...found);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
for (const file of files) {
|
|
36
|
+
try {
|
|
37
|
+
const src = readFileSync(file, 'utf8');
|
|
38
|
+
const out = await formatSource(src, file);
|
|
39
|
+
const changed = out !== src;
|
|
40
|
+
if (changed) {
|
|
41
|
+
report.changed.push(file);
|
|
42
|
+
if (!opts.check)
|
|
43
|
+
writeFileSync(file, out);
|
|
44
|
+
}
|
|
45
|
+
else
|
|
46
|
+
report.unchanged++;
|
|
47
|
+
opts.onFile?.(file, changed);
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
report.failed.push({ file, error: String(e?.message ?? e).split('\n')[0] });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return report;
|
|
54
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import dagre from '@dagrejs/dagre';
|
|
2
|
+
import { gradient } from '../theme.js';
|
|
3
|
+
const escape = (text) => text.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
|
4
|
+
export async function dependencyGraphic(graph, format) {
|
|
5
|
+
const layout = new dagre.graphlib.Graph();
|
|
6
|
+
layout.setGraph({ rankdir: 'LR', nodesep: 20, ranksep: 100, marginx: 32, marginy: 52 });
|
|
7
|
+
layout.setDefaultEdgeLabel(() => ({}));
|
|
8
|
+
const ids = new Map(graph.files.map((file, index) => [file.path, String(index)]));
|
|
9
|
+
for (const file of graph.files)
|
|
10
|
+
layout.setNode(ids.get(file.path), { width: Math.min(440, Math.max(130, file.path.length * 8 + 30)), height: 38 });
|
|
11
|
+
for (const edge of graph.edges)
|
|
12
|
+
layout.setEdge(ids.get(edge.from), ids.get(edge.to));
|
|
13
|
+
dagre.layout(layout);
|
|
14
|
+
const { width, height } = layout.graph();
|
|
15
|
+
const w = Math.max(480, width || 0);
|
|
16
|
+
const h = Math.max(200, height || 0);
|
|
17
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="File dependency graph">
|
|
18
|
+
<defs><linearGradient id="background"><stop stop-color="#101022"/><stop offset="1" stop-color="#081b21"/></linearGradient><linearGradient id="outline"><stop stop-color="${gradient[0]}"/><stop offset="1" stop-color="${gradient[2]}"/></linearGradient><marker id="arrow" markerWidth="7" markerHeight="7" refX="6" refY="3" orient="auto"><path d="M0 0L6 3L0 6Z" fill="#8098af"/></marker></defs>
|
|
19
|
+
<rect width="100%" height="100%" fill="url(#background)"/>
|
|
20
|
+
<text x="32" y="30" fill="#eef2ff" font-family="monospace" font-size="16">bati · ${graph.files.length} files · ${graph.edges.length} imports</text>
|
|
21
|
+
${graph.edges.map(({ from, to }) => {
|
|
22
|
+
const a = ids.get(from);
|
|
23
|
+
const b = ids.get(to);
|
|
24
|
+
const points = layout.edge(a, b).points.map(({ x, y }) => `${x},${y}`).join(' ');
|
|
25
|
+
return `<polyline data-from="${a}" data-to="${b}" points="${points}" fill="none" stroke="#71819c" stroke-width="1.5" marker-end="url(#arrow)"/>`;
|
|
26
|
+
}).join('')}
|
|
27
|
+
${graph.files.map((file) => {
|
|
28
|
+
const id = ids.get(file.path);
|
|
29
|
+
const { x, y, width, height } = layout.node(id);
|
|
30
|
+
return `<g data-node="${id}" data-label="${escape(file.path)}" tabindex="0" role="button" aria-label="${escape(file.path)}"><title>${escape(file.path)}</title><rect x="${x - width / 2}" y="${y - height / 2}" width="${width}" height="${height}" rx="10" fill="#171c34" stroke="url(#outline)"/><text x="${x}" y="${y + 4}" fill="#f3f5ff" text-anchor="middle" font-family="monospace" font-size="12">${escape(file.path.length > 54 ? '…' + file.path.slice(-53) : file.path)}</text></g>`;
|
|
31
|
+
}).join('')}
|
|
32
|
+
</svg>`;
|
|
33
|
+
if (format === 'svg')
|
|
34
|
+
return svg;
|
|
35
|
+
if (format === 'png')
|
|
36
|
+
return (await import('./diagram.js')).toPng(svg, Math.min(2, 8192 / Math.max(w, h)));
|
|
37
|
+
return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>bati · File dependencies</title>
|
|
38
|
+
<style>body{margin:0;color:#e5e7eb;background:#090913;font:15px system-ui}header{display:flex;align-items:center;gap:12px;padding:12px}input,button{background:#191930;color:inherit;border:1px solid #7c5cff;border-radius:8px;padding:8px}main{overflow:hidden;height:calc(100vh - 60px);touch-action:none}svg{width:100%;height:100%;cursor:grab}g[data-node]{cursor:pointer;transition:opacity .15s}.dim{opacity:.13}</style>
|
|
39
|
+
<header><strong>File dependencies</strong><input aria-label="Search files" placeholder="Search files"><button type="button">Reset view</button></header><main>${svg}</main>
|
|
40
|
+
<script>
|
|
41
|
+
const svg=document.querySelector('svg'), search=document.querySelector('input');
|
|
42
|
+
const nodes=[...svg.querySelectorAll('[data-node]')], edges=[...svg.querySelectorAll('[data-from]')];
|
|
43
|
+
const original=svg.getAttribute('viewBox').split(' ').map(Number);
|
|
44
|
+
let view=[...original], selected, drag, moved=false;
|
|
45
|
+
const update=()=>svg.setAttribute('viewBox',view.join(' '));
|
|
46
|
+
function highlight(){
|
|
47
|
+
const query=search.value.toLowerCase(), near=new Set([selected]);
|
|
48
|
+
for(const edge of edges){const {from,to}=edge.dataset;if(from===selected)near.add(to);if(to===selected)near.add(from);}
|
|
49
|
+
const active=new Set(nodes.filter(n=>(!selected||near.has(n.dataset.node))&&n.dataset.label.toLowerCase().includes(query)).map(n=>n.dataset.node));
|
|
50
|
+
for(const n of nodes)n.classList.toggle('dim',!active.has(n.dataset.node));
|
|
51
|
+
for(const e of edges)e.classList.toggle('dim',!active.has(e.dataset.from)||!active.has(e.dataset.to));
|
|
52
|
+
}
|
|
53
|
+
search.addEventListener('input',()=>{selected=undefined;highlight();});
|
|
54
|
+
function select(event){if(moved)return;const node=event.target.closest('[data-node]');selected=node&&node.dataset.node!==selected?node.dataset.node:undefined;highlight();}
|
|
55
|
+
svg.addEventListener('click',select);
|
|
56
|
+
svg.addEventListener('keydown',event=>{if(['Enter',' '].includes(event.key)){event.preventDefault();moved=false;select(event);}});
|
|
57
|
+
function point(event){return new DOMPoint(event.clientX,event.clientY).matrixTransform(svg.getScreenCTM().inverse());}
|
|
58
|
+
svg.addEventListener('wheel',event=>{event.preventDefault();const p=point(event),scale=Math.exp(Math.max(-500,Math.min(500,event.deltaY))*.001);if(view[2]*scale<20||view[2]*scale>original[2]*40)return;view=[p.x+(view[0]-p.x)*scale,p.y+(view[1]-p.y)*scale,view[2]*scale,view[3]*scale];update();},{passive:false});
|
|
59
|
+
svg.addEventListener('pointerdown',event=>{drag={x:event.clientX,y:event.clientY};moved=false;});
|
|
60
|
+
svg.addEventListener('pointermove',event=>{if(!drag||!event.buttons)return;const dx=event.clientX-drag.x,dy=event.clientY-drag.y;if(!moved&&Math.hypot(dx,dy)<4)return;moved=true;svg.setPointerCapture(event.pointerId);const scale=svg.getScreenCTM().a;view[0]-=dx/scale;view[1]-=dy/scale;drag={x:event.clientX,y:event.clientY};update();});
|
|
61
|
+
svg.addEventListener('pointerup',()=>{drag=undefined;});
|
|
62
|
+
svg.addEventListener('pointercancel',()=>{drag=undefined;});
|
|
63
|
+
document.querySelector('button').addEventListener('click',()=>{view=[...original];selected=undefined;search.value='';update();highlight();});
|
|
64
|
+
</script></html>`;
|
|
65
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { TaskResult } from './types.js';
|
|
2
|
+
export declare const mcpConfig: (dir: string, watch?: boolean) => {
|
|
3
|
+
mcpServers: {
|
|
4
|
+
bati: {
|
|
5
|
+
command: string;
|
|
6
|
+
args: string[];
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
export declare const mcpClients: readonly ["claude-desktop", "claude-code", "cursor"];
|
|
11
|
+
export declare function mergeMcpConfig(contents: string | undefined, entry: ReturnType<typeof mcpConfig>['mcpServers']['bati'], replace?: boolean): string | undefined;
|
|
12
|
+
export declare function installMcp(options: {
|
|
13
|
+
dir: string;
|
|
14
|
+
client?: string;
|
|
15
|
+
out?: string;
|
|
16
|
+
watch?: boolean;
|
|
17
|
+
replace?: boolean;
|
|
18
|
+
dryRun?: boolean;
|
|
19
|
+
}): Promise<TaskResult>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, mkdir, open, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir, platform } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { configuredOutput, loadConfig } from './config.js';
|
|
6
|
+
import { writeOutput } from './files.js';
|
|
7
|
+
export const mcpConfig = (dir, watch = false) => ({
|
|
8
|
+
mcpServers: { bati: { command: 'bati', args: ['mcp', path.resolve(dir), ...(watch ? ['--watch'] : [])] } }
|
|
9
|
+
});
|
|
10
|
+
export const mcpClients = ['claude-desktop', 'claude-code', 'cursor'];
|
|
11
|
+
function configPath(client, root) {
|
|
12
|
+
if (client === 'claude-code')
|
|
13
|
+
return path.join(root, '.mcp.json');
|
|
14
|
+
if (client === 'cursor')
|
|
15
|
+
return path.join(root, '.cursor', 'mcp.json');
|
|
16
|
+
const home = homedir();
|
|
17
|
+
if (platform() === 'darwin')
|
|
18
|
+
return path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
|
|
19
|
+
if (platform() === 'win32')
|
|
20
|
+
return path.join(process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json');
|
|
21
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, '.config'), 'Claude', 'claude_desktop_config.json');
|
|
22
|
+
}
|
|
23
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
export function mergeMcpConfig(contents, entry, replace = false) {
|
|
25
|
+
const value = contents === undefined ? {} : JSON.parse(contents);
|
|
26
|
+
if (!object(value) || ('mcpServers' in value && !object(value.mcpServers)))
|
|
27
|
+
throw new Error('Expected an MCP configuration JSON object');
|
|
28
|
+
const servers = value.mcpServers;
|
|
29
|
+
const current = servers?.bati;
|
|
30
|
+
if (object(current) && current.command === entry.command && JSON.stringify(current.args) === JSON.stringify(entry.args))
|
|
31
|
+
return undefined;
|
|
32
|
+
if (current !== undefined && !replace)
|
|
33
|
+
throw new Error('A different bati server already exists. Use --replace to replace it.');
|
|
34
|
+
return JSON.stringify({ ...value, mcpServers: { ...servers, bati: entry } }, null, 2) + '\n';
|
|
35
|
+
}
|
|
36
|
+
export async function installMcp(options) {
|
|
37
|
+
const root = path.resolve(options.dir);
|
|
38
|
+
if (!(await stat(root)).isDirectory())
|
|
39
|
+
throw new Error(`Not a project directory: ${root}`);
|
|
40
|
+
const clients = options.client ? [options.client] : [...mcpClients];
|
|
41
|
+
if (clients.some((client) => !mcpClients.includes(client)))
|
|
42
|
+
throw new Error(`Client must be ${mcpClients.join(', ')}`);
|
|
43
|
+
if (options.out && clients.length !== 1)
|
|
44
|
+
throw new Error('--out requires a single client');
|
|
45
|
+
const config = await loadConfig(root);
|
|
46
|
+
const entry = mcpConfig(root, options.watch).mcpServers.bati;
|
|
47
|
+
const targets = clients.map((client) => ({ client, file: config.outputs[`mcp-${client}`] || options.out ?
|
|
48
|
+
configuredOutput(root, config, `mcp-${client}`, configPath(client, root), options.out) : configPath(client, root) }));
|
|
49
|
+
if (options.dryRun)
|
|
50
|
+
return { title: 'MCP installation plan', lines: targets.map(({ client, file }) => `${client} · ${file}`), data: { targets, entry } };
|
|
51
|
+
const handles = [];
|
|
52
|
+
const settings = [];
|
|
53
|
+
try {
|
|
54
|
+
for (const { client, file: target } of targets.sort((a, b) => a.file.localeCompare(b.file))) {
|
|
55
|
+
const parent = path.dirname(target);
|
|
56
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
57
|
+
const file = path.join(await realpath(parent), path.basename(target));
|
|
58
|
+
const lock = file + '.bati.lock';
|
|
59
|
+
const handle = await open(lock, 'wx', 0o600);
|
|
60
|
+
handles.push({ file: lock, handle });
|
|
61
|
+
let previous;
|
|
62
|
+
try {
|
|
63
|
+
const metadata = await lstat(file);
|
|
64
|
+
if (!metadata.isFile())
|
|
65
|
+
throw new Error(`MCP configuration must be a regular file: ${file}`);
|
|
66
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
67
|
+
try {
|
|
68
|
+
previous = await handle.readFile('utf8');
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
await handle.close();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code !== 'ENOENT')
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
settings.push({ client, file, previous, next: mergeMcpConfig(previous, entry, options.replace) });
|
|
79
|
+
}
|
|
80
|
+
const datetime = new Date().toISOString().replace(/[:.]/g, '-');
|
|
81
|
+
const changed = [];
|
|
82
|
+
for (const { client, file, previous, next } of settings) {
|
|
83
|
+
let backup;
|
|
84
|
+
if (next !== undefined) {
|
|
85
|
+
if (previous !== undefined) {
|
|
86
|
+
backup = file + '.bati-' + datetime + '.bak';
|
|
87
|
+
await writeFile(backup, previous, { mode: 0o600, flag: 'wx' });
|
|
88
|
+
}
|
|
89
|
+
await writeOutput(file, next, 0o600);
|
|
90
|
+
}
|
|
91
|
+
changed.push({ client, file, updated: next !== undefined, backup });
|
|
92
|
+
}
|
|
93
|
+
return { title: 'MCP configuration', lines: changed.flatMap((item) => [`${item.updated ? 'Updated' : 'Already configured'} · ${item.file}`, ...(item.backup ? [`Backup · ${item.backup}`] : [])]), data: changed };
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
await Promise.all(handles.map(async ({ file, handle }) => {
|
|
97
|
+
try {
|
|
98
|
+
await handle.close();
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
await rm(file, { force: true });
|
|
102
|
+
}
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import type { DependencyGraph } from './deps.js';
|
|
3
|
+
export declare function changeImpact(graph: DependencyGraph, files: string[]): {
|
|
4
|
+
file: string;
|
|
5
|
+
distance: number;
|
|
6
|
+
}[];
|
|
7
|
+
export declare function createMcp(dir: string): Promise<{
|
|
8
|
+
server: McpServer;
|
|
9
|
+
invalidate(): void;
|
|
10
|
+
}>;
|
|
11
|
+
export declare const startMcp: (dir: string, watchChanges?: boolean) => Promise<void>;
|
|
12
|
+
export { mcpConfig } from './mcp-install.js';
|
package/dist/core/mcp.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { readFileSync, watch } from 'node:fs';
|
|
4
|
+
import { stat } from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { filterModel, roleStats, scanProject } from './scan.js';
|
|
8
|
+
import { toMermaid } from './diagram.js';
|
|
9
|
+
import { loadSpec } from './openapi.js';
|
|
10
|
+
import { loadConfig } from './config.js';
|
|
11
|
+
import { listFiles, runGit } from './files.js';
|
|
12
|
+
const packageVersion = () => {
|
|
13
|
+
for (const relative of ['../package.json', '../../package.json']) {
|
|
14
|
+
try {
|
|
15
|
+
const file = new URL(relative, import.meta.url);
|
|
16
|
+
const manifest = JSON.parse(readFileSync(file, 'utf8'));
|
|
17
|
+
if (manifest.name === 'bati' && typeof manifest.version === 'string')
|
|
18
|
+
return manifest.version;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT')
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
throw new Error('Unable to locate the bati package version');
|
|
26
|
+
};
|
|
27
|
+
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
28
|
+
const brief = (c) => ({
|
|
29
|
+
name: c.name,
|
|
30
|
+
kind: c.kind,
|
|
31
|
+
file: c.file,
|
|
32
|
+
extends: c.extends,
|
|
33
|
+
implements: c.implements,
|
|
34
|
+
traits: c.traits
|
|
35
|
+
});
|
|
36
|
+
const full = (c) => ({
|
|
37
|
+
...brief(c),
|
|
38
|
+
props: c.props.map((p) => `${p.visibility}${p.static ? ' static' : ''} ${p.name}${p.type ? ': ' + p.type : ''}`),
|
|
39
|
+
methods: c.methods.map((m) => `${m.visibility}${m.static ? ' static' : ''} ${m.name}(${m.params ?? ''})${m.returns ? ': ' + m.returns : ''}`)
|
|
40
|
+
});
|
|
41
|
+
function cached(load) {
|
|
42
|
+
let pending;
|
|
43
|
+
return {
|
|
44
|
+
clear() { pending = undefined; },
|
|
45
|
+
get() {
|
|
46
|
+
if (!pending) {
|
|
47
|
+
const current = load().catch((error) => { if (pending === current)
|
|
48
|
+
pending = undefined; throw error; });
|
|
49
|
+
pending = current;
|
|
50
|
+
}
|
|
51
|
+
return pending;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function changeImpact(graph, files) {
|
|
56
|
+
const reverse = new Map();
|
|
57
|
+
for (const edge of graph.edges) {
|
|
58
|
+
const source = reverse.get(edge.to) ?? [];
|
|
59
|
+
source.push(edge.from);
|
|
60
|
+
reverse.set(edge.to, source);
|
|
61
|
+
}
|
|
62
|
+
const queue = files.map((file) => ({ file, distance: 0 }));
|
|
63
|
+
const seen = new Set(files);
|
|
64
|
+
for (let index = 0; index < queue.length; index++) {
|
|
65
|
+
const from = queue[index];
|
|
66
|
+
for (const file of reverse.get(from.file) ?? [])
|
|
67
|
+
if (!seen.has(file)) {
|
|
68
|
+
seen.add(file);
|
|
69
|
+
queue.push({ file, distance: from.distance + 1 });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return queue.slice(files.length);
|
|
73
|
+
}
|
|
74
|
+
export async function createMcp(dir) {
|
|
75
|
+
const root = path.resolve(dir);
|
|
76
|
+
const scan = cached(() => scanProject(root));
|
|
77
|
+
const dependencies = cached(async () => (await import('./deps.js')).analyzeDeps(root));
|
|
78
|
+
const routes = cached(async () => (await import('./routes.js')).collectRoutes(root));
|
|
79
|
+
const schema = cached(async () => (await import('./db.js')).collectSchema(root));
|
|
80
|
+
const inventory = cached(() => listFiles(root));
|
|
81
|
+
const model = (refresh = false) => {
|
|
82
|
+
if (refresh)
|
|
83
|
+
scan.clear();
|
|
84
|
+
return scan.get();
|
|
85
|
+
};
|
|
86
|
+
const server = new McpServer({ name: 'bati', version: packageVersion() });
|
|
87
|
+
server.tool('project_overview', 'High level overview of the project: languages, file roles, counts and top level folders', { refresh: z.boolean().optional() }, async ({ refresh }) => {
|
|
88
|
+
const m = await model(refresh);
|
|
89
|
+
const dirs = new Map();
|
|
90
|
+
for (const f of m.files) {
|
|
91
|
+
const top = f.path.includes('/') ? f.path.split('/')[0] : '.';
|
|
92
|
+
dirs.set(top, (dirs.get(top) ?? 0) + 1);
|
|
93
|
+
}
|
|
94
|
+
return text({
|
|
95
|
+
root: m.root,
|
|
96
|
+
files: m.files.length,
|
|
97
|
+
classes: m.classes.length,
|
|
98
|
+
lines: m.files.reduce((a, f) => a + f.lines, 0),
|
|
99
|
+
roles: Object.fromEntries(roleStats(m)),
|
|
100
|
+
folders: Object.fromEntries([...dirs.entries()].sort((a, b) => b[1] - a[1]).slice(0, 25))
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
server.tool('list_files', 'List project files with their inferred role (controller, model, service, component...) and the classes they define', { role: z.string().optional(), language: z.enum(['ts', 'js', 'php']).optional(), query: z.string().optional(), limit: z.number().int().positive().optional() }, async ({ role, language, query, limit }) => {
|
|
104
|
+
const m = await model();
|
|
105
|
+
const q = query?.toLowerCase();
|
|
106
|
+
const rows = m.files
|
|
107
|
+
.filter((f) => (!role || f.role === role) && (!language || f.lang === language) && (!q || f.path.toLowerCase().includes(q) || f.classes.some((c) => c.toLowerCase().includes(q))))
|
|
108
|
+
.slice(0, limit ?? 100)
|
|
109
|
+
.map((f) => ({ path: f.path, role: f.role, lines: f.lines, classes: f.classes }));
|
|
110
|
+
return text(rows);
|
|
111
|
+
});
|
|
112
|
+
server.tool('get_class', 'Full structure of a class, interface, trait or enum: members, parents, children and dependencies', { name: z.string() }, async ({ name }) => {
|
|
113
|
+
const m = await model();
|
|
114
|
+
const c = m.classes.find((x) => x.name === name) ?? m.classes.find((x) => x.name.toLowerCase() === name.toLowerCase());
|
|
115
|
+
if (!c)
|
|
116
|
+
return text(`No class named ${name}`);
|
|
117
|
+
const byId = new Map(m.classes.map((x) => [x.id, x]));
|
|
118
|
+
const out = m.edges.filter((e) => e.from === c.id).map((e) => ({ kind: e.kind, target: byId.get(e.to)?.name }));
|
|
119
|
+
const inc = m.edges.filter((e) => e.to === c.id).map((e) => ({ kind: e.kind, source: byId.get(e.from)?.name }));
|
|
120
|
+
return text({ ...full(c), dependsOn: out, usedBy: inc });
|
|
121
|
+
});
|
|
122
|
+
server.tool('find_related', 'Neighbourhood of a class in the dependency graph up to a given depth', { name: z.string(), depth: z.number().int().min(1).max(4).optional() }, async ({ name, depth }) => {
|
|
123
|
+
const m = await model();
|
|
124
|
+
const start = m.classes.find((x) => x.name === name);
|
|
125
|
+
if (!start)
|
|
126
|
+
return text(`No class named ${name}`);
|
|
127
|
+
const seen = new Set([start.id]);
|
|
128
|
+
let frontier = [start.id];
|
|
129
|
+
for (let i = 0; i < (depth ?? 1); i++) {
|
|
130
|
+
const next = [];
|
|
131
|
+
for (const e of m.edges) {
|
|
132
|
+
if (frontier.includes(e.from) && !seen.has(e.to))
|
|
133
|
+
(seen.add(e.to), next.push(e.to));
|
|
134
|
+
if (frontier.includes(e.to) && !seen.has(e.from))
|
|
135
|
+
(seen.add(e.from), next.push(e.from));
|
|
136
|
+
}
|
|
137
|
+
frontier = next;
|
|
138
|
+
}
|
|
139
|
+
return text(m.classes.filter((c) => seen.has(c.id)).map(brief));
|
|
140
|
+
});
|
|
141
|
+
server.tool('class_diagram', 'Mermaid class diagram for the whole project or for classes matching a query and their direct neighbours', { query: z.string().optional() }, async ({ query }) => {
|
|
142
|
+
const m = await model();
|
|
143
|
+
return text(toMermaid(filterModel(m, query)));
|
|
144
|
+
});
|
|
145
|
+
server.tool('file_outline', 'Role, size and class outline of a single file, optionally with its source', { path: z.string(), include_source: z.boolean().optional() }, async ({ path: p, include_source }) => {
|
|
146
|
+
const m = await model();
|
|
147
|
+
const f = m.files.find((x) => x.path === p);
|
|
148
|
+
if (!f)
|
|
149
|
+
return text(`Unknown file ${p}`);
|
|
150
|
+
const cs = m.classes.filter((c) => c.file === p).map(full);
|
|
151
|
+
return text({ ...f, outline: cs, source: include_source ? readFileSync(path.join(root, p), 'utf8') : undefined });
|
|
152
|
+
});
|
|
153
|
+
server.tool('api_endpoints', 'Summarise the endpoints of an OpenAPI document (path or URL)', { spec: z.string() }, async ({ spec }) => {
|
|
154
|
+
const s = await loadSpec(spec);
|
|
155
|
+
const rows = [];
|
|
156
|
+
for (const [p, item] of Object.entries(s.paths ?? {})) {
|
|
157
|
+
for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
|
|
158
|
+
if (item[method])
|
|
159
|
+
rows.push(`${method.toUpperCase()} ${p}${item[method].summary ? ' — ' + item[method].summary : ''}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return text(rows);
|
|
163
|
+
});
|
|
164
|
+
const targets = async (target) => {
|
|
165
|
+
const relative = path.relative(root, path.resolve(root, target)).split(path.sep).join('/');
|
|
166
|
+
const graph = await dependencies.get();
|
|
167
|
+
if (graph.files.some((file) => file.path === relative))
|
|
168
|
+
return [relative];
|
|
169
|
+
return [...new Set((await model()).classes.filter((info) => info.name.toLowerCase() === target.toLowerCase()).map((info) => info.file))];
|
|
170
|
+
};
|
|
171
|
+
server.tool('find_usages', 'Find file imports and class references for a file or class', { target: z.string().min(1) }, async ({ target }) => {
|
|
172
|
+
const files = await targets(target);
|
|
173
|
+
const graph = await dependencies.get();
|
|
174
|
+
const m = await model();
|
|
175
|
+
const classes = new Map(m.classes.map((item) => [item.id, item]));
|
|
176
|
+
const references = m.edges.filter((edge) => files.includes(classes.get(edge.to).file) &&
|
|
177
|
+
(target.toLowerCase() === classes.get(edge.to).name.toLowerCase() || files.includes(target)))
|
|
178
|
+
.map((edge) => ({ from: brief(classes.get(edge.from)), target: brief(classes.get(edge.to)), kind: edge.kind }));
|
|
179
|
+
return text({ files, imports: graph.edges.filter((edge) => files.includes(edge.to)), references });
|
|
180
|
+
});
|
|
181
|
+
server.tool('impact_of_change', 'Find all direct and transitive dependents of a file or class', { target: z.string().min(1) }, async ({ target }) => {
|
|
182
|
+
const files = await targets(target);
|
|
183
|
+
return text({ files, dependents: changeImpact(await dependencies.get(), files) });
|
|
184
|
+
});
|
|
185
|
+
server.tool('list_routes', 'List supported framework routes', { query: z.string().optional(), limit: z.number().int().min(1).max(1000).optional() }, async ({ query, limit }) => {
|
|
186
|
+
const q = query?.toLowerCase();
|
|
187
|
+
return text((await routes.get()).filter((route) => !q || `${route.method} ${route.path} ${route.framework} ${route.controller ?? ''}`.toLowerCase().includes(q)).slice(0, limit ?? 100));
|
|
188
|
+
});
|
|
189
|
+
server.tool('explain_route', 'Get a route, middleware, controller location and inferred request and response shapes', { path: z.string(), method: z.string().optional() }, async (input) => text((await routes.get()).filter((route) => route.path === input.path && (!input.method || route.method === input.method.toUpperCase()))));
|
|
190
|
+
server.tool('db_schema', 'Get inferred database tables, columns and keys', { table: z.string().optional() }, async ({ table }) => {
|
|
191
|
+
const data = await schema.get();
|
|
192
|
+
return text({ ...data, tables: data.tables.filter((item) => !table || item.name.toLowerCase() === table.toLowerCase()) });
|
|
193
|
+
});
|
|
194
|
+
server.tool('diff_summary', 'Summarize unstaged and staged Git changes by file', { staged: z.boolean().optional() }, async ({ staged }) => {
|
|
195
|
+
const status = await runGit('git', ['status', '--short', '--untracked-files=normal', '--', '.'], { cwd: root });
|
|
196
|
+
const diff = await runGit('git', ['diff', ...(staged ? ['--cached'] : []), '--stat', '--', '.'], { cwd: root, maxBuffer: 8 * 1024 * 1024 });
|
|
197
|
+
return text({ staged: !!staged, status: status.stdout.trimEnd(), summary: diff.stdout.trimEnd() });
|
|
198
|
+
});
|
|
199
|
+
const resourceUri = (file) => `bati://outline/${Buffer.from(file, 'utf8').toString('base64url')}`;
|
|
200
|
+
server.registerResource('file-outline', new ResourceTemplate('bati://outline/{id}', {
|
|
201
|
+
list: async () => ({ resources: (await inventory.get()).map((file) => ({ uri: resourceUri(file), name: file, mimeType: 'application/json' })) })
|
|
202
|
+
}), { mimeType: 'application/json', description: 'File metadata and declared class members' }, async (uri, { id }) => {
|
|
203
|
+
if (typeof id !== 'string')
|
|
204
|
+
throw new Error('Invalid outline URI');
|
|
205
|
+
const file = Buffer.from(id, 'base64url').toString('utf8');
|
|
206
|
+
if (uri.href !== resourceUri(file) || !(await inventory.get()).includes(file))
|
|
207
|
+
throw new Error('Unknown file outline');
|
|
208
|
+
const m = await model();
|
|
209
|
+
const record = m.files.find((item) => item.path === file);
|
|
210
|
+
const metadata = await stat(path.join(root, file));
|
|
211
|
+
return { contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify({
|
|
212
|
+
path: file, size: metadata.size, ...record, classes: m.classes.filter((item) => item.file === file).map(full)
|
|
213
|
+
}) }] };
|
|
214
|
+
});
|
|
215
|
+
const config = await loadConfig(root);
|
|
216
|
+
for (const tool of config.plugins.flatMap((plugin) => plugin.mcpTools ?? [])) {
|
|
217
|
+
server.tool(tool.name, tool.description, tool.input, async (args) => text(await tool.run({ root }, args)));
|
|
218
|
+
}
|
|
219
|
+
return { server, invalidate() {
|
|
220
|
+
for (const cache of [scan, dependencies, routes, schema, inventory])
|
|
221
|
+
cache.clear();
|
|
222
|
+
server.sendResourceListChanged();
|
|
223
|
+
} };
|
|
224
|
+
}
|
|
225
|
+
export const startMcp = async (dir, watchChanges = false) => {
|
|
226
|
+
const { server, invalidate } = await createMcp(dir);
|
|
227
|
+
const transport = new StdioServerTransport();
|
|
228
|
+
await server.connect(transport);
|
|
229
|
+
if (!watchChanges)
|
|
230
|
+
return;
|
|
231
|
+
let timer;
|
|
232
|
+
const watcher = watch(path.resolve(dir), { recursive: true, persistent: false }, (_, file) => {
|
|
233
|
+
if (file && /(?:^|[\\/])(?:node_modules|vendor|\.git|dist|\.next|storage|coverage)(?:[\\/]|$)/.test(file))
|
|
234
|
+
return;
|
|
235
|
+
if (timer)
|
|
236
|
+
clearTimeout(timer);
|
|
237
|
+
timer = setTimeout(invalidate, 120);
|
|
238
|
+
timer.unref();
|
|
239
|
+
});
|
|
240
|
+
watcher.on('error', (error) => process.stderr.write(`bati MCP watch: ${error.message}\n`));
|
|
241
|
+
process.stdin.once('end', () => { watcher.close(); if (timer)
|
|
242
|
+
clearTimeout(timer); });
|
|
243
|
+
};
|
|
244
|
+
export { mcpConfig } from './mcp-install.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type S = any;
|
|
2
|
+
export declare const loadSpec: (src: string) => Promise<S>;
|
|
3
|
+
export interface GenOptions {
|
|
4
|
+
typesOnly?: boolean;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
zod?: boolean;
|
|
7
|
+
query?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface GenResult {
|
|
10
|
+
code: string;
|
|
11
|
+
parts: Record<string, string>;
|
|
12
|
+
operations: number;
|
|
13
|
+
schemas: number;
|
|
14
|
+
}
|
|
15
|
+
export declare const generate: (spec: S, opts?: GenOptions) => Promise<GenResult>;
|
|
16
|
+
export {};
|