@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.
Files changed (143) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +202 -0
  3. package/README.md +139 -2
  4. package/dist/packs/csharp/calls.d.ts +4 -0
  5. package/dist/packs/csharp/calls.js +167 -0
  6. package/dist/packs/csharp/declarations.d.ts +4 -0
  7. package/dist/packs/csharp/declarations.js +142 -0
  8. package/dist/packs/csharp/pack.d.ts +2 -0
  9. package/dist/packs/csharp/pack.js +39 -0
  10. package/dist/packs/csharp/resolve.d.ts +2 -0
  11. package/dist/packs/csharp/resolve.js +35 -0
  12. package/dist/packs/csharp/signals.d.ts +7 -0
  13. package/dist/packs/csharp/signals.js +143 -0
  14. package/dist/packs/dart/calls.d.ts +4 -0
  15. package/dist/packs/dart/calls.js +130 -0
  16. package/dist/packs/dart/declarations.d.ts +11 -0
  17. package/dist/packs/dart/declarations.js +79 -0
  18. package/dist/packs/dart/members.d.ts +4 -0
  19. package/dist/packs/dart/members.js +62 -0
  20. package/dist/packs/dart/pack.d.ts +2 -0
  21. package/dist/packs/dart/pack.js +37 -0
  22. package/dist/packs/dart/resolve.d.ts +2 -0
  23. package/dist/packs/dart/resolve.js +32 -0
  24. package/dist/packs/index.d.ts +3 -0
  25. package/dist/packs/index.js +8 -0
  26. package/dist/packs/json/pack.d.ts +2 -0
  27. package/dist/packs/json/pack.js +27 -0
  28. package/dist/packs/msbuild/pack.d.ts +2 -0
  29. package/dist/packs/msbuild/pack.js +75 -0
  30. package/dist/packs/msbuild/xml.d.ts +16 -0
  31. package/dist/packs/msbuild/xml.js +123 -0
  32. package/dist/packs/typescript/calls.d.ts +4 -0
  33. package/dist/packs/typescript/calls.js +201 -0
  34. package/dist/packs/typescript/declarations.d.ts +9 -0
  35. package/dist/packs/typescript/declarations.js +74 -0
  36. package/dist/packs/typescript/members.d.ts +4 -0
  37. package/dist/packs/typescript/members.js +92 -0
  38. package/dist/packs/typescript/pack.d.ts +2 -0
  39. package/dist/packs/typescript/pack.js +53 -0
  40. package/dist/packs/typescript/resolve.d.ts +2 -0
  41. package/dist/packs/typescript/resolve.js +68 -0
  42. package/dist/packs/typescript/signals.d.ts +7 -0
  43. package/dist/packs/typescript/signals.js +186 -0
  44. package/dist/packs/yaml/pack.d.ts +2 -0
  45. package/dist/packs/yaml/pack.js +35 -0
  46. package/dist/src/cli.d.ts +2 -0
  47. package/dist/src/cli.js +371 -0
  48. package/dist/src/graph/build.d.ts +17 -0
  49. package/dist/src/graph/build.js +41 -0
  50. package/dist/src/graph/metrics.d.ts +12 -0
  51. package/dist/src/graph/metrics.js +75 -0
  52. package/dist/src/graph/topology.d.ts +5 -0
  53. package/dist/src/graph/topology.js +54 -0
  54. package/dist/src/health/compare.d.ts +2 -0
  55. package/dist/src/health/compare.js +38 -0
  56. package/dist/src/health/duplicates.d.ts +11 -0
  57. package/dist/src/health/duplicates.js +66 -0
  58. package/dist/src/health/health.d.ts +12 -0
  59. package/dist/src/health/health.js +94 -0
  60. package/dist/src/health/types.d.ts +101 -0
  61. package/dist/src/health/types.js +5 -0
  62. package/dist/src/index.d.ts +23 -0
  63. package/dist/src/index.js +20 -0
  64. package/dist/src/init/init.d.ts +73 -0
  65. package/dist/src/init/init.js +305 -0
  66. package/dist/src/init/scout.d.ts +45 -0
  67. package/dist/src/init/scout.js +208 -0
  68. package/dist/src/jsonc.d.ts +5 -0
  69. package/dist/src/jsonc.js +34 -0
  70. package/dist/src/mcp/server.d.ts +266 -0
  71. package/dist/src/mcp/server.js +414 -0
  72. package/dist/src/metrics/doctor.d.ts +15 -0
  73. package/dist/src/metrics/doctor.js +125 -0
  74. package/dist/src/metrics/log.d.ts +43 -0
  75. package/dist/src/metrics/log.js +101 -0
  76. package/dist/src/metrics/stats.d.ts +43 -0
  77. package/dist/src/metrics/stats.js +172 -0
  78. package/dist/src/model.d.ts +178 -0
  79. package/dist/src/model.js +2 -0
  80. package/dist/src/outputs.d.ts +16 -0
  81. package/dist/src/outputs.js +48 -0
  82. package/dist/src/packs/calls.d.ts +9 -0
  83. package/dist/src/packs/calls.js +119 -0
  84. package/dist/src/packs/dataShape.d.ts +6 -0
  85. package/dist/src/packs/dataShape.js +54 -0
  86. package/dist/src/packs/pack.d.ts +51 -0
  87. package/dist/src/packs/pack.js +3 -0
  88. package/dist/src/packs/packFiles.d.ts +5 -0
  89. package/dist/src/packs/packFiles.js +12 -0
  90. package/dist/src/packs/symbols.d.ts +39 -0
  91. package/dist/src/packs/symbols.js +98 -0
  92. package/dist/src/packs/treeSitter.d.ts +8 -0
  93. package/dist/src/packs/treeSitter.js +107 -0
  94. package/dist/src/queries/flow.d.ts +42 -0
  95. package/dist/src/queries/flow.js +391 -0
  96. package/dist/src/queries/map.d.ts +28 -0
  97. package/dist/src/queries/map.js +102 -0
  98. package/dist/src/queries/neighborhood.d.ts +35 -0
  99. package/dist/src/queries/neighborhood.js +60 -0
  100. package/dist/src/scan/audit.d.ts +2 -0
  101. package/dist/src/scan/audit.js +41 -0
  102. package/dist/src/scan/records.d.ts +12 -0
  103. package/dist/src/scan/records.js +42 -0
  104. package/dist/src/scan/resolveImports.d.ts +3 -0
  105. package/dist/src/scan/resolveImports.js +47 -0
  106. package/dist/src/scan/roles.d.ts +5 -0
  107. package/dist/src/scan/roles.js +87 -0
  108. package/dist/src/scan/scan.d.ts +24 -0
  109. package/dist/src/scan/scan.js +72 -0
  110. package/dist/src/text/briefs.d.ts +13 -0
  111. package/dist/src/text/briefs.js +43 -0
  112. package/dist/src/text/collapse.d.ts +10 -0
  113. package/dist/src/text/collapse.js +58 -0
  114. package/dist/src/text/declarations.d.ts +12 -0
  115. package/dist/src/text/declarations.js +120 -0
  116. package/dist/src/text/structure.d.ts +2 -0
  117. package/dist/src/text/structure.js +15 -0
  118. package/dist/src/text/tree.d.ts +20 -0
  119. package/dist/src/text/tree.js +49 -0
  120. package/dist/src/tokens.d.ts +4 -0
  121. package/dist/src/tokens.js +9 -0
  122. package/dist/src/version.d.ts +10 -0
  123. package/dist/src/version.js +11 -0
  124. package/dist/src/walk/ignoreRules.d.ts +17 -0
  125. package/dist/src/walk/ignoreRules.js +72 -0
  126. package/dist/src/walk/walk.d.ts +11 -0
  127. package/dist/src/walk/walk.js +29 -0
  128. package/grammars/LICENSE-tree-sitter-dart +20 -0
  129. package/grammars/README.md +11 -0
  130. package/grammars/tree-sitter-dart.wasm +0 -0
  131. package/package.json +68 -4
  132. package/packs/csharp/README.md +9 -0
  133. package/packs/csharp/imports.scm +3 -0
  134. package/packs/csharp/symbols.scm +17 -0
  135. package/packs/dart/imports.scm +5 -0
  136. package/packs/dart/symbols.scm +13 -0
  137. package/packs/msbuild/README.md +11 -0
  138. package/packs/typescript/exports.scm +16 -0
  139. package/packs/typescript/imports.scm +9 -0
  140. package/packs/typescript/symbols.scm +19 -0
  141. package/schema/ast_code_map.schema.json +144 -0
  142. package/schema/schema-lock.json +7 -0
  143. package/schema/topology.schema.json +87 -0
@@ -0,0 +1,12 @@
1
+ import type { FileRecord } from '../model.js';
2
+ import { type LanguagePack } from '../packs/pack.js';
3
+ import type { WalkedFile } from '../walk/walk.js';
4
+ /** One file's record: parsed by its pack, or listed without symbols when no pack claims it or it is too large. */
5
+ export declare const DEFAULT_MAX_FILE_BYTES = 200000;
6
+ /** Data files (JSON, YAML) are only shaped, so much larger ones are read. */
7
+ export declare const DEFAULT_MAX_DATA_FILE_BYTES = 20000000;
8
+ export declare function packFor(file: string, packs: LanguagePack[]): LanguagePack | undefined;
9
+ /** A file no pack claims: listed as `other`, never read, never guessed at (CIN-05). */
10
+ export declare function unsupportedRecord(file: WalkedFile): FileRecord;
11
+ /** Parses one file with its pack. A ParseError is recorded on the file (CIN-04); any other error is a bug and propagates. */
12
+ export declare function parsedRecord(root: string, file: WalkedFile, pack: LanguagePack, maxBytes: number): Promise<FileRecord>;
@@ -0,0 +1,42 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ParseError } from '../packs/pack.js';
4
+ import { skeletonOf } from '../text/declarations.js';
5
+ import { estimateTokens } from '../tokens.js';
6
+ /** One file's record: parsed by its pack, or listed without symbols when no pack claims it or it is too large. */
7
+ export const DEFAULT_MAX_FILE_BYTES = 200_000;
8
+ /** Data files (JSON, YAML) are only shaped, so much larger ones are read. */
9
+ export const DEFAULT_MAX_DATA_FILE_BYTES = 20_000_000;
10
+ export function packFor(file, packs) {
11
+ return packs.find((p) => p.claims(file));
12
+ }
13
+ function base(file, language) {
14
+ return { path: file.path, language, sizeBytes: file.sizeBytes, mtimeMs: file.mtimeMs, symbols: [], imports: [], skeleton: '', rawTokens: 0, skeletonTokens: 0 };
15
+ }
16
+ /** A file no pack claims: listed as `other`, never read, never guessed at (CIN-05). */
17
+ export function unsupportedRecord(file) {
18
+ return base(file, 'other');
19
+ }
20
+ /** Parses one file with its pack. A ParseError is recorded on the file (CIN-04); any other error is a bug and propagates. */
21
+ export async function parsedRecord(root, file, pack, maxBytes) {
22
+ const record = base(file, pack.id);
23
+ if (file.sizeBytes > maxBytes)
24
+ return { ...record, skipped: `larger than ${Math.round(maxBytes / 1000)} KB` };
25
+ const content = fs.readFileSync(path.join(root, file.path), 'utf8');
26
+ record.rawTokens = estimateTokens(content);
27
+ try {
28
+ const parsed = await pack.parse({ path: file.path, content });
29
+ const skeleton = parsed.skeleton ?? skeletonOf(parsed.symbols, content);
30
+ return {
31
+ ...record, symbols: parsed.symbols, skeleton, skeletonTokens: estimateTokens(skeleton),
32
+ imports: parsed.imports.map((i) => ({ ...i, kind: 'unresolved' })),
33
+ ...(parsed.declares ? { declares: parsed.declares } : {}),
34
+ ...(parsed.roles?.length ? { roles: parsed.roles } : {}),
35
+ };
36
+ }
37
+ catch (err) {
38
+ if (err instanceof ParseError)
39
+ return { ...record, error: err.message };
40
+ throw err;
41
+ }
42
+ }
@@ -0,0 +1,3 @@
1
+ import type { FileRecord } from '../model.js';
2
+ import type { LanguagePack } from '../packs/pack.js';
3
+ export declare function resolveImports(root: string, records: FileRecord[], packs: LanguagePack[]): FileRecord[];
@@ -0,0 +1,47 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { packFor } from './records.js';
4
+ /**
5
+ * Resolves every import of every record against the files of this scan. It runs on every scan, also for files that
6
+ * were not parsed again, so an import of an unchanged file follows a file that was added or removed.
7
+ */
8
+ function projectView(root, records) {
9
+ const paths = new Set(records.map((r) => r.path));
10
+ const sorted = [...paths].sort();
11
+ const texts = new Map();
12
+ return {
13
+ has: (p) => paths.has(p),
14
+ paths: () => sorted,
15
+ read: (p) => {
16
+ if (!texts.has(p))
17
+ texts.set(p, paths.has(p) ? fs.readFileSync(path.join(root, p), 'utf8') : undefined);
18
+ return texts.get(p);
19
+ },
20
+ };
21
+ }
22
+ /** A reused record holds resolved imports, one per target; each import statement is resolved once again. */
23
+ function rawImports(imports) {
24
+ const seen = new Set();
25
+ return imports.filter((i) => {
26
+ const key = `${i.line}\u0000${i.specifier}`;
27
+ if (seen.has(key))
28
+ return false;
29
+ seen.add(key);
30
+ return true;
31
+ });
32
+ }
33
+ /** One import, or one per target when it points at several files. */
34
+ function resolved(imp, from, pack, project) {
35
+ const { specifier, line, typeOnly } = imp;
36
+ const resolution = pack?.resolve?.({ from, raw: { specifier, line, typeOnly }, project }) ?? { kind: 'unresolved' };
37
+ return (Array.isArray(resolution) ? resolution : [resolution]).map((r) => ({ specifier, line, ...(typeOnly ? { typeOnly } : {}), ...r }));
38
+ }
39
+ export function resolveImports(root, records, packs) {
40
+ const project = projectView(root, records);
41
+ return records.map((r) => {
42
+ if (r.imports.length === 0)
43
+ return r;
44
+ const pack = packFor(r.path, packs);
45
+ return { ...r, imports: rawImports(r.imports).flatMap((i) => resolved(i, r.path, pack, project)) };
46
+ });
47
+ }
@@ -0,0 +1,5 @@
1
+ import type { FileRecord, RoleTag } from '../model.js';
2
+ /** Closed-vocabulary structural roles inferred deterministically from AST hints, symbols, and imports. */
3
+ export declare const ROLE_TAGS: readonly RoleTag[];
4
+ /** Deterministic closed-vocabulary roles for a file, sorted in canonical `ROLE_TAGS` order. */
5
+ export declare function inferFileRoles(record: FileRecord, astRoles?: readonly RoleTag[]): RoleTag[];
@@ -0,0 +1,87 @@
1
+ /** Closed-vocabulary structural roles inferred deterministically from AST hints, symbols, and imports. */
2
+ export const ROLE_TAGS = ['http', 'event', 'job', 'db', 'auth', 'ui', 'io'];
3
+ const HTTP_PACKAGES = new Set([
4
+ 'express', 'fastify', 'koa', 'hono', '@nestjs/platform-express', '@nestjs/platform-fastify',
5
+ 'axios', 'got', 'superagent', 'undici', 'node-fetch', 'ky', 'http', 'https', 'node:http', 'node:https',
6
+ ]);
7
+ const EVENT_PACKAGES = new Set([
8
+ 'events', 'node:events', '@nestjs/event-emitter', 'eventemitter2', 'eventemitter3', 'rxjs', 'mitt',
9
+ '@nestjs/websockets', 'socket.io', 'ws',
10
+ ]);
11
+ const JOB_PACKAGES = new Set([
12
+ 'bull', 'bullmq', '@nestjs/bull', '@nestjs/bullmq', '@nestjs/schedule', 'node-cron', 'cron', 'agenda', 'bree',
13
+ 'pg-boss', 'bee-queue', 'amqplib', 'kafkajs',
14
+ ]);
15
+ const DB_PACKAGES = new Set([
16
+ 'typeorm', '@nestjs/typeorm', 'prisma', '@prisma/client', 'kysely', 'drizzle-orm', 'knex', 'pg',
17
+ 'mysql', 'mysql2', 'sqlite3', 'better-sqlite3', 'mongodb', 'mongoose', 'sequelize', '@mikro-orm/core',
18
+ 'ioredis', 'redis', 'slonik', 'objection',
19
+ ]);
20
+ const AUTH_PACKAGES = new Set([
21
+ 'passport', '@nestjs/passport', '@nestjs/jwt', 'jsonwebtoken', 'bcrypt', 'bcryptjs', 'argon2',
22
+ 'openid-client', 'oauth4webapi', 'jose', 'next-auth', 'lucia', 'arctic', 'oslo',
23
+ ]);
24
+ const UI_PACKAGES = new Set([
25
+ 'react', 'react-dom', 'preact', 'solid-js', 'vue', '@angular/core', 'svelte', 'next', 'flutter',
26
+ ]);
27
+ const IO_PACKAGES = new Set([
28
+ 'fs', 'node:fs', 'fs/promises', 'node:fs/promises', 'stream', 'node:stream', 'child_process', 'node:child_process',
29
+ 'sharp', 'fluent-ffmpeg', 'multer', 'archiver', 'tar', 'zlib', 'node:zlib', 'readline', 'node:readline',
30
+ ]);
31
+ const HTTP_NS_PREFIXES = ['Microsoft.AspNetCore.Mvc', 'Microsoft.AspNetCore.Http', 'System.Net.Http'];
32
+ const EVENT_NS_PREFIXES = ['MediatR', 'MassTransit'];
33
+ const JOB_NS_PREFIXES = ['Hangfire', 'Quartz', 'Microsoft.Extensions.Hosting'];
34
+ const DB_NS_PREFIXES = ['Microsoft.EntityFrameworkCore', 'Dapper', 'Npgsql', 'System.Data', 'MongoDB.Driver', 'StackExchange.Redis'];
35
+ const AUTH_NS_PREFIXES = ['Microsoft.AspNetCore.Authorization', 'Microsoft.AspNetCore.Authentication', 'Microsoft.AspNetCore.Identity', 'System.Security.Claims'];
36
+ const IO_NS_PREFIXES = ['System.IO'];
37
+ const AUTH_EXCEPTION = /(Unauthorized|Forbidden|Authentication|Unauthenticated|InvalidToken|InvalidCredentials)/i;
38
+ const HTTP_ENTRYPOINT = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ALL|route:)/;
39
+ function matchesPrefix(specifier, prefixes) {
40
+ return prefixes.some((p) => specifier === p || specifier.startsWith(`${p}.`));
41
+ }
42
+ function rolesFromImport(imp, roles) {
43
+ const pkg = imp.package ?? imp.specifier;
44
+ const spec = imp.specifier;
45
+ if (HTTP_PACKAGES.has(pkg) || HTTP_PACKAGES.has(spec) || matchesPrefix(spec, HTTP_NS_PREFIXES))
46
+ roles.add('http');
47
+ if (EVENT_PACKAGES.has(pkg) || EVENT_PACKAGES.has(spec) || matchesPrefix(spec, EVENT_NS_PREFIXES))
48
+ roles.add('event');
49
+ if (JOB_PACKAGES.has(pkg) || JOB_PACKAGES.has(spec) || matchesPrefix(spec, JOB_NS_PREFIXES))
50
+ roles.add('job');
51
+ if (DB_PACKAGES.has(pkg) || DB_PACKAGES.has(spec) || matchesPrefix(spec, DB_NS_PREFIXES))
52
+ roles.add('db');
53
+ if (AUTH_PACKAGES.has(pkg) || AUTH_PACKAGES.has(spec) || matchesPrefix(spec, AUTH_NS_PREFIXES))
54
+ roles.add('auth');
55
+ if (UI_PACKAGES.has(pkg) || UI_PACKAGES.has(spec))
56
+ roles.add('ui');
57
+ if (IO_PACKAGES.has(pkg) || IO_PACKAGES.has(spec) || matchesPrefix(spec, IO_NS_PREFIXES))
58
+ roles.add('io');
59
+ }
60
+ function rolesFromSymbols(symbols, roles) {
61
+ for (const s of symbols) {
62
+ if (s.lifecycle)
63
+ roles.add('ui');
64
+ for (const ep of s.entrypoints ?? []) {
65
+ if (HTTP_ENTRYPOINT.test(ep))
66
+ roles.add('http');
67
+ else if (ep.startsWith('event:'))
68
+ roles.add('event');
69
+ else if (ep.startsWith('job:') || ep.startsWith('cron:'))
70
+ roles.add('job');
71
+ }
72
+ for (const err of s.throws ?? []) {
73
+ if (AUTH_EXCEPTION.test(err))
74
+ roles.add('auth');
75
+ }
76
+ if (s.members?.length)
77
+ rolesFromSymbols(s.members, roles);
78
+ }
79
+ }
80
+ /** Deterministic closed-vocabulary roles for a file, sorted in canonical `ROLE_TAGS` order. */
81
+ export function inferFileRoles(record, astRoles) {
82
+ const roles = new Set(astRoles ?? []);
83
+ for (const imp of record.imports)
84
+ rolesFromImport(imp, roles);
85
+ rolesFromSymbols(record.symbols, roles);
86
+ return ROLE_TAGS.filter((tag) => roles.has(tag));
87
+ }
@@ -0,0 +1,24 @@
1
+ import type { CodeMap, Topology } from '../model.js';
2
+ import type { LanguagePack } from '../packs/pack.js';
3
+ /** A scan (FR-01): walk the folder, parse what changed, resolve imports, build the graph, write the four outputs. */
4
+ export interface ScanOptions {
5
+ /** The folder to scan. */
6
+ root: string;
7
+ /** The output folder; `<root>/.faber-atlas` when absent. */
8
+ out?: string;
9
+ /** Paths relative to `root` that are left out, as if they were ignored. */
10
+ exclude?: string[];
11
+ /** Parse every file again instead of reusing the records of unchanged ones. */
12
+ full?: boolean;
13
+ /** Files larger than this are listed without being parsed; 200 KB when absent. */
14
+ maxFileBytes?: number;
15
+ /** The same for data files (JSON, YAML), which are only shaped; 20 MB when absent. */
16
+ maxDataFileBytes?: number;
17
+ packs: LanguagePack[];
18
+ }
19
+ export interface ScanResult {
20
+ map: CodeMap;
21
+ topology: Topology;
22
+ out: string;
23
+ }
24
+ export declare function scan(options: ScanOptions): Promise<ScanResult>;
@@ -0,0 +1,72 @@
1
+ import path from 'node:path';
2
+ import { buildTopology } from '../graph/topology.js';
3
+ import { recordScanMetric } from '../metrics/log.js';
4
+ import { previousCodeMap, writeOutputs } from '../outputs.js';
5
+ import { GENERATOR_VERSION, SCHEMA_VERSION } from '../version.js';
6
+ import { walk } from '../walk/walk.js';
7
+ import { dependencyAudit } from './audit.js';
8
+ import { DEFAULT_MAX_DATA_FILE_BYTES, DEFAULT_MAX_FILE_BYTES, packFor, parsedRecord, unsupportedRecord } from './records.js';
9
+ import { resolveImports } from './resolveImports.js';
10
+ import { inferFileRoles } from './roles.js';
11
+ /** Records of the previous scan that still match the file's size and modification time. */
12
+ function reusable(previous) {
13
+ return new Map((previous?.files ?? []).map((f) => [f.path, f]));
14
+ }
15
+ function sizeLimit(options, pack) {
16
+ return pack.data ? (options.maxDataFileBytes ?? DEFAULT_MAX_DATA_FILE_BYTES) : (options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES);
17
+ }
18
+ async function recordsOf(options, files, previous) {
19
+ const records = [];
20
+ let parsed = 0;
21
+ for (const file of files) {
22
+ const old = previous.get(file.path);
23
+ const pack = packFor(file.path, options.packs);
24
+ if (old && old.sizeBytes === file.sizeBytes && old.mtimeMs === file.mtimeMs)
25
+ records.push(old);
26
+ else if (!pack)
27
+ records.push(unsupportedRecord(file));
28
+ else {
29
+ records.push(await parsedRecord(options.root, file, pack, sizeLimit(options, pack)));
30
+ parsed++;
31
+ }
32
+ }
33
+ return { records, parsed };
34
+ }
35
+ function extensionOf(file) {
36
+ const ext = path.posix.extname(file);
37
+ return ext || path.posix.basename(file);
38
+ }
39
+ function summarize(records, parsed, durationMs) {
40
+ const count = (key, list) => list.reduce((acc, r) => ({ ...acc, [key(r)]: (acc[key(r)] ?? 0) + 1 }), {});
41
+ const countSymbols = (list) => list.reduce((sum, r) => sum + r.symbols.length + r.symbols.reduce((m, s) => m + (s.members?.length ?? 0), 0), 0);
42
+ return {
43
+ files: records.length, parsed, reused: records.length - parsed,
44
+ failed: records.filter((r) => r.error).map((r) => ({ path: r.path, error: r.error })),
45
+ unsupported: count((r) => extensionOf(r.path), records.filter((r) => r.language === 'other')),
46
+ languages: count((r) => r.language, records),
47
+ symbols: countSymbols(records),
48
+ rawTokens: records.reduce((s, r) => s + r.rawTokens, 0),
49
+ skeletonTokens: records.reduce((s, r) => s + r.skeletonTokens, 0),
50
+ durationMs,
51
+ };
52
+ }
53
+ export async function scan(options) {
54
+ const started = Date.now();
55
+ const root = path.resolve(options.root);
56
+ const out = path.resolve(options.out ?? path.join(root, '.faber-atlas'));
57
+ const files = walk(root, options.exclude);
58
+ const previous = options.full ? new Map() : reusable(previousCodeMap(out, GENERATOR_VERSION));
59
+ const { records: raw, parsed } = await recordsOf({ ...options, root }, files, previous);
60
+ const resolved = resolveImports(root, raw, options.packs);
61
+ const records = resolved.map((r) => {
62
+ const roles = inferFileRoles(r, r.roles);
63
+ return roles.length ? { ...r, roles } : r;
64
+ });
65
+ const generator = { schemaVersion: SCHEMA_VERSION, generatorVersion: GENERATOR_VERSION, generatedAt: new Date().toISOString() };
66
+ const codeLanguages = new Set(options.packs.filter((p) => p.resolve).map((p) => p.id));
67
+ const map = { ...generator, rootName: path.basename(root), summary: summarize(records, parsed, Date.now() - started), files: records, audit: dependencyAudit(records) };
68
+ const topology = buildTopology(records, codeLanguages, generator);
69
+ writeOutputs(out, map, topology);
70
+ recordScanMetric(out, map.summary, previous.size > 0);
71
+ return { map, topology, out };
72
+ }
@@ -0,0 +1,13 @@
1
+ import type { CodeMap } from '../model.js';
2
+ import { type Neighborhood } from '../queries/neighborhood.js';
3
+ /** The text the CLI prints for `neighborhood` and `brief`: each file under a header line, as a brief or as its contents. */
4
+ /** Where the scanned files are read from for `--contents`: the given root, or the folder that holds the outputs. */
5
+ export interface ContentSource {
6
+ root: string;
7
+ }
8
+ /** One header line per file, without briefs or contents. */
9
+ export declare function neighborhoodList(result: Neighborhood): string;
10
+ /** Each file's header, then its brief, or its contents when a source is given. */
11
+ export declare function neighborhoodText(result: Neighborhood, source?: ContentSource): string;
12
+ /** The briefs of the given files, each under its path. */
13
+ export declare function briefsText(map: CodeMap, files: string[]): string;
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { UnknownFileError } from '../queries/neighborhood.js';
4
+ function body(entry, source) {
5
+ if (!source)
6
+ return (entry.brief ?? '').trimEnd();
7
+ return fs.readFileSync(path.join(source.root, entry.path), 'utf8').trimEnd();
8
+ }
9
+ function header(entry) {
10
+ return `## tier ${entry.tier} ${entry.path} (${entry.tokens} tokens; ${entry.reason})`;
11
+ }
12
+ function footer(result) {
13
+ const files = result.targets.length + result.selected.length;
14
+ const left = result.omitted.files;
15
+ if (result.budget === undefined) {
16
+ const more = left ? `; ${left} files one ring further left out (${result.omitted.tokens} tokens; give --budget to include them)` : '';
17
+ return `${result.selectedTokens} tokens in ${files} files${more}.`;
18
+ }
19
+ return `${result.selectedTokens} of ${result.budget} tokens used; ${left} files left out (${result.omitted.tokens} tokens).`;
20
+ }
21
+ /** One header line per file, without briefs or contents. */
22
+ export function neighborhoodList(result) {
23
+ const lines = [...result.targets, ...result.selected].map((e) => `tier ${e.tier} ${e.path} (${e.tokens} tokens; ${e.reason})`);
24
+ return [...lines, footer(result)].join('\n');
25
+ }
26
+ /** Each file's header, then its brief, or its contents when a source is given. */
27
+ export function neighborhoodText(result, source) {
28
+ const blocks = [...result.targets, ...result.selected].map((e) => `${header(e)}\n${body(e, source)}`);
29
+ return [...blocks, footer(result)].join('\n\n');
30
+ }
31
+ /** The briefs of the given files, each under its path. */
32
+ export function briefsText(map, files) {
33
+ const records = new Map(map.files.map((f) => [f.path, f]));
34
+ const paths = files.map((p) => p.replace(/^\.\//, ''));
35
+ const unknown = paths.filter((p) => !records.has(p));
36
+ if (unknown.length)
37
+ throw new UnknownFileError(`Not in the code map: ${unknown.join(', ')}`);
38
+ return paths.map((p) => {
39
+ const rec = records.get(p);
40
+ const roles = rec.roles?.length ? ` [${rec.roles.join(', ')}]` : '';
41
+ return `## ${p} (${rec.skeletonTokens} tokens)${roles}\n${rec.skeleton}`;
42
+ }).join('\n\n');
43
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Collapses numbered files in one folder: `quiz_1.json` .. `quiz_45.json` becomes `quiz_{1..45}.json [45 JSON files]`.
3
+ * Only runs of three or more consecutive numbers collapse, so a listing never claims files that do not exist.
4
+ */
5
+ export declare const byName: (a: string, b: string) => number;
6
+ /** The names to show for one folder's files, sorted; `collapsed` maps a group label to the files it stands for. */
7
+ export declare function collapseNames(files: string[]): {
8
+ names: string[];
9
+ collapsed: Map<string, string[]>;
10
+ };
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Collapses numbered files in one folder: `quiz_1.json` .. `quiz_45.json` becomes `quiz_{1..45}.json [45 JSON files]`.
3
+ * Only runs of three or more consecutive numbers collapse, so a listing never claims files that do not exist.
4
+ */
5
+ export const byName = (a, b) => a.localeCompare(b, 'en');
6
+ function numbersIn(file) {
7
+ const dot = file.lastIndexOf('.');
8
+ const ext = dot === -1 ? '' : file.slice(dot + 1).toLowerCase();
9
+ const base = dot === -1 ? file : file.slice(0, dot);
10
+ return [...base.matchAll(/\d+/g)].map((m) => ({
11
+ file, ext, digits: m[0], num: Number(m[0]), index: m.index,
12
+ prefix: base.slice(0, m.index), suffix: base.slice(m.index + m[0].length),
13
+ }));
14
+ }
15
+ function toRun(items) {
16
+ const first = items[0];
17
+ const ext = first.ext ? `.${first.ext}` : '';
18
+ const what = first.ext ? `${first.ext.toUpperCase()} files` : 'files';
19
+ const label = `${first.prefix}{${first.digits}..${items[items.length - 1].digits}}${first.suffix}${ext} [${items.length} ${what}]`;
20
+ return { files: items.map((i) => i.file), label, index: first.index };
21
+ }
22
+ /** Runs of three or more consecutive numbers among files sharing a prefix, suffix and extension. */
23
+ function runs(files) {
24
+ const groups = new Map();
25
+ for (const n of files.flatMap(numbersIn)) {
26
+ const key = `${n.prefix.toLowerCase()}#${n.suffix.toLowerCase()}#${n.ext}`;
27
+ groups.set(key, [...(groups.get(key) ?? []), n]);
28
+ }
29
+ const found = [];
30
+ for (const items of groups.values()) {
31
+ items.sort((a, b) => a.num - b.num);
32
+ let current = [items[0]];
33
+ for (const item of [...items.slice(1), undefined]) {
34
+ if (item && item.num === current[current.length - 1].num + 1)
35
+ current.push(item);
36
+ else {
37
+ if (current.length >= 3)
38
+ found.push(toRun(current));
39
+ if (item)
40
+ current = [item];
41
+ }
42
+ }
43
+ }
44
+ return found.sort((a, b) => b.files.length - a.files.length || b.index - a.index);
45
+ }
46
+ /** The names to show for one folder's files, sorted; `collapsed` maps a group label to the files it stands for. */
47
+ export function collapseNames(files) {
48
+ const collapsed = new Map();
49
+ const claimed = new Set();
50
+ for (const run of files.length > 2 ? runs(files) : []) {
51
+ if (run.files.some((f) => claimed.has(f)))
52
+ continue;
53
+ run.files.forEach((f) => claimed.add(f));
54
+ collapsed.set(run.label, run.files);
55
+ }
56
+ const names = [...collapsed.keys(), ...files.filter((f) => !claimed.has(f))].sort(byName);
57
+ return { names, collapsed };
58
+ }
@@ -0,0 +1,12 @@
1
+ import type { FileRecord, SymbolNode } from '../model.js';
2
+ /** The one-line summary of a file in the map: its containers, then its other declarations. */
3
+ export declare function mapSummary(record: FileRecord, fields: boolean): string | undefined;
4
+ /** Zoom 1 one-line summary: top-level classes/interfaces/enums/functions/types only (no method lists), plus role tags. */
5
+ export declare function mapSummaryZoom1(record: FileRecord): string | undefined;
6
+ /** The full public declarations of a file, one line per top-level declaration (TopologyFULL.txt). */
7
+ export declare function fullBlock(record: FileRecord): string[];
8
+ /**
9
+ * The skeleton of a file, the brief a tool reads instead of the file: its declarations without bodies (non-private
10
+ * members), with long enums and constant runs cut; or its first lines when it declares nothing.
11
+ */
12
+ export declare function skeletonOf(symbols: SymbolNode[], content: string): string;
@@ -0,0 +1,120 @@
1
+ import { CONTAINER_KINDS } from '../packs/symbols.js';
2
+ /**
3
+ * What the text outputs print for a file. Only the public surface is shown: exported top-level declarations and
4
+ * their public and protected members. Constructors are left out; the map also leaves out framework callbacks.
5
+ */
6
+ const LIMITS = { containers: 4, methods: 15, fields: 25, topLevel: 6 };
7
+ const MODIFIER = /^(public|protected|private|readonly|static|final|const|late|var|abstract|override|covariant|external|declare|async)\s+/;
8
+ const FIELD_KINDS = new Set(['field', 'getter']);
9
+ const METHOD_KINDS = new Set(['method', 'setter']);
10
+ function visibleMembers(symbol, withLifecycle) {
11
+ return (symbol.members ?? []).filter((m) => m.visibility !== 'private' && m.kind !== 'constructor' && (withLifecycle || !m.lifecycle));
12
+ }
13
+ /** A field or getter as `name: Type` or `Type name`, without modifiers: `readonly id: string` gives `id: string`. */
14
+ function fieldLabel(member) {
15
+ let label = member.signature;
16
+ while (MODIFIER.test(label))
17
+ label = label.replace(MODIFIER, '');
18
+ return label.replace(/\bget\s+/, '').replace(/\(\)\s*:/, ':');
19
+ }
20
+ function unique(items, limit) {
21
+ return [...new Set(items)].slice(0, limit);
22
+ }
23
+ function containerSummary(symbol, fields) {
24
+ if (symbol.kind === 'enum')
25
+ return `enum ${symbol.name}`;
26
+ const members = visibleMembers(symbol, false);
27
+ const fieldList = fields ? unique(members.filter((m) => FIELD_KINDS.has(m.kind)).map(fieldLabel), LIMITS.fields) : [];
28
+ const methods = unique(members.filter((m) => METHOD_KINDS.has(m.kind)).map((m) => `${m.name}()`), LIMITS.methods);
29
+ const details = [...fieldList, ...methods].join(', ');
30
+ return `${symbol.kind} ${symbol.name}${details ? ` { ${details} }` : ''}`;
31
+ }
32
+ /** The one-line summary of a file in the map: its containers, then its other declarations. */
33
+ export function mapSummary(record, fields) {
34
+ const exported = record.symbols.filter((s) => s.exported && !s.lifecycle);
35
+ const containers = exported.filter((s) => CONTAINER_KINDS.has(s.kind)).slice(0, LIMITS.containers).map((s) => containerSummary(s, fields));
36
+ const others = exported.filter((s) => !CONTAINER_KINDS.has(s.kind) && (fields || s.kind !== 'variable'));
37
+ const topLevel = others.slice(0, LIMITS.topLevel).map((s) => (s.kind === 'function' ? `${s.name}()` : s.kind === 'type' ? `type ${s.name}` : fieldLabel(s)));
38
+ const parts = [...containers, ...(topLevel.length ? [topLevel.join(', ')] : [])];
39
+ return parts.length ? parts.join(' | ') : undefined;
40
+ }
41
+ /** Zoom 1 one-line summary: top-level classes/interfaces/enums/functions/types only (no method lists), plus role tags. */
42
+ export function mapSummaryZoom1(record) {
43
+ const exported = record.symbols.filter((s) => s.exported && !s.lifecycle);
44
+ const containers = exported.filter((s) => CONTAINER_KINDS.has(s.kind)).slice(0, LIMITS.containers).map((s) => `${s.kind} ${s.name}`);
45
+ const others = exported.filter((s) => !CONTAINER_KINDS.has(s.kind) && s.kind !== 'variable');
46
+ const topLevel = others.slice(0, LIMITS.topLevel).map((s) => (s.kind === 'function' ? `${s.name}()` : `type ${s.name}`));
47
+ const parts = [...containers, ...(topLevel.length ? [topLevel.join(', ')] : [])];
48
+ const roles = record.roles?.length ? `[${record.roles.join(', ')}]` : '';
49
+ const body = parts.join(' | ');
50
+ if (body && roles)
51
+ return `${body} ${roles}`;
52
+ return body || roles || undefined;
53
+ }
54
+ function containerBlock(symbol) {
55
+ const members = visibleMembers(symbol, true);
56
+ if (symbol.kind === 'enum') {
57
+ const constants = members.filter((m) => m.kind === 'enumMember').map((m) => m.name).join(', ');
58
+ const others = members.filter((m) => m.kind !== 'enumMember').map((m) => ` ${m.signature};`).join('');
59
+ return `${symbol.signature} { ${constants}${others ? `;${others}` : ''} }`;
60
+ }
61
+ return members.length ? `${symbol.signature} { ${members.map((m) => `${m.signature};`).join(' ')} }` : `${symbol.signature} {}`;
62
+ }
63
+ /** The full public declarations of a file, one line per top-level declaration (TopologyFULL.txt). */
64
+ export function fullBlock(record) {
65
+ return record.symbols.filter((s) => s.exported).map((s) => (CONTAINER_KINDS.has(s.kind) ? containerBlock(s) : `${s.signature};`));
66
+ }
67
+ /** A skeleton stays a brief: long enums and long runs of top-level constants are cut, the full text is one read away. */
68
+ const BRIEF = { enumMembers: 8, constantRun: 10 };
69
+ /** An enum's members (with their values) on one line, cut after `BRIEF.enumMembers`; other members (Dart) follow on their own lines. */
70
+ function enumSkeleton(symbol) {
71
+ const members = (symbol.members ?? []).filter((m) => m.visibility !== 'private');
72
+ const names = members.filter((m) => m.kind === 'enumMember').map((m) => m.signature);
73
+ const shown = names.slice(0, BRIEF.enumMembers).join(', ');
74
+ const more = names.length > BRIEF.enumMembers ? `, ... +${names.length - BRIEF.enumMembers} more` : '';
75
+ const others = members.filter((m) => m.kind !== 'enumMember').map((m) => ` ${m.signature};`);
76
+ if (!others.length)
77
+ return `${symbol.signature} { ${shown}${more} }`;
78
+ return `${symbol.signature} {\n ${shown}${more};\n${others.join('\n')}\n}`;
79
+ }
80
+ function signalComment(symbol) {
81
+ const parts = [];
82
+ if (symbol.entrypoints?.length)
83
+ parts.push(`[${symbol.entrypoints.join(', ')}]`);
84
+ if (symbol.throws?.length)
85
+ parts.push(`throws: ${symbol.throws.join(', ')}`);
86
+ return parts.length ? ` // ${parts.join(' ')}` : '';
87
+ }
88
+ function symbolSkeleton(symbol) {
89
+ if (symbol.kind === 'enum')
90
+ return enumSkeleton(symbol);
91
+ if (!CONTAINER_KINDS.has(symbol.kind))
92
+ return `${symbol.signature};${signalComment(symbol)}`;
93
+ const members = (symbol.members ?? []).filter((m) => m.visibility !== 'private').map((m) => ` ${m.signature};${signalComment(m)}`);
94
+ const headerLine = `${symbol.signature}${members.length ? ' {' : ' {}'}${signalComment(symbol)}`;
95
+ return members.length ? `${headerLine}\n${members.join('\n')}\n}` : headerLine;
96
+ }
97
+ /** Keeps the first `BRIEF.constantRun` of each run of top-level constants and counts the rest. */
98
+ function cutConstantRuns(symbols) {
99
+ const blocks = [];
100
+ let run = 0;
101
+ for (const symbol of symbols) {
102
+ run = symbol.kind === 'variable' ? run + 1 : 0;
103
+ if (run <= BRIEF.constantRun)
104
+ blocks.push(symbolSkeleton(symbol));
105
+ else if (run === BRIEF.constantRun + 1)
106
+ blocks.push('// ... +1 more constants');
107
+ else
108
+ blocks[blocks.length - 1] = `// ... +${run - BRIEF.constantRun} more constants`;
109
+ }
110
+ return blocks;
111
+ }
112
+ /**
113
+ * The skeleton of a file, the brief a tool reads instead of the file: its declarations without bodies (non-private
114
+ * members), with long enums and constant runs cut; or its first lines when it declares nothing.
115
+ */
116
+ export function skeletonOf(symbols, content) {
117
+ if (symbols.length === 0)
118
+ return content.split('\n').slice(0, 30).join('\n');
119
+ return cutConstantRuns(symbols).join('\n\n');
120
+ }
@@ -0,0 +1,2 @@
1
+ import type { CodeMap } from '../model.js';
2
+ export declare function renderStructure(map: CodeMap): string;
@@ -0,0 +1,15 @@
1
+ import { CONTAINER_KINDS } from '../packs/symbols.js';
2
+ /** project_structure.md: the public declarations of every file, as Markdown. */
3
+ function lines(symbol) {
4
+ const own = `- \`${symbol.signature}\``;
5
+ if (!CONTAINER_KINDS.has(symbol.kind))
6
+ return [own];
7
+ const members = (symbol.members ?? []).filter((m) => m.visibility !== 'private' && m.kind !== 'constructor');
8
+ return [own, ...members.map((m) => ` - \`${m.signature}\``)];
9
+ }
10
+ export function renderStructure(map) {
11
+ const files = map.files.filter((f) => f.symbols.some((s) => s.exported));
12
+ const sections = files.map((f) => [`## \`${f.path}\``, '', ...f.symbols.filter((s) => s.exported).flatMap(lines)].join('\n'));
13
+ const intro = `${map.summary.files} files scanned, ${files.length} with public declarations. Generated by faber-atlas ${map.generatorVersion}.`;
14
+ return [`# Project structure: ${map.rootName}`, '', intro, '', ...sections.flatMap((s) => [s, ''])].join('\n');
15
+ }
@@ -0,0 +1,20 @@
1
+ /** The folder tree text of the map and of TopologyFULL.txt. */
2
+ export interface FileText {
3
+ /** Printed after the file name: `a.ts: class A`. */
4
+ inline?: string;
5
+ /** Printed as lines under the file name. */
6
+ block?: string[];
7
+ }
8
+ export interface TreeOptions {
9
+ rootName: string;
10
+ /** Folder levels below the root to print; unlimited when absent. */
11
+ maxDepth?: number;
12
+ /** Print folders only. */
13
+ foldersOnly?: boolean;
14
+ describe(path: string): FileText;
15
+ }
16
+ /**
17
+ * The tree of the given file paths under a `<root>/` header, indented two spaces per level. No tree lines or icons:
18
+ * they cost many tokens and tell a model nothing the indentation does not.
19
+ */
20
+ export declare function renderTree(paths: string[], opts: TreeOptions): string;