@fougere/compiler 0.8.4-alpha.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/dist/boot.d.ts +42 -0
  3. package/dist/boot.d.ts.map +1 -0
  4. package/dist/boot.js +59 -0
  5. package/dist/boot.js.map +1 -0
  6. package/dist/declarations.d.ts +35 -0
  7. package/dist/declarations.d.ts.map +1 -0
  8. package/dist/declarations.js +75 -0
  9. package/dist/declarations.js.map +1 -0
  10. package/dist/imports.d.ts +17 -0
  11. package/dist/imports.d.ts.map +1 -0
  12. package/dist/imports.js +78 -0
  13. package/dist/imports.js.map +1 -0
  14. package/dist/index.d.ts +12 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +12 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/placement.d.ts +26 -0
  19. package/dist/placement.d.ts.map +1 -0
  20. package/dist/placement.js +69 -0
  21. package/dist/placement.js.map +1 -0
  22. package/dist/scan/adapters.d.ts +3 -0
  23. package/dist/scan/adapters.d.ts.map +1 -0
  24. package/dist/scan/adapters.js +25 -0
  25. package/dist/scan/adapters.js.map +1 -0
  26. package/dist/scan/bundling.d.ts +3 -0
  27. package/dist/scan/bundling.d.ts.map +1 -0
  28. package/dist/scan/bundling.js +15 -0
  29. package/dist/scan/bundling.js.map +1 -0
  30. package/dist/scan/contract.d.ts +27 -0
  31. package/dist/scan/contract.d.ts.map +1 -0
  32. package/dist/scan/contract.js +45 -0
  33. package/dist/scan/contract.js.map +1 -0
  34. package/dist/scan/emit.d.ts +11 -0
  35. package/dist/scan/emit.d.ts.map +1 -0
  36. package/dist/scan/emit.js +143 -0
  37. package/dist/scan/emit.js.map +1 -0
  38. package/dist/scan/handler-parser.d.ts +24 -0
  39. package/dist/scan/handler-parser.d.ts.map +1 -0
  40. package/dist/scan/handler-parser.js +602 -0
  41. package/dist/scan/handler-parser.js.map +1 -0
  42. package/dist/scan/scanner.d.ts +11 -0
  43. package/dist/scan/scanner.d.ts.map +1 -0
  44. package/dist/scan/scanner.js +565 -0
  45. package/dist/scan/scanner.js.map +1 -0
  46. package/dist/scan/statement.d.ts +5 -0
  47. package/dist/scan/statement.d.ts.map +1 -0
  48. package/dist/scan/statement.js +134 -0
  49. package/dist/scan/statement.js.map +1 -0
  50. package/package.json +55 -0
  51. package/src/boot.ts +105 -0
  52. package/src/declarations.ts +110 -0
  53. package/src/imports.ts +94 -0
  54. package/src/index.ts +14 -0
  55. package/src/placement.ts +86 -0
  56. package/src/scan/adapters.ts +32 -0
  57. package/src/scan/bundling.ts +14 -0
  58. package/src/scan/contract.ts +79 -0
  59. package/src/scan/emit.ts +160 -0
  60. package/src/scan/handler-parser.ts +683 -0
  61. package/src/scan/scanner.ts +686 -0
  62. package/src/scan/statement.ts +159 -0
@@ -0,0 +1,683 @@
1
+ /** Handler signature parser — extracts method signatures from handler source files. */
2
+ import { type Param, type Signature, type TypeRef } from '@fougere/core/descriptor';
3
+
4
+ import type ts from '@typescript/typescript6';
5
+ import { readFileSync, existsSync, statSync } from 'node:fs';
6
+ import { join, dirname, resolve as resolvePath } from 'node:path';
7
+
8
+ /** Lazy-loaded TypeScript module — avoids bundling the 9MB compiler. */
9
+ let _ts: typeof ts | undefined;
10
+ async function loadTS(): Promise<typeof ts> {
11
+ if (!_ts) _ts = (await import('@typescript/typescript6')).default;
12
+ return _ts;
13
+ }
14
+ function getTS(): typeof ts {
15
+ if (!_ts) throw new Error('TypeScript not loaded — call an async parse function first');
16
+ return _ts;
17
+ }
18
+
19
+ interface TypeProject {
20
+ roots: Set<string>;
21
+ options: ts.CompilerOptions;
22
+ program: ts.Program;
23
+ }
24
+
25
+ /** One checked program per project/configuration during a scan. */
26
+ const typeProjects = new Map<string, TypeProject>();
27
+ const compilerProjects = new Map<string, { key: string; roots: string[]; options: ts.CompilerOptions }>();
28
+
29
+ /** What survives a run. */
30
+ const sourceFiles = new Map<string, { mtime: number; file: ts.SourceFile }>();
31
+ const retained = new Map<string, { host: ts.CompilerHost; program: ts.Program }>();
32
+
33
+ export function resetTypePrograms(): void {
34
+ typeProjects.clear();
35
+ compilerProjects.clear();
36
+ }
37
+
38
+ function keptHost(key: string, options: ts.CompilerOptions): ts.CompilerHost {
39
+ const cached = retained.get(key);
40
+ if (cached) return cached.host;
41
+ const typescript = getTS();
42
+ const base = typescript.createCompilerHost(options);
43
+ const host: ts.CompilerHost = {
44
+ ...base,
45
+ getSourceFile(fileName, languageVersion, onError, shouldCreate) {
46
+ const path = resolvePath(fileName);
47
+ const mtime = statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? -1;
48
+ const cached = sourceFiles.get(path);
49
+ if (cached && cached.mtime === mtime) return cached.file;
50
+ const file = base.getSourceFile(fileName, languageVersion, onError, shouldCreate);
51
+ if (file && mtime >= 0) sourceFiles.set(path, { mtime, file });
52
+ return file;
53
+ },
54
+ };
55
+ retained.set(key, { host, program: undefined as unknown as ts.Program });
56
+ return host;
57
+ }
58
+
59
+ function builtProgram(key: string, roots: readonly string[], options: ts.CompilerOptions): ts.Program {
60
+ const typescript = getTS();
61
+ const host = keptHost(key, options);
62
+ const program = typescript.createProgram({
63
+ rootNames: [...roots], options, host, oldProgram: retained.get(key)?.program,
64
+ });
65
+ retained.set(key, { host, program });
66
+ return program;
67
+ }
68
+
69
+ function compilerProjectOf(filePath: string, projectRoot?: string): { key: string; roots: string[]; options: ts.CompilerOptions } {
70
+ const typescript = getTS();
71
+ const absolute = resolvePath(filePath);
72
+ const configPath = typescript.findConfigFile(dirname(absolute), typescript.sys.fileExists);
73
+
74
+ if (configPath) {
75
+ const key = `${configPath}:${projectRoot ?? ''}`;
76
+ const cached = compilerProjects.get(key);
77
+ if (cached) return cached;
78
+
79
+ const read = typescript.readConfigFile(configPath, typescript.sys.readFile);
80
+ if (read.error) throw new Error(typescript.flattenDiagnosticMessageText(read.error.messageText, '\n'));
81
+ const parsed = typescript.parseJsonConfigFileContent(read.config, typescript.sys, dirname(configPath));
82
+ const configured = {
83
+ key,
84
+ // Compiler options belong to the project; its entire include glob does not belong
85
+ // to this scan. Each declaration inspected below becomes a root and TypeScript
86
+ // follows its imports. Seeding the monorepo here made a one-file scan compile it all.
87
+ roots: [],
88
+ // Handlers may be authored or emitted as JavaScript. They still need to belong to
89
+ // the checked program so constructor parsing does not fail on the first cold scan.
90
+ options: { ...parsed.options, allowJs: true, noEmit: true },
91
+ };
92
+ compilerProjects.set(key, configured);
93
+ return configured;
94
+ }
95
+
96
+ const key = projectRoot ?? dirname(absolute);
97
+ const cached = compilerProjects.get(key);
98
+ if (cached) return cached;
99
+ const configured = {
100
+ key,
101
+ roots: [],
102
+ options: {
103
+ target: typescript.ScriptTarget.ES2022,
104
+ module: typescript.ModuleKind.Node16,
105
+ moduleResolution: typescript.ModuleResolutionKind.Node16,
106
+ strict: true,
107
+ skipLibCheck: true,
108
+ allowJs: true,
109
+ noEmit: true,
110
+ },
111
+ };
112
+ compilerProjects.set(key, configured);
113
+ return configured;
114
+ }
115
+
116
+ /** Declare every file a run will read, so one program covers it. */
117
+ export async function seedTypeProgram(filePaths: readonly string[], projectRoot?: string): Promise<void> {
118
+ const typescript = await loadTS();
119
+ const grouped = new Map<string, { options: ts.CompilerOptions; paths: string[] }>();
120
+
121
+ for (const filePath of filePaths) {
122
+ const absolute = resolvePath(filePath);
123
+ const configured = compilerProjectOf(absolute, projectRoot);
124
+ const group = grouped.get(configured.key) ?? { options: configured.options, paths: [] };
125
+ group.paths.push(absolute);
126
+ grouped.set(configured.key, group);
127
+ }
128
+
129
+ for (const [key, { options, paths }] of grouped) {
130
+ const roots = new Set(typeProjects.get(key)?.roots ?? []);
131
+ for (const path of paths) roots.add(path);
132
+ typeProjects.set(key, { roots, options, program: builtProgram(key, [...roots], options) });
133
+ }
134
+ }
135
+
136
+ function checkedSourceOf(filePath: string, projectRoot?: string): { source: ts.SourceFile; checker: ts.TypeChecker } {
137
+ const typescript = getTS();
138
+ const absolute = resolvePath(filePath);
139
+ const configured = compilerProjectOf(absolute, projectRoot);
140
+ let project = typeProjects.get(configured.key);
141
+
142
+ if (!project) {
143
+ // `path.resolve` is variadic, so handing it directly to `map` also passed the
144
+ // index and the whole roots array as path segments. A fixture without a warm scan
145
+ // cache exposed that first-run-only failure.
146
+ const roots = new Set(configured.roots.map((root) => resolvePath(root)));
147
+ roots.add(absolute);
148
+ const program = builtProgram(configured.key, [...roots], configured.options);
149
+ project = { roots, options: configured.options, program };
150
+ typeProjects.set(configured.key, project);
151
+ } else if (!project.roots.has(absolute)) {
152
+ project.roots.add(absolute);
153
+ project.program = builtProgram(configured.key, [...project.roots], project.options);
154
+ }
155
+
156
+ const source = project.program.getSourceFile(absolute);
157
+ if (!source) throw new Error(`TypeScript did not include '${absolute}' in its program.`);
158
+ return { source, checker: project.program.getTypeChecker() };
159
+ }
160
+
161
+ /** A file, opened. Five places read and parsed one, each spelling the same two calls. */
162
+ function sourceOf(filePath: string): ts.SourceFile {
163
+ const ts = getTS();
164
+ return ts.createSourceFile(filePath, readFileSync(filePath, 'utf-8'), ts.ScriptTarget.Latest, true);
165
+ }
166
+
167
+ /** One declared parameter — a constructor's and a method's are read the same way. */
168
+ function parsedParam(param: ts.ParameterDeclaration, source: ts.SourceFile, checker?: ts.TypeChecker): Param {
169
+ const ts = getTS();
170
+ const type = param.type ? parseTypeNode(param.type, source, checker) : { raw: 'unknown', name: 'unknown' };
171
+ return {
172
+ name: ts.isIdentifier(param.name) ? param.name.text : param.name.getText(source),
173
+ type,
174
+ // `user?: User` and `user: User | undefined` are the same declaration of
175
+ // absence. A type alias may carry the latter, so only the checker can see it.
176
+ optional: param.questionToken !== undefined || param.initializer !== undefined || type.undefined === true,
177
+ };
178
+ }
179
+
180
+ /** Parse a TypeScript type node into a TypeRef. */
181
+ function parseTypeNode(node: ts.TypeNode, source: ts.SourceFile, checker?: ts.TypeChecker): TypeRef {
182
+ const ts = getTS();
183
+ const raw = node.getText(source);
184
+
185
+ if (checker) {
186
+ // `Fact<T>` is deliberately transparent in TypeScript (`type Fact<T> = T`), because
187
+ // a subscriber receives the payload itself. The checker erases that marker, while
188
+ // the binding plan still needs it to distinguish a fact from an ordinary body.
189
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.text === 'Fact') {
190
+ return {
191
+ raw,
192
+ name: 'Fact',
193
+ generics: node.typeArguments?.map((arg) => parseTypeNode(arg, source, checker)) ?? [],
194
+ };
195
+ }
196
+ return parseCheckedType(checker.getTypeFromTypeNode(node), raw, checker);
197
+ }
198
+
199
+ // Union types — extract nullable, strip Promise
200
+ if (ts.isUnionTypeNode(node)) {
201
+ const nonNull = node.types.filter(
202
+ (t) => !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword)
203
+ && !(t.kind === ts.SyntaxKind.UndefinedKeyword)
204
+ && !(t.kind === ts.SyntaxKind.VoidKeyword)
205
+ && !(t.kind === ts.SyntaxKind.NullKeyword),
206
+ );
207
+ const nullable = node.types.some((t) =>
208
+ (ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword)
209
+ || t.kind === ts.SyntaxKind.NullKeyword,
210
+ );
211
+ const undefinable = node.types.some((t) =>
212
+ t.kind === ts.SyntaxKind.UndefinedKeyword || t.kind === ts.SyntaxKind.VoidKeyword,
213
+ );
214
+ if (nonNull.length === 1) {
215
+ const inner = parseTypeNode(nonNull[0], source);
216
+ return { ...inner, nullable: nullable || inner.nullable, undefined: undefinable || inner.undefined, raw };
217
+ }
218
+ return { raw, name: raw, nullable, undefined: undefinable };
219
+ }
220
+
221
+ // Promise<T> — unwrap
222
+ if (ts.isTypeReferenceNode(node)) {
223
+ const typeName = node.typeName.getText(source);
224
+
225
+ if (typeName === 'Promise' && node.typeArguments?.length === 1) {
226
+ const inner = parseTypeNode(node.typeArguments[0], source);
227
+ return { ...inner, promise: true, raw };
228
+ }
229
+
230
+ // Array<T>
231
+ if (typeName === 'Array' && node.typeArguments?.length === 1) {
232
+ const inner = parseTypeNode(node.typeArguments[0], source);
233
+ return { ...inner, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1, raw };
234
+ }
235
+
236
+ // Generic type: Foo<Bar, Baz>
237
+ if (node.typeArguments && node.typeArguments.length > 0) {
238
+ const generics = node.typeArguments.map((arg) => parseTypeNode(arg, source));
239
+ return { raw, name: typeName, generics };
240
+ }
241
+
242
+ // Simple type reference: Post, string, etc.
243
+ return { raw, name: typeName };
244
+ }
245
+
246
+ // T[]
247
+ if (ts.isArrayTypeNode(node)) {
248
+ const inner = parseTypeNode(node.elementType, source);
249
+ return { ...inner, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1, raw };
250
+ }
251
+
252
+ // Keyword types: string, number, boolean, void
253
+ switch (node.kind) {
254
+ case ts.SyntaxKind.StringKeyword: return { raw, name: 'string' };
255
+ case ts.SyntaxKind.NumberKeyword: return { raw, name: 'number' };
256
+ case ts.SyntaxKind.BooleanKeyword: return { raw, name: 'boolean' };
257
+ case ts.SyntaxKind.VoidKeyword: return { raw, name: 'void', undefined: true };
258
+ case ts.SyntaxKind.UndefinedKeyword: return { raw, name: 'undefined', undefined: true };
259
+ case ts.SyntaxKind.NullKeyword: return { raw, name: 'null', nullable: true };
260
+ case ts.SyntaxKind.AnyKeyword: return { raw, name: 'any' };
261
+ case ts.SyntaxKind.UnknownKeyword: return { raw, name: 'unknown' };
262
+ }
263
+
264
+ // Object literal type: { title: string; limit: number }
265
+ if (ts.isTypeLiteralNode(node)) {
266
+ return { raw, name: raw };
267
+ }
268
+
269
+ // Fallback
270
+ return { raw, name: raw };
271
+ }
272
+
273
+ function meaningfulSymbolName(type: ts.Type, checker: ts.TypeChecker): string {
274
+ const typescript = getTS();
275
+ const symbol = type.aliasSymbol ?? type.getSymbol();
276
+ if (symbol && symbol.name !== 'default' && !symbol.name.startsWith('__')) return symbol.name;
277
+
278
+ for (const declaration of symbol?.declarations ?? []) {
279
+ if (
280
+ (typescript.isClassDeclaration(declaration)
281
+ || typescript.isInterfaceDeclaration(declaration)
282
+ || typescript.isTypeAliasDeclaration(declaration))
283
+ && declaration.name
284
+ ) return declaration.name.text;
285
+ }
286
+
287
+ return checker.typeToString(type, undefined, typescript.TypeFormatFlags.NoTruncation);
288
+ }
289
+
290
+ /** Turn a checked TypeScript type into the small, serializable vocabulary the runtime reads. */
291
+ function parseCheckedType(type: ts.Type, raw: string, checker: ts.TypeChecker, depth = 0): TypeRef {
292
+ const typescript = getTS();
293
+ if (depth > 12) return { raw, name: checker.typeToString(type) };
294
+
295
+ if (type.isUnion()) {
296
+ const nullable = type.types.some((member) => (member.flags & typescript.TypeFlags.Null) !== 0);
297
+ const undefinable = type.types.some((member) =>
298
+ (member.flags & (typescript.TypeFlags.Undefined | typescript.TypeFlags.Void)) !== 0,
299
+ );
300
+ const members = type.types.filter((member) =>
301
+ (member.flags & (typescript.TypeFlags.Null | typescript.TypeFlags.Undefined | typescript.TypeFlags.Void)) === 0,
302
+ );
303
+ // The checker represents the `boolean` keyword itself as `false | true`. Preserve
304
+ // the primitive vocabulary consumed by binding and presenter metadata.
305
+ if (
306
+ members.length > 0
307
+ && members.every((member) => (member.flags & typescript.TypeFlags.BooleanLiteral) !== 0)
308
+ ) {
309
+ return { raw, name: 'boolean', nullable, undefined: undefinable };
310
+ }
311
+ if (members.length === 1) {
312
+ const inner = parseCheckedType(members[0]!, raw, checker, depth + 1);
313
+ return {
314
+ ...inner,
315
+ raw,
316
+ nullable: nullable || inner.nullable,
317
+ undefined: undefinable || inner.undefined,
318
+ };
319
+ }
320
+ return {
321
+ raw,
322
+ name: members.map((member) => meaningfulSymbolName(member, checker)).join(' | ') || raw,
323
+ nullable,
324
+ undefined: undefinable,
325
+ };
326
+ }
327
+
328
+ // Present at runtime in the supported compiler versions, but intentionally omitted
329
+ // from TypeScript's public TypeChecker declaration.
330
+ const promised = (checker as ts.TypeChecker & {
331
+ getPromisedTypeOfPromise(candidate: ts.Type): ts.Type | undefined;
332
+ }).getPromisedTypeOfPromise(type);
333
+ if (promised) return { ...parseCheckedType(promised, raw, checker, depth + 1), raw, promise: true };
334
+
335
+ if (checker.isArrayType(type)) {
336
+ const [element] = checker.getTypeArguments(type as ts.TypeReference);
337
+ const inner = element ? parseCheckedType(element, raw, checker, depth + 1) : { raw, name: 'unknown' };
338
+ return { ...inner, raw, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1 };
339
+ }
340
+
341
+ if ((type.flags & typescript.TypeFlags.StringLike) !== 0) return { raw, name: 'string' };
342
+ if ((type.flags & typescript.TypeFlags.NumberLike) !== 0) return { raw, name: 'number' };
343
+ if ((type.flags & typescript.TypeFlags.BooleanLike) !== 0) return { raw, name: 'boolean' };
344
+ if ((type.flags & typescript.TypeFlags.Void) !== 0) return { raw, name: 'void', undefined: true };
345
+ if ((type.flags & typescript.TypeFlags.Undefined) !== 0) return { raw, name: 'undefined', undefined: true };
346
+ if ((type.flags & typescript.TypeFlags.Null) !== 0) return { raw, name: 'null', nullable: true };
347
+ if ((type.flags & typescript.TypeFlags.Any) !== 0) return { raw, name: 'any' };
348
+ if ((type.flags & typescript.TypeFlags.Unknown) !== 0) return { raw, name: 'unknown' };
349
+
350
+ const reference = type as ts.TypeReference;
351
+ // A declared alias such as `Emit<PostPublished>` may reduce to a function or object
352
+ // type, so it is no longer a TypeReference. The checker keeps its arguments beside
353
+ // `aliasSymbol`; losing them turns DI keys into bare `Emit`/`Facade`.
354
+ const args = (type as ts.Type & { aliasTypeArguments?: readonly ts.Type[] }).aliasTypeArguments
355
+ ?? checker.getTypeArguments(reference);
356
+ return {
357
+ raw,
358
+ name: meaningfulSymbolName(type, checker),
359
+ ...(args.length && { generics: args.map((arg) => parseCheckedType(arg, checker.typeToString(arg), checker, depth + 1)) }),
360
+ };
361
+ }
362
+
363
+ // ── Module resolution ────────────────────────
364
+
365
+ const TS_KEYWORDS = new Set([
366
+ 'string', 'number', 'boolean', 'void', 'undefined', 'null', 'any', 'unknown',
367
+ 'never', 'object', 'symbol', 'bigint',
368
+ ]);
369
+
370
+ /** Resolve an import specifier to an absolute file path. */
371
+ function resolveSpecifier(specifier: string, fromFile: string, projectRoot: string): string | undefined {
372
+ // Relative import
373
+ if (specifier.startsWith('.')) {
374
+ const dir = dirname(fromFile);
375
+ let resolved = resolvePath(dir, specifier);
376
+ // .js → .ts
377
+ if (resolved.endsWith('.js')) resolved = resolved.slice(0, -3) + '.ts';
378
+ if (!resolved.endsWith('.ts')) resolved += '.ts';
379
+ if (existsSync(resolved)) return resolved;
380
+ return undefined;
381
+ }
382
+
383
+ // Workspace package: @fougere/core → packages/core/src/index.ts
384
+ const match = specifier.match(/^@fougere\/([^/]+)$/);
385
+ if (match) {
386
+ const pkgDir = join(projectRoot, 'packages', match[1], 'src');
387
+ const indexPath = join(pkgDir, 'index.ts');
388
+ if (existsSync(indexPath)) return indexPath;
389
+ }
390
+
391
+ return undefined;
392
+ }
393
+
394
+ // ── Mixin / heritage parsing ─────────────────
395
+
396
+ /** The class a returned expression carries, however it is wrapped. */
397
+ function classInExpression(expr: ts.Node, depth = 0): ts.ClassExpression | undefined {
398
+ const ts = getTS();
399
+ if (depth > 8) return undefined;
400
+ if (ts.isClassExpression(expr)) return expr;
401
+ if (ts.isCallExpression(expr)) {
402
+ for (const arg of expr.arguments) {
403
+ const found = classInExpression(arg, depth + 1);
404
+ if (found) return found;
405
+ }
406
+ return undefined;
407
+ }
408
+ if (ts.isAsExpression(expr) || ts.isSatisfiesExpression(expr) || ts.isParenthesizedExpression(expr)) {
409
+ return classInExpression(expr.expression, depth + 1);
410
+ }
411
+ return undefined;
412
+ }
413
+
414
+ /** Find a class declaration inside a function (mixin pattern). */
415
+ function findClassInFunction(source: ts.SourceFile, functionName: string): ts.ClassDeclaration | ts.ClassExpression | undefined {
416
+ const ts = getTS();
417
+ for (const stmt of source.statements) {
418
+ if (!ts.isFunctionDeclaration(stmt)) continue;
419
+ if (stmt.name?.text !== functionName) continue;
420
+ if (!stmt.body) continue;
421
+
422
+ // Walk statements inside the function
423
+ for (const inner of stmt.body.statements) {
424
+ // return class CrudHandler { … }, or the same class behind a wrapper
425
+ if (ts.isReturnStatement(inner) && inner.expression) {
426
+ const found = classInExpression(inner.expression);
427
+ if (found) return found;
428
+ }
429
+ // class CrudHandler { ... } (followed by return)
430
+ if (ts.isClassDeclaration(inner)) return inner;
431
+ }
432
+ }
433
+ return undefined;
434
+ }
435
+
436
+ /**
437
+ * Extract methods from a class node (no file reading — works on already-parsed AST).
438
+ */
439
+ function extractClassMethods(
440
+ cls: ts.ClassDeclaration | ts.ClassExpression,
441
+ source: ts.SourceFile,
442
+ skip: Set<string>,
443
+ checker?: ts.TypeChecker,
444
+ ): Signature[] {
445
+ const ts = getTS();
446
+ const results: Signature[] = [];
447
+
448
+ for (const member of cls.members) {
449
+ if (!ts.isMethodDeclaration(member)) continue;
450
+ if (!member.name || !ts.isIdentifier(member.name)) continue;
451
+ // `private`/`protected` is a statement about the surface, and the AST carries it —
452
+ // it was read past. Every helper a handler names by intent (`mustOwn`, `readMany`,
453
+ // `refuse`) became a callable op: measured on the bench, `list.readMany` executed
454
+ // and `list.mayPublish` validated its argument. A door is what the author declares
455
+ // public, and TypeScript already has the word for it. `#name` is private too, but
456
+ // it is not an identifier, so it never reached here in the first place.
457
+ if (member.modifiers?.some((m) => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword)) continue;
458
+
459
+ const name = member.name.text;
460
+ if (skip.has(name)) continue;
461
+
462
+ const params = member.parameters.map((p) => parsedParam(p, source, checker));
463
+ const returnType = member.type ? parseTypeNode(member.type, source, checker) : undefined;
464
+ results.push({
465
+ name, params, returnType,
466
+ description: docSentenceOf(member, source),
467
+ });
468
+ }
469
+
470
+ return results;
471
+ }
472
+
473
+ /** The first sentence of a member's doc comment, or nothing. */
474
+ function docSentenceOf(member: ts.Node, source: ts.SourceFile): string | undefined {
475
+ const ts = getTS();
476
+ const ranges = ts.getLeadingCommentRanges(source.text, member.pos) ?? [];
477
+ const block = ranges.filter((r) => source.text.slice(r.pos, r.pos + 3) === '/**').pop();
478
+ if (!block) return undefined;
479
+
480
+ const body = source.text
481
+ .slice(block.pos + 3, block.end - 2)
482
+ .split('\n')
483
+ .map((line) => line.replace(/^\s*\*/, '').trim())
484
+ .join(' ')
485
+ .trim();
486
+
487
+ const [sentence] = body.split(/(?<=\.)\s/);
488
+
489
+ return sentence?.trim() || undefined;
490
+ }
491
+
492
+ /**
493
+ * Parse inherited methods from a class's heritage clause.
494
+ * Handles both `extends Crud(Entity)` (mixin) and `extends BaseClass` patterns.
495
+ */
496
+ /** Where a name used here is declared. */
497
+ function declarationFileOf(node: ts.Node, checker: ts.TypeChecker): string | undefined {
498
+ const typescript = getTS();
499
+ let symbol = checker.getSymbolAtLocation(node);
500
+ if (!symbol) return undefined;
501
+ if (symbol.flags & typescript.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
502
+ return symbol.declarations?.[0]?.getSourceFile().fileName;
503
+ }
504
+
505
+ /** The methods a base class contributes, read from the INSTANTIATED type. */
506
+ function inheritedFromBase(
507
+ base: ts.ExpressionWithTypeArguments,
508
+ checker: ts.TypeChecker,
509
+ skip: Set<string>,
510
+ ): Signature[] {
511
+ const typescript = getTS();
512
+ const results: Signature[] = [];
513
+
514
+ for (const property of checker.getPropertiesOfType(checker.getTypeAtLocation(base))) {
515
+ if (skip.has(property.name)) continue;
516
+
517
+ // `private`/`protected` is a statement about the surface, and the declaration carries
518
+ // it. A door is what the author declares public.
519
+ const declaration = property.declarations?.[0];
520
+ if (declaration && typescript.canHaveModifiers(declaration)
521
+ && typescript.getModifiers(declaration)?.some((m) => m.kind === typescript.SyntaxKind.PrivateKeyword
522
+ || m.kind === typescript.SyntaxKind.ProtectedKeyword)) continue;
523
+
524
+ const signature = checker.getTypeOfSymbolAtLocation(property, base).getCallSignatures()[0];
525
+ if (!signature) continue;
526
+
527
+ const returned = signature.getReturnType();
528
+ const sentence = typescript.displayPartsToString(property.getDocumentationComment(checker)).trim();
529
+ results.push({
530
+ name: property.name,
531
+ params: signature.getParameters().map((parameter) => {
532
+ const type = checker.getTypeOfSymbolAtLocation(parameter, base);
533
+ return {
534
+ name: parameter.name,
535
+ type: parseCheckedType(type, checker.typeToString(type), checker),
536
+ optional: (parameter.flags & typescript.SymbolFlags.Optional) !== 0,
537
+ };
538
+ }),
539
+ returnType: parseCheckedType(returned, checker.typeToString(returned), checker),
540
+ ...(sentence ? { description: sentence.split(/(?<=\.)\s/)[0] } : {}),
541
+ });
542
+ }
543
+ return results;
544
+ }
545
+
546
+ function parseInheritedMethods(
547
+ cls: ts.ClassDeclaration,
548
+ source: ts.SourceFile,
549
+ checker: ts.TypeChecker,
550
+ skip: Set<string>,
551
+ /**
552
+ * Base classes this pass could not open — an INSTALLED one, typically, whose source is not in
553
+ * the workspace.
554
+ */
555
+ unresolved: string[],
556
+ ): Signature[] {
557
+ const ts = getTS();
558
+ if (!cls.heritageClauses) return [];
559
+
560
+ for (const clause of cls.heritageClauses) {
561
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword) continue;
562
+
563
+ for (const base of clause.types) {
564
+ const fromType = inheritedFromBase(base, checker, skip);
565
+ if (fromType.length > 0) return fromType;
566
+
567
+ // A factory that ERASES its own type — `assertShape<unknown>(class …)`, `as unknown`
568
+ // — leaves the checker with nothing to enumerate. The written class is still there,
569
+ // so read it. This is the one case where what the author wrote beats what it means.
570
+ const expression = base.expression;
571
+ const declared = ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)
572
+ ? declarationFileOf(expression.expression, checker)
573
+ : ts.isIdentifier(expression) ? declarationFileOf(expression, checker) : undefined;
574
+ if (!declared) { unresolved.push(expression.getText(source)); continue; }
575
+
576
+ const declaredSource = sourceOf(declared);
577
+ const written = ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)
578
+ ? findClassInFunction(declaredSource, expression.expression.text)
579
+ : findDefaultClass(declaredSource);
580
+ if (!written) { unresolved.push(expression.getText(source)); continue; }
581
+
582
+ return extractClassMethods(written, declaredSource, skip);
583
+ }
584
+ }
585
+
586
+ return [];
587
+ }
588
+
589
+ // ── Class finding ────────────────────────────
590
+
591
+ /** Find the default exported class in a source file. */
592
+ function findDefaultClass(source: ts.SourceFile): ts.ClassDeclaration | undefined {
593
+ const ts = getTS();
594
+ for (const stmt of source.statements) {
595
+ // export default class Foo { ... }
596
+ if (ts.isClassDeclaration(stmt) && stmt.modifiers?.some(
597
+ (m) => m.kind === ts.SyntaxKind.ExportKeyword,
598
+ ) && stmt.modifiers?.some(
599
+ (m) => m.kind === ts.SyntaxKind.DefaultKeyword,
600
+ )) {
601
+ return stmt;
602
+ }
603
+ }
604
+
605
+ // export default Foo (separate statement) — find the class it points to
606
+ for (const stmt of source.statements) {
607
+ if (ts.isExportAssignment(stmt) && !stmt.isExportEquals && ts.isIdentifier(stmt.expression)) {
608
+ const name = stmt.expression.text;
609
+ for (const s of source.statements) {
610
+ if (ts.isClassDeclaration(s) && s.name?.text === name) return s;
611
+ }
612
+ }
613
+ }
614
+
615
+ return undefined;
616
+ }
617
+
618
+ /** What a handler file yielded — its methods, AND what the pass could not open. */
619
+ export interface HandlerParse {
620
+ methods: Signature[];
621
+ /** Base classes whose source this pass could not open. Empty is a claim. */
622
+ unresolvedHeritage: string[];
623
+ }
624
+
625
+ /**
626
+ * Every method a handler declares, its inherited ones included — the raw material of a
627
+ * binding plan. With a `projectRoot`, the heritage clause is followed too.
628
+ */
629
+ export async function parseAllHandlerMethods(filePath: string, projectRoot?: string): Promise<HandlerParse> {
630
+ await loadTS();
631
+ return parseClassMethods(filePath, CONSTRUCTOR_ONLY, projectRoot);
632
+ }
633
+
634
+ /** Parse a presenter source file and extract all method signatures. */
635
+ export async function parsePresenterMethods(filePath: string, projectRoot?: string): Promise<Signature[]> {
636
+ await loadTS();
637
+ // No `projectRoot`, so no heritage pass and nothing to report: a presenter's
638
+ // computed fields are its own methods.
639
+ return parseClassMethods(filePath, CONSTRUCTOR_ONLY, undefined, projectRoot).methods;
640
+ }
641
+
642
+ /**
643
+ * Parse constructor parameter types from a source file's default class.
644
+ * Returns type names (e.g. ['PostStorage', 'Logger']) for DI resolution.
645
+ */
646
+ export async function parseConstructorParams(filePath: string, projectRoot?: string): Promise<Param[]> {
647
+ const ts = await loadTS();
648
+ const { source, checker } = checkedSourceOf(filePath, projectRoot);
649
+ const cls = findDefaultClass(source);
650
+ if (!cls) return [];
651
+
652
+ const ctor = cls.members.find(ts.isConstructorDeclaration);
653
+ return ctor ? ctor.parameters.map((p) => parsedParam(p, source, checker)) : [];
654
+ }
655
+
656
+ const CONSTRUCTOR_ONLY = new Set(['constructor']);
657
+
658
+ function parseClassMethods(
659
+ filePath: string,
660
+ skip: Set<string>,
661
+ heritageRoot?: string,
662
+ typeRoot: string | undefined = heritageRoot,
663
+ ): HandlerParse {
664
+ const unresolved: string[] = [];
665
+ const { source, checker } = checkedSourceOf(filePath, typeRoot);
666
+ const cls = findDefaultClass(source);
667
+ if (!cls) return { methods: [], unresolvedHeritage: unresolved };
668
+
669
+ const childMethods = extractClassMethods(cls, source, skip, checker);
670
+ const childNames = new Set(childMethods.map((m) => m.name));
671
+
672
+ // Parse inherited methods (if projectRoot is provided for resolution)
673
+ if (heritageRoot) {
674
+ const inherited = parseInheritedMethods(cls, source, checker, skip, unresolved);
675
+ // Merge: child methods win over inherited
676
+ const parentOnly = inherited
677
+ .filter((m) => !childNames.has(m.name))
678
+ .map((m) => ({ ...m, inherited: true }));
679
+ return { methods: [...childMethods, ...parentOnly], unresolvedHeritage: unresolved };
680
+ }
681
+
682
+ return { methods: childMethods, unresolvedHeritage: unresolved };
683
+ }