@fabersep/atlas 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/CHANGELOG.md +30 -0
- package/LICENSE +202 -0
- package/README.md +139 -2
- package/dist/packs/csharp/calls.d.ts +4 -0
- package/dist/packs/csharp/calls.js +167 -0
- package/dist/packs/csharp/declarations.d.ts +4 -0
- package/dist/packs/csharp/declarations.js +142 -0
- package/dist/packs/csharp/pack.d.ts +2 -0
- package/dist/packs/csharp/pack.js +39 -0
- package/dist/packs/csharp/resolve.d.ts +2 -0
- package/dist/packs/csharp/resolve.js +35 -0
- package/dist/packs/csharp/signals.d.ts +7 -0
- package/dist/packs/csharp/signals.js +143 -0
- package/dist/packs/dart/calls.d.ts +4 -0
- package/dist/packs/dart/calls.js +130 -0
- package/dist/packs/dart/declarations.d.ts +11 -0
- package/dist/packs/dart/declarations.js +79 -0
- package/dist/packs/dart/members.d.ts +4 -0
- package/dist/packs/dart/members.js +62 -0
- package/dist/packs/dart/pack.d.ts +2 -0
- package/dist/packs/dart/pack.js +37 -0
- package/dist/packs/dart/resolve.d.ts +2 -0
- package/dist/packs/dart/resolve.js +32 -0
- package/dist/packs/index.d.ts +3 -0
- package/dist/packs/index.js +8 -0
- package/dist/packs/json/pack.d.ts +2 -0
- package/dist/packs/json/pack.js +27 -0
- package/dist/packs/msbuild/pack.d.ts +2 -0
- package/dist/packs/msbuild/pack.js +75 -0
- package/dist/packs/msbuild/xml.d.ts +16 -0
- package/dist/packs/msbuild/xml.js +123 -0
- package/dist/packs/typescript/calls.d.ts +4 -0
- package/dist/packs/typescript/calls.js +201 -0
- package/dist/packs/typescript/declarations.d.ts +9 -0
- package/dist/packs/typescript/declarations.js +74 -0
- package/dist/packs/typescript/members.d.ts +4 -0
- package/dist/packs/typescript/members.js +92 -0
- package/dist/packs/typescript/pack.d.ts +2 -0
- package/dist/packs/typescript/pack.js +53 -0
- package/dist/packs/typescript/resolve.d.ts +2 -0
- package/dist/packs/typescript/resolve.js +68 -0
- package/dist/packs/typescript/signals.d.ts +7 -0
- package/dist/packs/typescript/signals.js +186 -0
- package/dist/packs/yaml/pack.d.ts +2 -0
- package/dist/packs/yaml/pack.js +35 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +371 -0
- package/dist/src/graph/build.d.ts +17 -0
- package/dist/src/graph/build.js +41 -0
- package/dist/src/graph/metrics.d.ts +12 -0
- package/dist/src/graph/metrics.js +75 -0
- package/dist/src/graph/topology.d.ts +5 -0
- package/dist/src/graph/topology.js +54 -0
- package/dist/src/health/compare.d.ts +2 -0
- package/dist/src/health/compare.js +38 -0
- package/dist/src/health/duplicates.d.ts +11 -0
- package/dist/src/health/duplicates.js +66 -0
- package/dist/src/health/health.d.ts +12 -0
- package/dist/src/health/health.js +94 -0
- package/dist/src/health/types.d.ts +101 -0
- package/dist/src/health/types.js +5 -0
- package/dist/src/index.d.ts +23 -0
- package/dist/src/index.js +20 -0
- package/dist/src/init/init.d.ts +73 -0
- package/dist/src/init/init.js +305 -0
- package/dist/src/init/scout.d.ts +45 -0
- package/dist/src/init/scout.js +208 -0
- package/dist/src/jsonc.d.ts +5 -0
- package/dist/src/jsonc.js +34 -0
- package/dist/src/mcp/server.d.ts +266 -0
- package/dist/src/mcp/server.js +414 -0
- package/dist/src/metrics/doctor.d.ts +15 -0
- package/dist/src/metrics/doctor.js +125 -0
- package/dist/src/metrics/log.d.ts +43 -0
- package/dist/src/metrics/log.js +101 -0
- package/dist/src/metrics/stats.d.ts +43 -0
- package/dist/src/metrics/stats.js +172 -0
- package/dist/src/model.d.ts +178 -0
- package/dist/src/model.js +2 -0
- package/dist/src/outputs.d.ts +16 -0
- package/dist/src/outputs.js +48 -0
- package/dist/src/packs/calls.d.ts +9 -0
- package/dist/src/packs/calls.js +119 -0
- package/dist/src/packs/dataShape.d.ts +6 -0
- package/dist/src/packs/dataShape.js +54 -0
- package/dist/src/packs/pack.d.ts +51 -0
- package/dist/src/packs/pack.js +3 -0
- package/dist/src/packs/packFiles.d.ts +5 -0
- package/dist/src/packs/packFiles.js +12 -0
- package/dist/src/packs/symbols.d.ts +39 -0
- package/dist/src/packs/symbols.js +98 -0
- package/dist/src/packs/treeSitter.d.ts +8 -0
- package/dist/src/packs/treeSitter.js +107 -0
- package/dist/src/queries/flow.d.ts +42 -0
- package/dist/src/queries/flow.js +391 -0
- package/dist/src/queries/map.d.ts +28 -0
- package/dist/src/queries/map.js +102 -0
- package/dist/src/queries/neighborhood.d.ts +35 -0
- package/dist/src/queries/neighborhood.js +60 -0
- package/dist/src/scan/audit.d.ts +2 -0
- package/dist/src/scan/audit.js +41 -0
- package/dist/src/scan/records.d.ts +12 -0
- package/dist/src/scan/records.js +42 -0
- package/dist/src/scan/resolveImports.d.ts +3 -0
- package/dist/src/scan/resolveImports.js +47 -0
- package/dist/src/scan/roles.d.ts +5 -0
- package/dist/src/scan/roles.js +87 -0
- package/dist/src/scan/scan.d.ts +24 -0
- package/dist/src/scan/scan.js +72 -0
- package/dist/src/text/briefs.d.ts +13 -0
- package/dist/src/text/briefs.js +43 -0
- package/dist/src/text/collapse.d.ts +10 -0
- package/dist/src/text/collapse.js +58 -0
- package/dist/src/text/declarations.d.ts +12 -0
- package/dist/src/text/declarations.js +120 -0
- package/dist/src/text/structure.d.ts +2 -0
- package/dist/src/text/structure.js +15 -0
- package/dist/src/text/tree.d.ts +20 -0
- package/dist/src/text/tree.js +49 -0
- package/dist/src/tokens.d.ts +4 -0
- package/dist/src/tokens.js +9 -0
- package/dist/src/version.d.ts +10 -0
- package/dist/src/version.js +11 -0
- package/dist/src/walk/ignoreRules.d.ts +17 -0
- package/dist/src/walk/ignoreRules.js +72 -0
- package/dist/src/walk/walk.d.ts +11 -0
- package/dist/src/walk/walk.js +29 -0
- package/grammars/LICENSE-tree-sitter-dart +20 -0
- package/grammars/README.md +11 -0
- package/grammars/tree-sitter-dart.wasm +0 -0
- package/package.json +68 -4
- package/packs/csharp/README.md +9 -0
- package/packs/csharp/imports.scm +3 -0
- package/packs/csharp/symbols.scm +17 -0
- package/packs/dart/imports.scm +5 -0
- package/packs/dart/symbols.scm +13 -0
- package/packs/msbuild/README.md +11 -0
- package/packs/typescript/exports.scm +16 -0
- package/packs/typescript/imports.scm +9 -0
- package/packs/typescript/symbols.scm +19 -0
- package/schema/ast_code_map.schema.json +144 -0
- package/schema/schema-lock.json +7 -0
- package/schema/topology.schema.json +87 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { CodeMap, Topology } from './model.js';
|
|
2
|
+
/** The four output files of a scan, written to and read from one output folder. */
|
|
3
|
+
/** Outputs made by another major schema version are never read or converted (CIN-15). */
|
|
4
|
+
export declare class OutputVersionError extends Error {
|
|
5
|
+
constructor(file: string, found: unknown);
|
|
6
|
+
}
|
|
7
|
+
export declare class OutputMissingError extends Error {
|
|
8
|
+
constructor(file: string);
|
|
9
|
+
}
|
|
10
|
+
/** The index folder ignores itself, so a scan never leaves untracked files in the repository's git status. */
|
|
11
|
+
export declare const SELF_IGNORE = "# Written by faber-atlas: this folder is a generated index.\n*\n";
|
|
12
|
+
export declare function writeOutputs(out: string, map: CodeMap, topology: Topology): void;
|
|
13
|
+
export declare const readCodeMap: (out: string) => CodeMap;
|
|
14
|
+
export declare const readTopology: (out: string) => Topology;
|
|
15
|
+
/** The previous code map for an incremental scan; none when there is no file or it was made by another version. */
|
|
16
|
+
export declare function previousCodeMap(out: string, generatorVersion: string): CodeMap | undefined;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { renderMap } from './queries/map.js';
|
|
4
|
+
import { renderStructure } from './text/structure.js';
|
|
5
|
+
import { OUTPUT_FILES, SCHEMA_VERSION } from './version.js';
|
|
6
|
+
/** The four output files of a scan, written to and read from one output folder. */
|
|
7
|
+
/** Outputs made by another major schema version are never read or converted (CIN-15). */
|
|
8
|
+
export class OutputVersionError extends Error {
|
|
9
|
+
constructor(file, found) {
|
|
10
|
+
super(`${file} was made with schema version ${String(found)}; this version reads ${SCHEMA_VERSION}. Scan the folder again.`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class OutputMissingError extends Error {
|
|
14
|
+
constructor(file) {
|
|
15
|
+
super(`${file} does not exist. Run "faber-atlas scan" first.`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** The index folder ignores itself, so a scan never leaves untracked files in the repository's git status. */
|
|
19
|
+
export const SELF_IGNORE = '# Written by faber-atlas: this folder is a generated index.\n*\n';
|
|
20
|
+
export function writeOutputs(out, map, topology) {
|
|
21
|
+
fs.mkdirSync(out, { recursive: true });
|
|
22
|
+
const ignoreFile = path.join(out, '.gitignore');
|
|
23
|
+
if (!fs.existsSync(ignoreFile))
|
|
24
|
+
fs.writeFileSync(ignoreFile, SELF_IGNORE);
|
|
25
|
+
fs.writeFileSync(path.join(out, OUTPUT_FILES.codeMap), `${JSON.stringify(map, null, 2)}\n`);
|
|
26
|
+
fs.writeFileSync(path.join(out, OUTPUT_FILES.topology), `${JSON.stringify(topology, null, 2)}\n`);
|
|
27
|
+
fs.writeFileSync(path.join(out, OUTPUT_FILES.topologyText), `${renderMap(map, { full: true })}\n`);
|
|
28
|
+
fs.writeFileSync(path.join(out, OUTPUT_FILES.structure), renderStructure(map));
|
|
29
|
+
}
|
|
30
|
+
function readJson(out, name) {
|
|
31
|
+
const file = path.join(out, name);
|
|
32
|
+
if (!fs.existsSync(file))
|
|
33
|
+
throw new OutputMissingError(file);
|
|
34
|
+
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
35
|
+
if (doc.schemaVersion !== SCHEMA_VERSION)
|
|
36
|
+
throw new OutputVersionError(file, doc.schemaVersion);
|
|
37
|
+
return doc;
|
|
38
|
+
}
|
|
39
|
+
export const readCodeMap = (out) => readJson(out, OUTPUT_FILES.codeMap);
|
|
40
|
+
export const readTopology = (out) => readJson(out, OUTPUT_FILES.topology);
|
|
41
|
+
/** The previous code map for an incremental scan; none when there is no file or it was made by another version. */
|
|
42
|
+
export function previousCodeMap(out, generatorVersion) {
|
|
43
|
+
const file = path.join(out, OUTPUT_FILES.codeMap);
|
|
44
|
+
if (!fs.existsSync(file))
|
|
45
|
+
return undefined;
|
|
46
|
+
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
47
|
+
return doc.schemaVersion === SCHEMA_VERSION && doc.generatorVersion === generatorVersion ? doc : undefined;
|
|
48
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CallSite, ExternalBoundary, SymbolNode } from '../model.js';
|
|
2
|
+
/** Extracts the simple type name from an annotation like `Readonly<IOrderRepository> | null` -> `IOrderRepository`. */
|
|
3
|
+
export declare function cleanTypeName(raw: string | undefined): string | undefined;
|
|
4
|
+
export declare function isNoiseCall(receiver: string | undefined, receiverType: string | undefined, method: string, isThisMember: boolean): boolean;
|
|
5
|
+
export declare function detectBoundary(kind: CallSite['kind'], receiver: string | undefined, receiverType: string | undefined, method: string): ExternalBoundary | undefined;
|
|
6
|
+
/** Deduplicates calls per callable symbol (same kind + callee + targetKey), preserving first line order. */
|
|
7
|
+
export declare function dedupeCalls(calls: CallSite[]): CallSite[];
|
|
8
|
+
/** Builds a field-name -> simple-type map for a class/container's declared fields. */
|
|
9
|
+
export declare function fieldTypeMap(container: SymbolNode): Map<string, string>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Shared helpers for static call & wiring extraction across TypeScript, C#, and Dart packs. */
|
|
2
|
+
const NOISE_RECEIVERS = new Set([
|
|
3
|
+
'console', 'Math', 'JSON', 'Object', 'Array', 'Promise', 'Date', 'String', 'Number', 'Boolean',
|
|
4
|
+
'Map', 'Set', 'WeakMap', 'WeakSet', 'RegExp', 'Error', 'Reflect', 'Symbol', 'Intl', 'Buffer',
|
|
5
|
+
'process', 'global', 'globalThis', 'window', 'document', 'URL', 'URLSearchParams', 'BigInt',
|
|
6
|
+
'logger', '_logger', 'log', '_log', 'Logger', 'Log',
|
|
7
|
+
'Console', 'Convert', 'Guid', 'DateTime', 'DateTimeOffset', 'TimeSpan', 'TimeOnly', 'DateOnly',
|
|
8
|
+
'Enumerable', 'Task', 'Parallel', 'Interlocked', 'StringBuilder', 'Encoding', 'Environment',
|
|
9
|
+
'Debug', 'Trace', 'Assert', 'Regex', 'CultureInfo', 'Encoding', 'JsonSerializer', 'JsonConvert',
|
|
10
|
+
'string', 'int', 'long', 'double', 'decimal', 'bool', 'char', 'object',
|
|
11
|
+
'Future', 'Stream', 'List', 'Iterable', 'Duration', 'Uri', 'RegExp', 'DateTime',
|
|
12
|
+
]);
|
|
13
|
+
const NOISE_BARE_FUNCTIONS = new Set([
|
|
14
|
+
'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'Number', 'String', 'Boolean', 'Array', 'Object',
|
|
15
|
+
'Symbol', 'BigInt', 'Date', 'RegExp', 'Error', 'Set', 'Map', 'WeakMap', 'WeakSet',
|
|
16
|
+
'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'queueMicrotask', 'structuredClone',
|
|
17
|
+
'encodeURIComponent', 'decodeURIComponent', 'encodeURI', 'decodeURI', 'atob', 'btoa',
|
|
18
|
+
'require', 'super', 'nameof', 'typeof', 'sizeof', 'print', 'debugPrint', 'identical',
|
|
19
|
+
'expect', 'describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll', 'vi', 'jest',
|
|
20
|
+
]);
|
|
21
|
+
/** Common collection/primitive methods that are noise when called on an untyped local variable (not `this.dep` or a known class). */
|
|
22
|
+
const COLLECTION_METHODS = new Set([
|
|
23
|
+
'map', 'flatMap', 'filter', 'reduce', 'reduceRight', 'forEach', 'some', 'every', 'find', 'findIndex',
|
|
24
|
+
'includes', 'indexOf', 'lastIndexOf', 'push', 'pop', 'shift', 'unshift', 'slice', 'splice', 'concat',
|
|
25
|
+
'join', 'sort', 'reverse', 'flat', 'fill', 'at', 'entries', 'keys', 'values',
|
|
26
|
+
'trim', 'trimStart', 'trimEnd', 'split', 'replace', 'replaceAll', 'match', 'matchAll', 'search',
|
|
27
|
+
'startsWith', 'endsWith', 'substring', 'substr', 'toLowerCase', 'toUpperCase', 'padStart', 'padEnd',
|
|
28
|
+
'toString', 'valueOf', 'toFixed', 'toISOString', 'toJSON', 'getTime', 'hasOwnProperty',
|
|
29
|
+
'then', 'catch', 'finally', 'bind', 'call', 'apply',
|
|
30
|
+
'Select', 'Where', 'ToList', 'ToArray', 'ToDictionary', 'First', 'FirstOrDefault', 'Single', 'SingleOrDefault',
|
|
31
|
+
'Any', 'All', 'Count', 'OrderBy', 'OrderByDescending', 'GroupBy', 'SelectMany', 'Distinct', 'Skip', 'Take',
|
|
32
|
+
'ToString', 'Equals', 'GetHashCode', 'CompareTo', 'Trim', 'Split', 'Replace', 'Contains', 'StartsWith', 'EndsWith',
|
|
33
|
+
'ToLower', 'ToUpper', 'IsNullOrEmpty', 'IsNullOrWhiteSpace', 'Add', 'AddRange', 'Remove', 'Clear', 'ContainsKey',
|
|
34
|
+
'TryGetValue', 'ConfigureAwait', 'GetAwaiter', 'GetResult',
|
|
35
|
+
'where', 'toList', 'toSet', 'fold', 'expand', 'any', 'every', 'firstWhere', 'singleWhere', 'contains',
|
|
36
|
+
'isEmpty', 'isNotEmpty', 'addAll', 'putIfAbsent',
|
|
37
|
+
]);
|
|
38
|
+
/** Extracts the simple type name from an annotation like `Readonly<IOrderRepository> | null` -> `IOrderRepository`. */
|
|
39
|
+
export function cleanTypeName(raw) {
|
|
40
|
+
if (!raw)
|
|
41
|
+
return undefined;
|
|
42
|
+
const trimmed = raw
|
|
43
|
+
.replace(/^(readonly|final|const|late)\s+/g, '')
|
|
44
|
+
.replace(/\s*\|\s*(undefined|null)/g, '')
|
|
45
|
+
.replace(/\?$/, '')
|
|
46
|
+
.trim();
|
|
47
|
+
const base = trimmed.replace(/<.*$/s, '').split('.').pop()?.trim();
|
|
48
|
+
if (!base || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(base))
|
|
49
|
+
return undefined;
|
|
50
|
+
if (/^(string|number|boolean|void|any|unknown|never|object|int|long|double|decimal|bool|var|dynamic|Function|Promise|Task|Future|List|Array|Set|Map|Record)$/.test(base)) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
return base;
|
|
54
|
+
}
|
|
55
|
+
export function isNoiseCall(receiver, receiverType, method, isThisMember) {
|
|
56
|
+
if (!receiver)
|
|
57
|
+
return NOISE_BARE_FUNCTIONS.has(method);
|
|
58
|
+
if (NOISE_RECEIVERS.has(receiver))
|
|
59
|
+
return true;
|
|
60
|
+
if (receiverType && NOISE_RECEIVERS.has(receiverType))
|
|
61
|
+
return true;
|
|
62
|
+
if (!isThisMember && !receiverType && COLLECTION_METHODS.has(method))
|
|
63
|
+
return true;
|
|
64
|
+
if (receiver === 'this' && COLLECTION_METHODS.has(method))
|
|
65
|
+
return false;
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
const DB_RX = /(db|database|prisma|kysely|knex|sequelize|mongoose|entityManager|dataSource|queryRunner|dbContext|sqlConnection|redis)$/i;
|
|
69
|
+
const DB_METHODS = new Set(['query', 'execute', 'selectFrom', 'insertInto', 'updateTable', 'deleteFrom', 'saveChanges', 'saveChangesAsync', 'transaction']);
|
|
70
|
+
const HTTP_RX = /(^|[\._])(http|axios|fetch|httpClient|got|superagent|undici|restClient|apiClient)$/i;
|
|
71
|
+
const QUEUE_RX = /(queue|bull|rabbit|kafka|sqs|serviceBus|jobRepository|jobs)$/i;
|
|
72
|
+
const FS_RX = /^(fs|fsp|fsPromises|File|Directory|FileSystem|storageCore)$/i;
|
|
73
|
+
const FS_METHODS = new Set([
|
|
74
|
+
'readFile', 'writeFile', 'appendFile', 'mkdir', 'rm', 'rmdir', 'unlink', 'rename', 'copyFile', 'stat', 'lstat',
|
|
75
|
+
'readdir', 'access', 'createReadStream', 'createWriteStream',
|
|
76
|
+
'ReadAllText', 'ReadAllTextAsync', 'WriteAllText', 'WriteAllTextAsync', 'ReadAllBytes', 'WriteAllBytes',
|
|
77
|
+
'OpenRead', 'OpenWrite', 'CreateDirectory', 'Delete', 'Move', 'Copy',
|
|
78
|
+
]);
|
|
79
|
+
export function detectBoundary(kind, receiver, receiverType, method) {
|
|
80
|
+
if (kind === 'queues')
|
|
81
|
+
return 'queue';
|
|
82
|
+
const target = receiverType ?? receiver ?? '';
|
|
83
|
+
if (!receiver && method === 'fetch')
|
|
84
|
+
return 'http';
|
|
85
|
+
if (FS_RX.test(target) || (FS_RX.test(receiver ?? '') && FS_METHODS.has(method)))
|
|
86
|
+
return 'fs';
|
|
87
|
+
if (HTTP_RX.test(target))
|
|
88
|
+
return 'http';
|
|
89
|
+
if (QUEUE_RX.test(target))
|
|
90
|
+
return 'queue';
|
|
91
|
+
if (DB_METHODS.has(method) || (DB_RX.test(target) && !/event|job/i.test(target)))
|
|
92
|
+
return 'db';
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
/** Deduplicates calls per callable symbol (same kind + callee + targetKey), preserving first line order. */
|
|
96
|
+
export function dedupeCalls(calls) {
|
|
97
|
+
const seen = new Set();
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const c of calls) {
|
|
100
|
+
const key = `${c.kind}|${c.callee}|${c.targetKey ?? ''}`;
|
|
101
|
+
if (seen.has(key))
|
|
102
|
+
continue;
|
|
103
|
+
seen.add(key);
|
|
104
|
+
out.push(c);
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/** Builds a field-name -> simple-type map for a class/container's declared fields. */
|
|
109
|
+
export function fieldTypeMap(container) {
|
|
110
|
+
const map = new Map();
|
|
111
|
+
for (const m of container.members ?? []) {
|
|
112
|
+
if (m.kind === 'field' || m.kind === 'getter') {
|
|
113
|
+
const clean = cleanTypeName(m.type);
|
|
114
|
+
if (clean)
|
|
115
|
+
map.set(m.name, clean);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return map;
|
|
119
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of parsed JSON or YAML data, compact enough for a prompt whatever the file's size: types instead of values,
|
|
3
|
+
* one item per array with the item count, and repeated entries folded. A 10,000-line list of records is a few lines.
|
|
4
|
+
*/
|
|
5
|
+
/** The skeleton of a data file: its shape. */
|
|
6
|
+
export declare function dataSkeleton(kind: 'JSON' | 'YAML', parsed: unknown): string;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of parsed JSON or YAML data, compact enough for a prompt whatever the file's size: types instead of values,
|
|
3
|
+
* one item per array with the item count, and repeated entries folded. A 10,000-line list of records is a few lines.
|
|
4
|
+
*/
|
|
5
|
+
const MAX_DEPTH = 5;
|
|
6
|
+
const MAX_KEYS = 25;
|
|
7
|
+
/** An object with at least this many keys whose values all have one shape is a dictionary: `{ [key]: shape }`. */
|
|
8
|
+
const DICTIONARY_KEYS = 8;
|
|
9
|
+
const SAMPLE_KEYS = 3;
|
|
10
|
+
const pad = (depth) => ' '.repeat(depth);
|
|
11
|
+
function shapeOf(value, depth) {
|
|
12
|
+
if (depth > MAX_DEPTH)
|
|
13
|
+
return 'any';
|
|
14
|
+
if (value === null)
|
|
15
|
+
return 'null';
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return arrayShape(value, depth);
|
|
18
|
+
if (typeof value === 'object')
|
|
19
|
+
return objectShape(value, depth);
|
|
20
|
+
return typeof value;
|
|
21
|
+
}
|
|
22
|
+
/** `[string] (3 items)`, or the first item's shape on its own lines when it spans several. */
|
|
23
|
+
function arrayShape(value, depth) {
|
|
24
|
+
if (value.length === 0)
|
|
25
|
+
return '[]';
|
|
26
|
+
const item = shapeOf(value[0], depth + 1);
|
|
27
|
+
const count = value.length > 1 ? ` (${value.length} items)` : '';
|
|
28
|
+
return item.includes('\n') ? `[\n${pad(depth + 1)}${item}\n${pad(depth)}]${count}` : `[${item}]${count}`;
|
|
29
|
+
}
|
|
30
|
+
/** The one shape all values share, when the object has enough keys to be a dictionary rather than a record. */
|
|
31
|
+
function dictionaryShape(values, depth) {
|
|
32
|
+
if (values.length < DICTIONARY_KEYS)
|
|
33
|
+
return undefined;
|
|
34
|
+
const first = shapeOf(values[0], depth + 1);
|
|
35
|
+
return values.every((v) => shapeOf(v, depth + 1) === first) ? first : undefined;
|
|
36
|
+
}
|
|
37
|
+
function objectShape(value, depth) {
|
|
38
|
+
const keys = Object.keys(value);
|
|
39
|
+
if (keys.length === 0)
|
|
40
|
+
return '{}';
|
|
41
|
+
const shared = dictionaryShape(Object.values(value), depth);
|
|
42
|
+
if (shared !== undefined) {
|
|
43
|
+
const sample = keys.slice(0, SAMPLE_KEYS).map((k) => JSON.stringify(k)).join(', ');
|
|
44
|
+
return `{ [key]: ${shared} } (${keys.length} keys: ${sample}, ...)`;
|
|
45
|
+
}
|
|
46
|
+
const lines = keys.slice(0, MAX_KEYS).map((k) => `${pad(depth + 1)}${k}: ${shapeOf(value[k], depth + 1)}`);
|
|
47
|
+
if (keys.length > MAX_KEYS)
|
|
48
|
+
lines.push(`${pad(depth + 1)}... +${keys.length - MAX_KEYS} more fields`);
|
|
49
|
+
return `{\n${lines.join('\n')}\n${pad(depth)}}`;
|
|
50
|
+
}
|
|
51
|
+
/** The skeleton of a data file: its shape. */
|
|
52
|
+
export function dataSkeleton(kind, parsed) {
|
|
53
|
+
return `// ${kind} shape\n${shapeOf(parsed, 0)}`;
|
|
54
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { DeclaredDependency, ImportRef, RoleTag, SymbolNode } from '../model.js';
|
|
2
|
+
/**
|
|
3
|
+
* The language pack contract (feature 20 FR-04). A pack claims files and turns one file's text into declarations,
|
|
4
|
+
* import specifiers and, for a manifest, declared dependencies. Resolving an import to a project file or a package
|
|
5
|
+
* happens after every file is known, so a new file can resolve an import of an unchanged one.
|
|
6
|
+
*/
|
|
7
|
+
export interface LanguagePack {
|
|
8
|
+
/** The pack's id; also the `language` of the files it claims. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** Whether the pack reads this file (a path relative to the scan root). */
|
|
11
|
+
claims(path: string): boolean;
|
|
12
|
+
/** A data format (JSON, YAML) rather than code: code health leaves its files out. */
|
|
13
|
+
data?: boolean;
|
|
14
|
+
parse(input: ParseInput): Promise<ParsedFile>;
|
|
15
|
+
/** Where an import points; packs without imports leave it out. A C# `using` can point at several files (one namespace, many files). */
|
|
16
|
+
resolve?(input: ResolveInput): Resolution | Resolution[];
|
|
17
|
+
}
|
|
18
|
+
export interface ParseInput {
|
|
19
|
+
path: string;
|
|
20
|
+
content: string;
|
|
21
|
+
}
|
|
22
|
+
export interface RawImport {
|
|
23
|
+
specifier: string;
|
|
24
|
+
line: number;
|
|
25
|
+
typeOnly?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface ParsedFile {
|
|
28
|
+
symbols: SymbolNode[];
|
|
29
|
+
imports: RawImport[];
|
|
30
|
+
/** A pack's own skeleton; the core renders one from the symbols when it is absent. */
|
|
31
|
+
skeleton?: string;
|
|
32
|
+
declares?: DeclaredDependency[];
|
|
33
|
+
/** AST-derived role hints from the pack; merged with import/symbol roles after import resolution. */
|
|
34
|
+
roles?: RoleTag[];
|
|
35
|
+
}
|
|
36
|
+
/** What a resolver can see of the project: its scanned files, and their text on demand. */
|
|
37
|
+
export interface ProjectView {
|
|
38
|
+
has(path: string): boolean;
|
|
39
|
+
read(path: string): string | undefined;
|
|
40
|
+
/** Every path of the scan, sorted. */
|
|
41
|
+
paths(): readonly string[];
|
|
42
|
+
}
|
|
43
|
+
export interface ResolveInput {
|
|
44
|
+
from: string;
|
|
45
|
+
raw: RawImport;
|
|
46
|
+
project: ProjectView;
|
|
47
|
+
}
|
|
48
|
+
export type Resolution = Pick<ImportRef, 'kind' | 'target' | 'package'>;
|
|
49
|
+
/** A parse failure the scan records against the file (CIN-04). */
|
|
50
|
+
export declare class ParseError extends Error {
|
|
51
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/**
|
|
5
|
+
* Reads a file of a pack's own folder (a query file). Compiled pack code runs from `dist/packs/<id>/`; its query
|
|
6
|
+
* files stay in `packs/<id>/`.
|
|
7
|
+
*/
|
|
8
|
+
export function readPackFile(moduleUrl, name) {
|
|
9
|
+
const dir = path.dirname(fileURLToPath(moduleUrl));
|
|
10
|
+
const source = dir.replace(`${path.sep}dist${path.sep}packs${path.sep}`, `${path.sep}packs${path.sep}`);
|
|
11
|
+
return fs.readFileSync(path.join(source, name), 'utf8');
|
|
12
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { SymbolKind, SymbolNode } from '../model.js';
|
|
3
|
+
/** Shared helpers for Tree-sitter packs: declaration text, and nesting members into their containers. */
|
|
4
|
+
export declare const CONTAINER_KINDS: Set<SymbolKind>;
|
|
5
|
+
/** Declarations with a body of statements: code health measures their length and nesting. */
|
|
6
|
+
export declare const FUNCTION_KINDS: Set<SymbolKind>;
|
|
7
|
+
/** A declaration with its source range, before nesting. */
|
|
8
|
+
export interface Declared extends Omit<SymbolNode, 'members'> {
|
|
9
|
+
start: number;
|
|
10
|
+
end: number;
|
|
11
|
+
}
|
|
12
|
+
export type SymbolFields = Omit<SymbolNode, 'lineStart' | 'lineEnd' | 'members'>;
|
|
13
|
+
/** A declaration spanning `node` (to `last` when the body is a separate sibling, as in Dart). */
|
|
14
|
+
export declare function declared(node: Node, fields: SymbolFields, last?: Node): Declared;
|
|
15
|
+
/**
|
|
16
|
+
* Nests declarations by their source ranges: a declaration inside a container becomes its member, one inside a
|
|
17
|
+
* function or method is local and left out, any other is top level. Syntax ranges nest exactly, so membership is
|
|
18
|
+
* never guessed from line numbers. A member outside any captured container (a class inside a namespace) is left out.
|
|
19
|
+
* A field declared by a constructor (TypeScript parameter properties) belongs to the constructor's class.
|
|
20
|
+
*/
|
|
21
|
+
export declare function nest(items: Declared[]): SymbolNode[];
|
|
22
|
+
/**
|
|
23
|
+
* The deepest nesting inside `start`..`end` of `root`: how many of the pack's `blocks` (if, loops, switch, try) sit
|
|
24
|
+
* inside each other. An `else if` stays on the level of its `if`; a lambda adds no level, but its statements count.
|
|
25
|
+
*/
|
|
26
|
+
export declare function nestingDepth(root: Node, start: number, end: number, blocks: ReadonlySet<string>): number;
|
|
27
|
+
/** Every function-like declaration with its nesting depth (FR-07), measured in the file's tree. */
|
|
28
|
+
export declare function withNesting(items: Declared[], root: Node, blocks: ReadonlySet<string>): Declared[];
|
|
29
|
+
/**
|
|
30
|
+
* The text of `node` from its first real token (decorators and comments skipped) up to `stop`, on one line,
|
|
31
|
+
* without a trailing `{`, `;`, `=>` or `=`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function header(source: string, node: Node, stop?: Node | null): string;
|
|
34
|
+
/** Splits a list on commas that are not inside brackets: `A<B, C>, D` gives `A<B, C>` and `D`. */
|
|
35
|
+
export declare function splitList(text: string): string[];
|
|
36
|
+
/** The first child of one of the given types. */
|
|
37
|
+
export declare function childOfType(node: Node, ...types: string[]): Node | undefined;
|
|
38
|
+
/** Whether a keyword token (such as `static`) is a direct child. */
|
|
39
|
+
export declare function hasToken(node: Node, token: string): boolean;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { oneLine } from '../tokens.js';
|
|
2
|
+
/** Shared helpers for Tree-sitter packs: declaration text, and nesting members into their containers. */
|
|
3
|
+
export const CONTAINER_KINDS = new Set(['class', 'interface', 'enum', 'mixin', 'extension']);
|
|
4
|
+
const MEMBER_KINDS = new Set(['method', 'constructor', 'field', 'getter', 'setter', 'enumMember']);
|
|
5
|
+
/** Declarations with a body of statements: code health measures their length and nesting. */
|
|
6
|
+
export const FUNCTION_KINDS = new Set(['function', 'method', 'constructor', 'getter', 'setter']);
|
|
7
|
+
/** A declaration spanning `node` (to `last` when the body is a separate sibling, as in Dart). */
|
|
8
|
+
export function declared(node, fields, last = node) {
|
|
9
|
+
return { ...fields, lineStart: node.startPosition.row + 1, lineEnd: last.endPosition.row + 1, start: node.startIndex, end: last.endIndex };
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Nests declarations by their source ranges: a declaration inside a container becomes its member, one inside a
|
|
13
|
+
* function or method is local and left out, any other is top level. Syntax ranges nest exactly, so membership is
|
|
14
|
+
* never guessed from line numbers. A member outside any captured container (a class inside a namespace) is left out.
|
|
15
|
+
* A field declared by a constructor (TypeScript parameter properties) belongs to the constructor's class.
|
|
16
|
+
*/
|
|
17
|
+
export function nest(items) {
|
|
18
|
+
const sorted = [...items].sort((a, b) => a.start - b.start || b.end - a.end);
|
|
19
|
+
const top = [];
|
|
20
|
+
const open = [];
|
|
21
|
+
for (const item of sorted) {
|
|
22
|
+
while (open.length && open[open.length - 1].item.end <= item.start)
|
|
23
|
+
open.pop();
|
|
24
|
+
const declaredByConstructor = item.kind === 'field' && open[open.length - 1]?.item.kind === 'constructor';
|
|
25
|
+
const parent = declaredByConstructor ? open[open.length - 2] : open[open.length - 1];
|
|
26
|
+
const node = toNode(item);
|
|
27
|
+
if (!parent && MEMBER_KINDS.has(item.kind))
|
|
28
|
+
continue;
|
|
29
|
+
if (!parent)
|
|
30
|
+
top.push(node);
|
|
31
|
+
else if (CONTAINER_KINDS.has(parent.item.kind))
|
|
32
|
+
(parent.node.members ??= []).push(node);
|
|
33
|
+
else
|
|
34
|
+
continue;
|
|
35
|
+
open.push({ item, node });
|
|
36
|
+
}
|
|
37
|
+
return top;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The deepest nesting inside `start`..`end` of `root`: how many of the pack's `blocks` (if, loops, switch, try) sit
|
|
41
|
+
* inside each other. An `else if` stays on the level of its `if`; a lambda adds no level, but its statements count.
|
|
42
|
+
*/
|
|
43
|
+
export function nestingDepth(root, start, end, blocks) {
|
|
44
|
+
const walk = (node, level) => node.children.reduce((deepest, child) => {
|
|
45
|
+
if (!child || child.endIndex <= start || child.startIndex >= end)
|
|
46
|
+
return deepest;
|
|
47
|
+
const opens = blocks.has(child.type) && child.startIndex >= start && child.previousSibling?.type !== 'else';
|
|
48
|
+
return Math.max(deepest, walk(child, opens ? level + 1 : level));
|
|
49
|
+
}, level);
|
|
50
|
+
return walk(root, 0);
|
|
51
|
+
}
|
|
52
|
+
/** Every function-like declaration with its nesting depth (FR-07), measured in the file's tree. */
|
|
53
|
+
export function withNesting(items, root, blocks) {
|
|
54
|
+
return items.map((d) => (FUNCTION_KINDS.has(d.kind) ? { ...d, nesting: nestingDepth(root, d.start, d.end, blocks) } : d));
|
|
55
|
+
}
|
|
56
|
+
function toNode(item) {
|
|
57
|
+
const { start, end, ...symbol } = item;
|
|
58
|
+
return CONTAINER_KINDS.has(item.kind) ? { ...symbol, members: [] } : symbol;
|
|
59
|
+
}
|
|
60
|
+
const LEADING = new Set(['decorator', 'annotation', 'comment']);
|
|
61
|
+
/**
|
|
62
|
+
* The text of `node` from its first real token (decorators and comments skipped) up to `stop`, on one line,
|
|
63
|
+
* without a trailing `{`, `;`, `=>` or `=`.
|
|
64
|
+
*/
|
|
65
|
+
export function header(source, node, stop) {
|
|
66
|
+
const first = node.children.find((c) => c && !LEADING.has(c.type)) ?? node;
|
|
67
|
+
const end = stop ? stop.startIndex : node.endIndex;
|
|
68
|
+
return oneLine(source.slice(first.startIndex, end)).replace(/\s*(\{|;|=>|=)$/, '');
|
|
69
|
+
}
|
|
70
|
+
/** Splits a list on commas that are not inside brackets: `A<B, C>, D` gives `A<B, C>` and `D`. */
|
|
71
|
+
export function splitList(text) {
|
|
72
|
+
const parts = [];
|
|
73
|
+
let depth = 0;
|
|
74
|
+
let current = '';
|
|
75
|
+
for (const ch of text) {
|
|
76
|
+
if ('<([{'.includes(ch))
|
|
77
|
+
depth++;
|
|
78
|
+
if ('>)]}'.includes(ch))
|
|
79
|
+
depth--;
|
|
80
|
+
if (ch === ',' && depth === 0) {
|
|
81
|
+
parts.push(current.trim());
|
|
82
|
+
current = '';
|
|
83
|
+
}
|
|
84
|
+
else
|
|
85
|
+
current += ch;
|
|
86
|
+
}
|
|
87
|
+
if (current.trim())
|
|
88
|
+
parts.push(current.trim());
|
|
89
|
+
return parts;
|
|
90
|
+
}
|
|
91
|
+
/** The first child of one of the given types. */
|
|
92
|
+
export function childOfType(node, ...types) {
|
|
93
|
+
return node.children.find((c) => !!c && types.includes(c.type));
|
|
94
|
+
}
|
|
95
|
+
/** Whether a keyword token (such as `static`) is a direct child. */
|
|
96
|
+
export function hasToken(node, token) {
|
|
97
|
+
return node.children.some((c) => c?.type === token);
|
|
98
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Language, Query, type Node } from 'web-tree-sitter';
|
|
2
|
+
/** A query compiled once per grammar and key. */
|
|
3
|
+
export declare function query(language: Language, key: string, source: string): Query;
|
|
4
|
+
/**
|
|
5
|
+
* Parses `content` with a grammar and hands the tree to `use`; the tree's WebAssembly memory is freed afterwards.
|
|
6
|
+
* A syntax error anywhere is a ParseError (the file then has no symbols, CIN-04).
|
|
7
|
+
*/
|
|
8
|
+
export declare function withTree<T>(grammar: string, content: string, use: (root: Node, language: Language) => T): Promise<T>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { Language, Parser, Query } from 'web-tree-sitter';
|
|
5
|
+
import { ParseError } from './pack.js';
|
|
6
|
+
/** Tree-sitter through WebAssembly (decision Q51): one grammar file serves every machine. */
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
let init;
|
|
9
|
+
const parsers = new Map();
|
|
10
|
+
/** Compiled queries per grammar: node ids differ between grammars, so a query never crosses languages. */
|
|
11
|
+
const queries = new WeakMap();
|
|
12
|
+
/**
|
|
13
|
+
* Grammars that `tree-sitter-wasms` ships too old for current code come from the grammar's own package, pinned in
|
|
14
|
+
* package.json (C#: tree-sitter-wasms has 0.20, which predates C# 12; TypeScript and TSX: its 0.20 grammar rejects a
|
|
15
|
+
* bare `&` in JSX text).
|
|
16
|
+
*/
|
|
17
|
+
const OWN_PACKAGE = {
|
|
18
|
+
c_sharp: 'tree-sitter-c-sharp',
|
|
19
|
+
typescript: 'tree-sitter-typescript',
|
|
20
|
+
tsx: 'tree-sitter-typescript',
|
|
21
|
+
};
|
|
22
|
+
/** Grammars no package ships current, built by this project (`grammars/README.md`; Dart: the packages predate Dart 3). */
|
|
23
|
+
const BUILT_HERE = new Set(['dart']);
|
|
24
|
+
const GRAMMARS_FOLDER = fileURLToPath(new URL('../../../grammars/', import.meta.url));
|
|
25
|
+
function grammarFile(grammar) {
|
|
26
|
+
if (BUILT_HERE.has(grammar))
|
|
27
|
+
return path.join(GRAMMARS_FOLDER, `tree-sitter-${grammar}.wasm`);
|
|
28
|
+
const own = OWN_PACKAGE[grammar];
|
|
29
|
+
if (own)
|
|
30
|
+
return path.join(path.dirname(require.resolve(`${own}/package.json`)), `tree-sitter-${grammar}.wasm`);
|
|
31
|
+
return path.join(path.dirname(require.resolve('tree-sitter-wasms/package.json')), 'out', `tree-sitter-${grammar}.wasm`);
|
|
32
|
+
}
|
|
33
|
+
async function load(grammar) {
|
|
34
|
+
init ??= Parser.init();
|
|
35
|
+
await init;
|
|
36
|
+
const language = await Language.load(grammarFile(grammar));
|
|
37
|
+
const parser = new Parser();
|
|
38
|
+
parser.setLanguage(language);
|
|
39
|
+
return { parser, language };
|
|
40
|
+
}
|
|
41
|
+
function parserFor(grammar) {
|
|
42
|
+
if (!parsers.has(grammar))
|
|
43
|
+
parsers.set(grammar, load(grammar));
|
|
44
|
+
return parsers.get(grammar);
|
|
45
|
+
}
|
|
46
|
+
/** A query compiled once per grammar and key. */
|
|
47
|
+
export function query(language, key, source) {
|
|
48
|
+
if (!queries.has(language))
|
|
49
|
+
queries.set(language, new Map());
|
|
50
|
+
const compiled = queries.get(language);
|
|
51
|
+
if (!compiled.has(key))
|
|
52
|
+
compiled.set(key, new Query(language, source));
|
|
53
|
+
return compiled.get(key);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Error nodes that are gaps of a pinned grammar, not errors in the code: valid code the grammar cannot read while the
|
|
57
|
+
* rest of the tree stays intact. tree-sitter-typescript 0.23.2, the newest, has two:
|
|
58
|
+
* - TSX: a bare `&` in JSX text ("Roles & Permissions"), which TypeScript and React accept.
|
|
59
|
+
* - TypeScript and TSX: a tagged template with type arguments (sql<Row>`SELECT ...`, common with Kysely and Drizzle).
|
|
60
|
+
* The grammar reads the call correctly but inserts a missing `!` after the type arguments.
|
|
61
|
+
*/
|
|
62
|
+
function isTypedTagGap(error) {
|
|
63
|
+
const nonNull = error.parent;
|
|
64
|
+
const call = nonNull?.parent;
|
|
65
|
+
return error.isMissing && error.type === '!' && nonNull?.type === 'non_null_expression'
|
|
66
|
+
&& nonNull.firstChild?.type === 'instantiation_expression' && call?.type === 'call_expression'
|
|
67
|
+
&& call.childForFieldName('arguments')?.type === 'template_string';
|
|
68
|
+
}
|
|
69
|
+
const isBareAmpersandGap = (error) => error.parent?.type === 'jsx_element' && /^&[^{}<>]*$/.test(error.text);
|
|
70
|
+
const GRAMMAR_GAPS = {
|
|
71
|
+
typescript: isTypedTagGap,
|
|
72
|
+
tsx: (error) => isTypedTagGap(error) || isBareAmpersandGap(error),
|
|
73
|
+
};
|
|
74
|
+
/** The first syntax error of a tree, as a message with its line, or undefined. */
|
|
75
|
+
function firstError(node, isGap) {
|
|
76
|
+
if (node.isMissing)
|
|
77
|
+
return isGap?.(node) ? undefined : `Syntax error at line ${node.startPosition.row + 1}: missing ${node.type}`;
|
|
78
|
+
if (node.type === 'ERROR')
|
|
79
|
+
return isGap?.(node) ? undefined : `Syntax error at line ${node.startPosition.row + 1}`;
|
|
80
|
+
if (!node.hasError)
|
|
81
|
+
return undefined;
|
|
82
|
+
for (const child of node.children) {
|
|
83
|
+
const found = child && firstError(child, isGap);
|
|
84
|
+
if (found)
|
|
85
|
+
return found;
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Parses `content` with a grammar and hands the tree to `use`; the tree's WebAssembly memory is freed afterwards.
|
|
91
|
+
* A syntax error anywhere is a ParseError (the file then has no symbols, CIN-04).
|
|
92
|
+
*/
|
|
93
|
+
export async function withTree(grammar, content, use) {
|
|
94
|
+
const { parser, language } = await parserFor(grammar);
|
|
95
|
+
const tree = parser.parse(content);
|
|
96
|
+
if (!tree)
|
|
97
|
+
throw new ParseError('The parser returned no tree');
|
|
98
|
+
try {
|
|
99
|
+
const error = firstError(tree.rootNode, GRAMMAR_GAPS[grammar]);
|
|
100
|
+
if (error)
|
|
101
|
+
throw new ParseError(error);
|
|
102
|
+
return use(tree.rootNode, language);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
tree.delete();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CallKind, CodeMap, ExternalBoundary } from '../model.js';
|
|
2
|
+
/**
|
|
3
|
+
* Execution flow graph (`flow` and `impact`) over a scanned CodeMap (Phase 2).
|
|
4
|
+
* Resolves static calls (`this.dep.method()` / `_dep.Method()` including inherited fields),
|
|
5
|
+
* `implements` edges (`IInterface.Method` -> `Impl.Method`), and virtual async/indirect bridges
|
|
6
|
+
* (events `@OnEvent`, jobs `@OnJob`, C# MediatR `IRequestHandler`/`INotificationHandler`).
|
|
7
|
+
*/
|
|
8
|
+
export type FlowEdgeKind = CallKind | 'impl' | 'handles';
|
|
9
|
+
export interface FlowOptions {
|
|
10
|
+
/** Maximum traversal depth (default: 4). */
|
|
11
|
+
depth?: number;
|
|
12
|
+
/** Include test files as callers/targets (default: false). */
|
|
13
|
+
includeTests?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface FlowNode {
|
|
16
|
+
id: string;
|
|
17
|
+
label: string;
|
|
18
|
+
file?: string;
|
|
19
|
+
line?: number;
|
|
20
|
+
virtual?: boolean;
|
|
21
|
+
entrypoints?: string[];
|
|
22
|
+
throws?: string[];
|
|
23
|
+
boundary?: ExternalBoundary;
|
|
24
|
+
cycle?: boolean;
|
|
25
|
+
edgeKind?: FlowEdgeKind;
|
|
26
|
+
callLine?: number;
|
|
27
|
+
children: FlowNode[];
|
|
28
|
+
}
|
|
29
|
+
export interface FlowResult {
|
|
30
|
+
query: string;
|
|
31
|
+
direction: 'downstream' | 'upstream';
|
|
32
|
+
depth: number;
|
|
33
|
+
roots: FlowNode[];
|
|
34
|
+
}
|
|
35
|
+
export declare class UnknownSymbolError extends Error {
|
|
36
|
+
}
|
|
37
|
+
/** Downstream execution flow from `<symbol>` up to `depth` hops. */
|
|
38
|
+
export declare function flow(map: CodeMap, symbolQuery: string, options?: FlowOptions): FlowResult;
|
|
39
|
+
/** Upstream impact (callers and entrypoints reaching `<symbol>`) up to `depth` hops. */
|
|
40
|
+
export declare function impact(map: CodeMap, symbolQuery: string, options?: FlowOptions): FlowResult;
|
|
41
|
+
/** Renders a `flow` or `impact` result as a compact indented tree with `file:line` addresses and edge kinds. */
|
|
42
|
+
export declare function renderFlow(result: FlowResult): string;
|