@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.
Files changed (67) hide show
  1. package/README.md +164 -2
  2. package/assets/bati-mark.svg +26 -0
  3. package/dist/api.ts +0 -0
  4. package/dist/bati-db.png +0 -0
  5. package/dist/bati-openapi.json +8 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +174 -0
  8. package/dist/core/api-generate.d.ts +9 -0
  9. package/dist/core/api-generate.js +74 -0
  10. package/dist/core/api.d.ts +44 -0
  11. package/dist/core/api.js +292 -0
  12. package/dist/core/config.d.ts +40 -0
  13. package/dist/core/config.js +53 -0
  14. package/dist/core/dashboard.d.ts +37 -0
  15. package/dist/core/dashboard.js +95 -0
  16. package/dist/core/db.d.ts +31 -0
  17. package/dist/core/db.js +392 -0
  18. package/dist/core/deps.d.ts +35 -0
  19. package/dist/core/deps.js +242 -0
  20. package/dist/core/diagram.d.ts +4 -0
  21. package/dist/core/diagram.js +151 -0
  22. package/dist/core/doctor.d.ts +23 -0
  23. package/dist/core/doctor.js +148 -0
  24. package/dist/core/files.d.ts +5 -0
  25. package/dist/core/files.js +69 -0
  26. package/dist/core/format.d.ts +13 -0
  27. package/dist/core/format.js +54 -0
  28. package/dist/core/graph-view.d.ts +2 -0
  29. package/dist/core/graph-view.js +65 -0
  30. package/dist/core/mcp-install.d.ts +19 -0
  31. package/dist/core/mcp-install.js +105 -0
  32. package/dist/core/mcp.d.ts +12 -0
  33. package/dist/core/mcp.js +244 -0
  34. package/dist/core/openapi.d.ts +16 -0
  35. package/dist/core/openapi.js +270 -0
  36. package/dist/core/pack.d.ts +8 -0
  37. package/dist/core/pack.js +101 -0
  38. package/dist/core/php.d.ts +6 -0
  39. package/dist/core/php.js +50 -0
  40. package/dist/core/preview.d.ts +9 -0
  41. package/dist/core/preview.js +89 -0
  42. package/dist/core/probe.d.ts +21 -0
  43. package/dist/core/probe.js +119 -0
  44. package/dist/core/routes.d.ts +37 -0
  45. package/dist/core/routes.js +343 -0
  46. package/dist/core/scan.d.ts +13 -0
  47. package/dist/core/scan.js +395 -0
  48. package/dist/core/tasks.d.ts +34 -0
  49. package/dist/core/tasks.js +88 -0
  50. package/dist/core/types.d.ts +46 -0
  51. package/dist/core/types.js +1 -0
  52. package/dist/openapi.json +8 -0
  53. package/dist/theme.d.ts +12 -0
  54. package/dist/theme.js +32 -0
  55. package/dist/ui/App.d.ts +5 -0
  56. package/dist/ui/App.js +247 -0
  57. package/dist/ui/Banner.d.ts +5 -0
  58. package/dist/ui/Banner.js +9 -0
  59. package/dist/ui/Dashboard.d.ts +26 -0
  60. package/dist/ui/Dashboard.js +52 -0
  61. package/dist/ui/MapView.d.ts +5 -0
  62. package/dist/ui/MapView.js +47 -0
  63. package/dist/ui/Wizard.d.ts +17 -0
  64. package/dist/ui/Wizard.js +112 -0
  65. package/dist/ui/presentation.d.ts +24 -0
  66. package/dist/ui/presentation.js +15 -0
  67. package/package.json +80 -4
@@ -0,0 +1,292 @@
1
+ import http from 'node:http';
2
+ import path from 'node:path';
3
+ import { watchFile, unwatchFile } from 'node:fs';
4
+ import { configuredOutput, loadConfig } from './config.js';
5
+ import { writeOutput } from './files.js';
6
+ import { loadSpec } from './openapi.js';
7
+ const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];
8
+ const owns = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
9
+ export const operationsOf = (spec) => new Map(Object.entries(spec.paths ?? {}).flatMap(([route, item]) => methods.filter((method) => item?.[method]).map((method) => [`${method.toUpperCase()} ${route}`, { route, method, operation: item[method], item }])));
10
+ export function resolveRef(value, spec) {
11
+ const visited = new Set();
12
+ while (typeof value?.$ref === 'string') {
13
+ const ref = value.$ref;
14
+ if (!ref.startsWith('#/') || visited.has(ref))
15
+ return {};
16
+ visited.add(ref);
17
+ value = ref.slice(2).split('/').reduce((entry, segment) => {
18
+ const key = decodeURIComponent(segment).replace(/~1/g, '/').replace(/~0/g, '~');
19
+ return entry && owns(entry, key) ? entry[key] : undefined;
20
+ }, spec);
21
+ }
22
+ return value ?? {};
23
+ }
24
+ export function compareSpecs(previous, next) {
25
+ const oldOps = operationsOf(previous);
26
+ const newOps = operationsOf(next);
27
+ const changes = [];
28
+ for (const [operation, oldItem] of oldOps) {
29
+ const add = (breaking, message) => changes.push({ operation, breaking, message });
30
+ const newItem = newOps.get(operation);
31
+ if (!newItem) {
32
+ add(true, 'Operation removed');
33
+ continue;
34
+ }
35
+ const seen = new WeakMap();
36
+ const compareSchema = (oldValue, newValue, label, input) => {
37
+ const a = resolveRef(oldValue, previous);
38
+ const b = resolveRef(newValue, next);
39
+ if (typeof a !== 'object' || typeof b !== 'object') {
40
+ if (a !== b)
41
+ add(input ? b === false : a === false, `${label} changed boolean schema`);
42
+ return;
43
+ }
44
+ const visited = seen.get(a) ?? new WeakSet();
45
+ if (visited.has(b))
46
+ return;
47
+ visited.add(b);
48
+ seen.set(a, visited);
49
+ const oldTypes = new Set([a.type].flat().filter(Boolean));
50
+ const newTypes = new Set([b.type].flat().filter(Boolean));
51
+ if (a.nullable)
52
+ oldTypes.add('null');
53
+ if (b.nullable)
54
+ newTypes.add('null');
55
+ const subset = (left, right) => !right.size || (left.size > 0 && [...left].every((type) => right.has(type) || type === 'integer' && right.has('number')));
56
+ if (!(subset(oldTypes, newTypes) && subset(newTypes, oldTypes)))
57
+ add(input ? !subset(oldTypes, newTypes) : !subset(newTypes, oldTypes), `${label} changed type`);
58
+ const allowed = (schema) => schema.enum?.map((value) => JSON.stringify(value)) ?? (owns(schema, 'const') ? [JSON.stringify(schema.const)] : undefined);
59
+ const oldValues = allowed(a);
60
+ const newValues = allowed(b);
61
+ const fits = (x, y) => !y || !!x?.every((entry) => y.includes(entry));
62
+ if (!(fits(oldValues, newValues) && fits(newValues, oldValues)))
63
+ add(input ? !fits(oldValues, newValues) : !fits(newValues, oldValues), `${label} changed allowed values`);
64
+ for (const [field, direction] of Object.entries({ minimum: 1, maximum: -1, minLength: 1, maxLength: -1, minItems: 1, maxItems: -1 })) {
65
+ if (a[field] === b[field])
66
+ continue;
67
+ const oldBound = a[field] ?? (direction === 1 ? -Infinity : Infinity);
68
+ const newBound = b[field] ?? (direction === 1 ? -Infinity : Infinity);
69
+ const narrowed = (newBound - oldBound) * direction > 0;
70
+ add(input ? narrowed : !narrowed, `${label} changed ${field}`);
71
+ }
72
+ for (const field of ['pattern', 'format', 'oneOf', 'allOf', 'anyOf', 'additionalProperties']) {
73
+ if (JSON.stringify(a[field]) !== JSON.stringify(b[field]))
74
+ add(true, `${label} changed ${field}`);
75
+ }
76
+ if (a.items && b.items)
77
+ compareSchema(a.items, b.items, `${label} items`, input);
78
+ const oldProperties = a.properties ?? {};
79
+ const newProperties = b.properties ?? {};
80
+ const oldRequired = new Set(a.required ?? []);
81
+ const newRequired = new Set(b.required ?? []);
82
+ for (const key of new Set([...Object.keys(oldProperties), ...Object.keys(newProperties)])) {
83
+ const name = `${label}.${key}`;
84
+ if (!owns(newProperties, key))
85
+ add(!input || b.additionalProperties === false, `${name} removed`);
86
+ else if (!owns(oldProperties, key))
87
+ add(input && newRequired.has(key), `${name} added`);
88
+ else {
89
+ if (oldRequired.has(key) !== newRequired.has(key))
90
+ add(input ? newRequired.has(key) : oldRequired.has(key), `${name} changed required status`);
91
+ compareSchema(oldProperties[key], newProperties[key], name, input);
92
+ }
93
+ }
94
+ };
95
+ const params = (entry, spec) => new Map([...(entry.item.parameters ?? []), ...(entry.operation.parameters ?? [])].map((param) => {
96
+ const value = resolveRef(param, spec);
97
+ return [`${value.in} ${value.name}`, value];
98
+ }));
99
+ const oldParams = params(oldItem, previous);
100
+ const newParams = params(newItem, next);
101
+ for (const [key, param] of newParams) {
102
+ const oldParam = oldParams.get(key);
103
+ if (!oldParam)
104
+ add(!!param.required, `Parameter ${key} added`);
105
+ else {
106
+ if (!!oldParam.required !== !!param.required)
107
+ add(!!param.required, `Parameter ${key} changed required status`);
108
+ compareSchema(oldParam.schema, param.schema, `Parameter ${key}`, true);
109
+ }
110
+ }
111
+ for (const key of oldParams.keys())
112
+ if (!newParams.has(key))
113
+ add(key.startsWith('path '), `Parameter ${key} removed`);
114
+ const content = (a, b, label, input) => {
115
+ const oldContent = a.content ?? {};
116
+ const newContent = b.content ?? {};
117
+ for (const mime of new Set([...Object.keys(oldContent), ...Object.keys(newContent)])) {
118
+ if (!owns(newContent, mime))
119
+ add(true, `${label} removed media type ${mime}`);
120
+ else if (!owns(oldContent, mime))
121
+ add(false, `${label} added media type ${mime}`);
122
+ else
123
+ compareSchema(oldContent[mime].schema, newContent[mime].schema, `${label} ${mime}`, input);
124
+ }
125
+ };
126
+ const oldBody = resolveRef(oldItem.operation.requestBody, previous);
127
+ const newBody = resolveRef(newItem.operation.requestBody, next);
128
+ if (!!oldBody.required !== !!newBody.required)
129
+ add(!!newBody.required, 'Request body changed required status');
130
+ content(oldBody, newBody, 'Request body', true);
131
+ const oldResponses = oldItem.operation.responses ?? {};
132
+ const newResponses = newItem.operation.responses ?? {};
133
+ for (const status of new Set([...Object.keys(oldResponses), ...Object.keys(newResponses)])) {
134
+ if (!owns(newResponses, status))
135
+ add(status.startsWith('2') || status === 'default', `Response ${status} removed`);
136
+ else if (!owns(oldResponses, status))
137
+ add(false, `Response ${status} added`);
138
+ else
139
+ content(resolveRef(oldResponses[status], previous), resolveRef(newResponses[status], next), `Response ${status}`, false);
140
+ }
141
+ const oldSecurity = oldItem.operation.security ?? previous.security ?? [];
142
+ const newSecurity = newItem.operation.security ?? next.security ?? [];
143
+ const alternatives = (security) => security.length ? security : [{}];
144
+ const canUse = (before, after) => Object.entries(after).every(([scheme, scopes]) => owns(before, scheme) && scopes.every((scope) => before[scheme].includes(scope)));
145
+ if (JSON.stringify(oldSecurity) !== JSON.stringify(newSecurity))
146
+ add(alternatives(oldSecurity).some((before) => !alternatives(newSecurity).some((after) => canUse(before, after))), 'Security requirements changed');
147
+ }
148
+ for (const operation of newOps.keys())
149
+ if (!oldOps.has(operation))
150
+ changes.push({ operation, breaking: false, message: 'Operation added' });
151
+ return changes;
152
+ }
153
+ export async function apiDiff(options) {
154
+ const [old, next] = await Promise.all([loadSpec(options.old), loadSpec(options.next)]);
155
+ const changes = compareSpecs(old, next);
156
+ const breaking = changes.filter((change) => change.breaking).length;
157
+ const format = options.format ?? (options.out?.endsWith('.json') ? 'json' : 'markdown');
158
+ if (format !== 'markdown' && format !== 'json')
159
+ throw new Error('Report format must be markdown or json');
160
+ const summary = `${breaking} breaking · ${changes.length - breaking} non-breaking`;
161
+ const lines = changes.map((item) => `- **${item.breaking ? 'Breaking' : 'Non-breaking'}** ${item.operation.replace(/[\x00-\x1f<>]/g, '')} · ${item.message.replace(/[\x00-\x1f<>]/g, '')}`);
162
+ const data = { breaking, nonBreaking: changes.length - breaking, changes };
163
+ const report = format === 'json' ? JSON.stringify(data, null, 2) : ['# OpenAPI diff', '', summary, '', ...lines].join('\n');
164
+ const config = await loadConfig();
165
+ const output = options.out || config.outputs['api-diff'] ? await writeOutput(configuredOutput('.', config, 'api-diff', 'bati-api-diff.md', options.out), report + '\n') : undefined;
166
+ return { title: 'OpenAPI diff', lines: [summary, ...(format === 'json' ? [report] : lines), ...(output ? [output] : [])], data, output, exitCode: breaking ? 1 : 0 };
167
+ }
168
+ export function exampleValue(schema, spec, field = '', depth = 0) {
169
+ if (depth > 8)
170
+ return null;
171
+ const value = resolveRef(schema, spec);
172
+ if (owns(value, 'example'))
173
+ return value.example;
174
+ if (value.examples?.length)
175
+ return value.examples[0];
176
+ if (owns(value, 'default'))
177
+ return value.default;
178
+ if (owns(value, 'const'))
179
+ return value.const;
180
+ if (value.enum?.length)
181
+ return value.enum[0];
182
+ if (value.oneOf?.length || value.anyOf?.length)
183
+ return exampleValue((value.oneOf ?? value.anyOf)[0], spec, field, depth + 1);
184
+ if (value.allOf?.length)
185
+ return Object.assign({}, ...value.allOf.map((item) => exampleValue(item, spec, field, depth + 1)));
186
+ const type = Array.isArray(value.type) ? value.type.find((type) => type !== 'null') : value.type;
187
+ if (type === 'object' || value.properties)
188
+ return Object.fromEntries(Object.entries(value.properties ?? {}).map(([key, child]) => [key, exampleValue(child, spec, key, depth + 1)]));
189
+ if (type === 'array')
190
+ return Array.from({ length: Math.min(20, value.maxItems ?? Infinity, Math.max(1, value.minItems ?? 0)) }, () => exampleValue(value.items, spec, field, depth + 1));
191
+ if (type === 'integer' || type === 'number')
192
+ return Math.min(value.maximum ?? Infinity, Math.max(value.minimum ?? -Infinity, 42));
193
+ if (type === 'boolean')
194
+ return true;
195
+ if (type === 'null')
196
+ return null;
197
+ const known = {
198
+ email: 'alex.rivera@example.test', uuid: 'b6f424fd-1214-4f82-83f9-d7af25a0415a', date: '2025-03-14',
199
+ 'date-time': '2025-03-14T10:00:00Z', uri: 'https://example.test/profile', url: 'https://example.test/profile',
200
+ name: 'Alex Rivera', firstname: 'Alex', lastname: 'Rivera', city: 'Portland', phone: '+1-202-555-0142', id: 'user_42'
201
+ };
202
+ const sample = known[value.format] ?? known[field.toLowerCase().replace(/_/g, '')] ?? (field ? `Example ${field}` : 'Example value');
203
+ return sample.padEnd(Math.min(1000, value.minLength ?? 0), 'x').slice(0, value.maxLength);
204
+ }
205
+ const regexEscape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
206
+ export function mockResponses(spec) {
207
+ const routes = [...operationsOf(spec).values()].sort((a, b) => Number(a.route.includes('{')) - Number(b.route.includes('{')) || b.route.length - a.route.length).map((route) => ({
208
+ ...route, pattern: new RegExp('^' + route.route.split(/(\{[^}]+\})/).map((part) => part.startsWith('{') ? '[^/]+' : regexEscape(part)).join('') + '/?$')
209
+ }));
210
+ return { count: routes.length, respond(method, target, requested = '') {
211
+ try {
212
+ const url = new URL(target, 'http://localhost');
213
+ const route = routes.find((entry) => entry.method.toUpperCase() === method && entry.pattern.test(url.pathname));
214
+ if (!route) {
215
+ return { status: 404, mime: 'application/json', payload: JSON.stringify({ error: 'Route not found' }) };
216
+ }
217
+ const responses = route.operation.responses ?? {};
218
+ const key = owns(responses, requested) && /^\d{3}$/.test(requested) ? requested : Object.keys(responses).sort().find((status) => /^2/.test(status)) ?? 'default';
219
+ const status = /^\d{3}$/.test(key) ? Number(key) : 200;
220
+ const body = resolveRef(responses[key], spec).content ?? {};
221
+ const mime = Object.keys(body).find((type) => type.includes('json')) ?? Object.keys(body)[0];
222
+ if (!mime || status === 204 || status === 304 || method === 'HEAD')
223
+ return { status };
224
+ const media = body[mime];
225
+ const example = Object.values(media.examples ?? {})[0];
226
+ const value = media.example ?? (example ? resolveRef(example, spec).value : undefined) ?? exampleValue(media.schema, spec);
227
+ return { status, mime, payload: mime.includes('json') || typeof value !== 'string' ? JSON.stringify(value) : value };
228
+ }
229
+ catch {
230
+ return { status: 500 };
231
+ }
232
+ } };
233
+ }
234
+ export async function startMock(options) {
235
+ const spec = await loadSpec(options.spec);
236
+ const port = options.port ?? 4010;
237
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
238
+ throw new Error('Port must be an integer from 0 to 65535');
239
+ const mock = mockResponses(spec);
240
+ const server = http.createServer((request, response) => {
241
+ const status = request.headers['x-mock-status'];
242
+ const { status: code, mime, payload } = mock.respond(request.method, request.url ?? '/', typeof status === 'string' ? status : undefined);
243
+ response.writeHead(code, mime ? { 'content-type': mime } : {}).end(payload);
244
+ });
245
+ const close = () => { server.close(); server.closeAllConnections(); };
246
+ await new Promise((resolve, reject) => {
247
+ server.once('error', reject);
248
+ server.listen(port, '127.0.0.1', () => { server.off('error', reject); resolve(); });
249
+ });
250
+ if (options.signal?.aborted)
251
+ close();
252
+ else if (options.signal) {
253
+ options.signal.addEventListener('abort', close, { once: true });
254
+ server.once('close', () => options.signal?.removeEventListener('abort', close));
255
+ }
256
+ const address = server.address();
257
+ const url = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : port}`;
258
+ return { result: { title: 'Mock server running', lines: [url, `${mock.count} operations`], data: { url, operations: mock.count } }, close };
259
+ }
260
+ export function watchSpec(file, run, onResult, signal) {
261
+ if (/^https?:\/\//i.test(file))
262
+ throw new Error('Watch mode requires a local specification');
263
+ const absolute = path.resolve(file);
264
+ let running = false;
265
+ let pending = false;
266
+ const update = async () => {
267
+ pending = true;
268
+ if (running)
269
+ return;
270
+ running = true;
271
+ try {
272
+ while (pending && !signal?.aborted) {
273
+ pending = false;
274
+ try {
275
+ onResult(await run());
276
+ }
277
+ catch (error) {
278
+ onResult({ title: 'Regeneration failed', lines: [String(error)], exitCode: 1 });
279
+ }
280
+ }
281
+ }
282
+ finally {
283
+ running = false;
284
+ }
285
+ };
286
+ const close = () => unwatchFile(absolute, update);
287
+ if (!signal?.aborted) {
288
+ watchFile(absolute, { interval: 400 }, update);
289
+ signal?.addEventListener('abort', close, { once: true });
290
+ }
291
+ return close;
292
+ }
@@ -0,0 +1,40 @@
1
+ import type { ZodRawShape } from 'zod';
2
+ import type { FileInfo, TaskResult } from './types.js';
3
+ import { theme } from '../theme.js';
4
+ export interface PluginContext {
5
+ root: string;
6
+ }
7
+ export interface PluginCommand {
8
+ name: string;
9
+ description: string;
10
+ run: (context: PluginContext, args: string[]) => Promise<TaskResult>;
11
+ }
12
+ export interface Plugin {
13
+ name: string;
14
+ scanners?: Array<(context: PluginContext, file: Readonly<FileInfo>) => Promise<Partial<Pick<FileInfo, 'role'>> | undefined>>;
15
+ generators?: PluginCommand[];
16
+ commands?: PluginCommand[];
17
+ mcpTools?: Array<{
18
+ name: string;
19
+ description: string;
20
+ input: ZodRawShape;
21
+ run: (context: PluginContext, args: Record<string, unknown>) => Promise<unknown>;
22
+ }>;
23
+ }
24
+ export interface BatiConfig {
25
+ theme: typeof theme & {
26
+ gradient: string[];
27
+ };
28
+ ignore: string[];
29
+ outputs: Record<string, string>;
30
+ plugins: Plugin[];
31
+ }
32
+ export declare const defineConfig: <T extends {
33
+ theme?: Partial<BatiConfig["theme"]>;
34
+ ignore?: string[];
35
+ outputs?: Record<string, string>;
36
+ plugins?: Plugin[];
37
+ }>(config: T) => T;
38
+ export declare function loadConfig(dir?: string): Promise<BatiConfig>;
39
+ export declare function configuredOutput(root: string, config: BatiConfig, key: string, fallback: string, explicit?: string): string;
40
+ export declare const pluginCommands: (config: BatiConfig) => PluginCommand[];
@@ -0,0 +1,53 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { gradient, theme } from '../theme.js';
4
+ export const defineConfig = (config) => config;
5
+ export async function loadConfig(dir = '.') {
6
+ const root = path.resolve(dir);
7
+ const file = path.join(root, 'bati.config.ts');
8
+ const defaults = { theme: { ...theme, gradient: [...gradient] }, ignore: [], outputs: {}, plugins: [] };
9
+ if (process.env.BATI_CONFIG_DISABLED === '1')
10
+ return defaults;
11
+ try {
12
+ await stat(file);
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'ENOENT')
16
+ return defaults;
17
+ throw error;
18
+ }
19
+ const [{ createJiti }, { z }] = await Promise.all([import('jiti'), import('zod')]);
20
+ const callable = z.custom((value) => typeof value === 'function', 'Expected a function');
21
+ const name = z.string().regex(/^[a-z][a-z0-9_-]*$/);
22
+ const command = z.object({ name, description: z.string().min(1), run: callable }).strict();
23
+ const plugin = z.object({
24
+ name,
25
+ scanners: z.array(callable).optional(),
26
+ generators: z.array(command).optional(),
27
+ commands: z.array(command).optional(),
28
+ mcpTools: z.array(command.extend({ input: z.record(z.custom((value) => value instanceof z.ZodType)) })).optional()
29
+ }).strict();
30
+ const color = z.string().regex(/^#[0-9a-f]{6}$/i);
31
+ const colors = Object.fromEntries(Object.keys(theme).map((key) => [key, color.optional()]));
32
+ const schema = z.object({
33
+ theme: z.object({ ...colors, gradient: z.array(color).min(2).optional() }).strict().optional(),
34
+ ignore: z.array(z.string().min(1)).optional(),
35
+ outputs: z.record(z.string().min(1)).optional(),
36
+ plugins: z.array(plugin).optional()
37
+ }).strict();
38
+ const config = schema.parse(await createJiti(import.meta.url, { moduleCache: false, fsCache: false }).import(file, { default: true }));
39
+ const plugins = (config.plugins ?? []);
40
+ for (const names of [
41
+ plugins.map((entry) => entry.name),
42
+ plugins.flatMap((entry) => [...(entry.commands ?? []), ...(entry.generators ?? [])].map((item) => item.name)),
43
+ plugins.flatMap((entry) => (entry.mcpTools ?? []).map((item) => item.name))
44
+ ]) {
45
+ if (new Set(names).size !== names.length)
46
+ throw new Error('Duplicate plugin registration in bati.config.ts');
47
+ }
48
+ return { ...defaults, ...config, theme: { ...defaults.theme, ...config.theme }, plugins };
49
+ }
50
+ export function configuredOutput(root, config, key, fallback, explicit) {
51
+ return explicit ? path.resolve(explicit) : path.resolve(root, config.outputs[key] ?? fallback);
52
+ }
53
+ export const pluginCommands = (config) => config.plugins.flatMap((plugin) => [...(plugin.commands ?? []), ...(plugin.generators ?? [])]);
@@ -0,0 +1,37 @@
1
+ import type { DependencyGraph } from './deps.js';
2
+ import type { TaskResult } from './types.js';
3
+ export interface SearchEntry {
4
+ kind: 'file' | 'class' | 'route' | 'endpoint';
5
+ label: string;
6
+ file: string;
7
+ detail?: string;
8
+ }
9
+ export declare function hotspots(graph: DependencyGraph, churn: Map<string, number>): {
10
+ file: string;
11
+ complexity: number;
12
+ churn: number;
13
+ score: number;
14
+ }[];
15
+ export declare function fuzzyScore(query: string, value: string): number;
16
+ export declare function fuzzyFind<T>(query: string, entries: T[], label: (entry: T) => string, limit?: number): T[];
17
+ export declare function inspectProject(dir: string): Promise<{
18
+ root: string;
19
+ files: number;
20
+ roles: [string, number][];
21
+ classes: number;
22
+ cycles: number;
23
+ routes: number;
24
+ endpoints: number;
25
+ hotspots: {
26
+ file: string;
27
+ complexity: number;
28
+ churn: number;
29
+ score: number;
30
+ }[];
31
+ entries: SearchEntry[];
32
+ }>;
33
+ export declare function projectDashboard(dir: string): Promise<TaskResult>;
34
+ export declare function projectSearch(query: string, dir: string): Promise<TaskResult>;
35
+ export declare const recentStorage: () => string;
36
+ export declare function recentProjects(file?: string): Promise<string[]>;
37
+ export declare function rememberProject(dir: string, file?: string): Promise<string[]>;
@@ -0,0 +1,95 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { gitChurn, listFiles, writeOutput } from './files.js';
5
+ export function hotspots(graph, churn) {
6
+ return graph.files.map((file) => ({ file: file.path, complexity: file.complexity, churn: churn.get(file.path) ?? 0,
7
+ score: file.complexity * (churn.get(file.path) ?? 0) }))
8
+ .filter((file) => file.score).sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
9
+ }
10
+ export function fuzzyScore(query, value) {
11
+ const pattern = query.trim().toLowerCase();
12
+ const text = value.toLowerCase();
13
+ if (!pattern)
14
+ return 0;
15
+ const direct = text.indexOf(pattern);
16
+ if (direct >= 0)
17
+ return 1000 - Math.min(800, direct) - Math.min(80, text.length - pattern.length);
18
+ let position = 0;
19
+ let score = 0;
20
+ for (const character of pattern) {
21
+ const found = text.indexOf(character, position);
22
+ if (found < 0)
23
+ return -1;
24
+ score += found === position ? 10 : 4;
25
+ if (found === 0 || /[\s/_:.\-]/.test(text[found - 1]))
26
+ score += 12;
27
+ position = found + 1;
28
+ }
29
+ return score;
30
+ }
31
+ export function fuzzyFind(query, entries, label, limit = 100) {
32
+ return entries.map((entry, index) => ({ entry, index, score: fuzzyScore(query, label(entry)) }))
33
+ .filter(({ score }) => score >= 0).sort((a, b) => b.score - a.score || a.index - b.index)
34
+ .slice(0, limit).map(({ entry }) => entry);
35
+ }
36
+ export async function inspectProject(dir) {
37
+ const root = path.resolve(dir);
38
+ const [{ scanProject, roleStats }, { analyzeDeps }, { collectRoutes }, { operationsOf }, { loadSpec }] = await Promise.all([
39
+ import('./scan.js'), import('./deps.js'), import('./routes.js'), import('./api.js'), import('./openapi.js')
40
+ ]);
41
+ const [model, graph, routes, files, churn] = await Promise.all([
42
+ scanProject(root), analyzeDeps(root), collectRoutes(root), listFiles(root), gitChurn(root)
43
+ ]);
44
+ const documents = files.filter((file) => /(?:^|\/)[^/]*(?:openapi|swagger)[^/]*\.(?:json|ya?ml)$/i.test(file));
45
+ const endpoints = (await Promise.all(documents.map(async (file) => {
46
+ try {
47
+ return [...operationsOf(await loadSpec(path.join(root, file))).keys()].map((label) => ({ kind: 'endpoint', label, file }));
48
+ }
49
+ catch {
50
+ return [];
51
+ }
52
+ }))).flat();
53
+ const roles = roleStats(model);
54
+ const entries = [
55
+ ...model.classes.map((item) => ({ kind: 'class', label: item.name, file: item.file,
56
+ detail: [...item.props.map((prop) => prop.name), ...item.methods.map((method) => method.name + '()')].join(' · ') })),
57
+ ...routes.map((item) => ({ kind: 'route', label: `${item.method} ${item.path}`, file: item.controllerFile ?? item.file,
58
+ detail: [item.framework, item.controller, ...item.middleware].filter(Boolean).join(' · ') })),
59
+ ...endpoints,
60
+ ...files.map((file) => ({ kind: 'file', label: file, file }))
61
+ ];
62
+ return { root, files: files.length, roles, classes: model.classes.length, cycles: graph.cycles.length, routes: routes.length,
63
+ endpoints: endpoints.length, hotspots: hotspots(graph, churn), entries };
64
+ }
65
+ export async function projectDashboard(dir) {
66
+ const { entries, ...data } = await inspectProject(dir);
67
+ return { title: 'Project dashboard', lines: [`${data.files} files · ${data.classes} classes · ${data.cycles} circular groups · ${data.routes} routes`,
68
+ ...data.roles.map(([role, count]) => `${role} ${count}`), ...data.hotspots.slice(0, 5).map((file) => `${file.score} ${file.file}`)], data };
69
+ }
70
+ export async function projectSearch(query, dir) {
71
+ const { entries } = await inspectProject(dir);
72
+ const matches = fuzzyFind(query, entries, (entry) => `${entry.kind} ${entry.label} ${entry.file}`);
73
+ return { title: 'Project search', lines: matches.map((entry) => `${entry.kind.padEnd(8)} ${entry.label} · ${entry.file}`), data: matches };
74
+ }
75
+ export const recentStorage = () => path.resolve(process.env.XDG_STATE_HOME || path.join(homedir(), '.local', 'state'), 'bati', 'projects.json');
76
+ export async function recentProjects(file = recentStorage()) {
77
+ try {
78
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
79
+ if (Array.isArray(parsed))
80
+ return [...new Set(parsed.filter((value) => typeof value === 'string' && path.isAbsolute(value)))].slice(0, 15);
81
+ }
82
+ catch (error) {
83
+ if (error.code !== 'ENOENT' && !(error instanceof SyntaxError))
84
+ throw error;
85
+ }
86
+ return [];
87
+ }
88
+ export async function rememberProject(dir, file = recentStorage()) {
89
+ const absolute = path.resolve(dir);
90
+ if (!(await stat(absolute)).isDirectory())
91
+ throw new Error(`Not a project directory: ${absolute}`);
92
+ const projects = [absolute, ...(await recentProjects(file)).filter((item) => item !== absolute)].slice(0, 15);
93
+ await writeOutput(file, JSON.stringify(projects, null, 2) + '\n');
94
+ return projects;
95
+ }
@@ -0,0 +1,31 @@
1
+ import type { TaskResult } from './types.js';
2
+ export interface Column {
3
+ name: string;
4
+ type: string;
5
+ nullable: boolean;
6
+ primary: boolean;
7
+ unique: boolean;
8
+ default?: string;
9
+ }
10
+ export interface ForeignKey {
11
+ columns: string[];
12
+ table: string;
13
+ references: string[];
14
+ }
15
+ export interface Table {
16
+ name: string;
17
+ file: string;
18
+ source: 'laravel' | 'prisma' | 'drizzle' | 'sql';
19
+ columns: Column[];
20
+ foreignKeys: ForeignKey[];
21
+ }
22
+ export declare function collectSchema(dir: string): Promise<{
23
+ root: string;
24
+ tables: Table[];
25
+ }>;
26
+ export declare function schemaText(tables: Table[], format: string): string;
27
+ export declare function db(options: {
28
+ dir: string;
29
+ format?: string;
30
+ out?: string;
31
+ }): Promise<TaskResult>;