import path from 'node:path'; import ts from 'typescript'; import { readProgram, unwrap, type Diagnostic } from './check.js'; export interface GeneratedInjects { /** The generated file's contents. */ readonly source: string; /** Classes whose dependency lists were inferred. */ readonly classes: readonly string[]; readonly diagnostics: readonly Diagnostic[]; } export interface GenerateInjectsOptions { /** Path to tsconfig.json. */ readonly project: string; /** Where the file will be written; imports are relative to it. */ readonly out: string; } /** How every file `avi inject` writes begins. */ export const INJECT_HEADER = '// Generated by `avi inject`'; /** * Infers the dependency lists of classes that have constructor parameters but no `static inject`, * from the parameters' types, and generates a file that registers them with `registerInjects`. * Only class types and config tokens (`TokenType`) can be inferred; a class with * other parameter types gets a warning and keeps needing `static inject`. */ export function generateInjects(options: GenerateInjectsOptions): GeneratedInjects { const { program, roots } = readProgram(options.project); return generateInjectsFrom(program, roots, options); } /** `generateInjects` on a program that is already built, such as the watcher's. */ export function generateInjectsFrom( program: ts.Program, roots: ReadonlySet, options: Pick, ): GeneratedInjects { return new InjectGenerator(program, roots, path.resolve(options.out)).run(); } interface Import { readonly specifier: string; readonly name: string; alias: string; } class InjectGenerator { readonly #checker: ts.TypeChecker; readonly #imports = new Map(); readonly #diagnostics: Diagnostic[] = []; readonly #entries: { cls: string; deps: string[]; order: string }[] = []; constructor( private readonly program: ts.Program, private readonly roots: ReadonlySet, private readonly out: string, ) { this.#checker = program.getTypeChecker(); } run(): GeneratedInjects { const needsDev = this.#devReasons(devOnlyPackages(this.program)); const own = (source: ts.SourceFile) => this.#inProject(source); const unsafe = (source: ts.SourceFile): string | undefined => runsCode(source, this.#checker, own) ? 'runs code when imported (an entry point or a script)' : needsDev.get(path.resolve(source.fileName)); for (const source of this.program.getSourceFiles()) { if (!this.#inProject(source) || path.resolve(source.fileName) === this.out) continue; // Test files are not loaded by the app, and the generated file must not import them. if (/\.(test|spec)\.[cm]?tsx?$/.test(source.fileName)) continue; const classes = source.statements.filter(ts.isClassDeclaration); if (classes.length === 0) continue; // Importing a file runs its top level. Only import files that just declare things: never an // entry point, a worker or a seed script, and nothing a production install may lack. const reason = unsafe(source); for (const node of classes) this.#class(node, source, reason); } this.#entries.sort((a, b) => a.order.localeCompare(b.order)); // Packages first, then the app's own files, each in order. const rank = (specifier: string) => `${specifier.startsWith('.') ? '1' : '0'}${specifier}`; const imports = [...this.#imports.values()].sort((a, b) => a.specifier === b.specifier ? a.alias.localeCompare(b.alias) : rank(a.specifier).localeCompare(rank(b.specifier)), ); const bySpecifier = new Map(); for (const item of imports) { const binding = item.alias === item.name ? item.name : `${item.name} as ${item.alias}`; bySpecifier.set(item.specifier, [...(bySpecifier.get(item.specifier) ?? []), binding]); } const lines = [ `${INJECT_HEADER}; \`avi dev\` and \`avi build\` keep it up to date. Do not edit.`, '// Dependency lists inferred from constructor types. A `static inject` in a class wins.', "import { registerInjects } from '@avijs/core';", ...[...bySpecifier].map( ([specifier, names]) => `import { ${names.join(', ')} } from '${specifier}';`, ), '', // A function, read when the app starts: classes in an import cycle with this file exist by then. this.#entries.length === 0 ? 'registerInjects(() => []);' : [ 'registerInjects(() => [', ...this.#entries.map((e) => ` [${e.cls}, [${e.deps.join(', ')}]],`), ']);', ].join('\n'), '', ]; const diagnostics = this.#diagnostics.sort((a, b) => a.file === b.file ? a.line - b.line || a.column - b.column : a.file.localeCompare(b.file), ); return { source: lines.join('\n'), classes: this.#entries.map((e) => e.cls), diagnostics, }; } #class(node: ts.ClassDeclaration, source: ts.SourceFile, unsafe: string | undefined): void { if (!node.name) return; const hasList = node.members.some( (member) => ts.isPropertyDeclaration(member) && (ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static) !== 0 && member.name.getText(source) === 'inject', ); if (hasList) return; const ctor = node.members.find( (member): member is ts.ConstructorDeclaration => ts.isConstructorDeclaration(member) && member.body !== undefined, ); if (!ctor) return; // Like constructor.length: optional, defaulted and rest parameters are left out. const optional = ctor.parameters.findIndex( (p) => p.questionToken !== undefined || p.initializer !== undefined || p.dotDotDotToken !== undefined, ); const required = optional === -1 ? [...ctor.parameters] : ctor.parameters.slice(0, optional); if (required.length === 0) return; const tokens = required.map((param) => this.#token(param, source)); const resolved = tokens.filter((token): token is string => token !== undefined); if (resolved.length < tokens.length) { // A class none of whose parameters are injectable is not a DI class: say nothing. if (resolved.length === 0 && !isDecorated(node)) return; const param = required[tokens.findIndex((token) => token === undefined)]; const which = param ? `\`${param.name.getText(source)}\`` : 'a parameter'; this.#report( source, param ?? ctor, `Cannot infer what to inject for ${which} of ${node.name.text}: only classes and tokens named like their type can be inferred; add static inject`, ); return; } if (unsafe) { this.#report( source, node.name, `${node.name.text} is in a file that ${unsafe}, so inject.gen.ts cannot import it: move the class to its own file, or add static inject`, 'AVI203', ); return; } const cls = this.#importClass(node, source); if (!cls) return; this.#entries.push({ cls, deps: resolved, order: `${path.resolve(source.fileName)}#${node.name.text}`, }); } /** The local name of the token a parameter needs, or undefined when it cannot be inferred. */ #token(param: ts.ParameterDeclaration, source: ts.SourceFile): string | undefined { if (param.dotDotDotToken || !param.type || !ts.isTypeReferenceNode(param.type)) return; if (param.type.typeArguments?.length) return; let symbol = this.#checker.getSymbolAtLocation(param.type.typeName); if (!symbol) return; if (symbol.flags & ts.SymbolFlags.Alias) symbol = this.#checker.getAliasedSymbol(symbol); // `type Cfg = TokenType`: the token is the value behind typeof. const alias = symbol.declarations?.find(ts.isTypeAliasDeclaration); const target = alias && configTarget(alias.type); if (target) { const valueSymbol = this.#checker.getSymbolAtLocation(target); const value = valueSymbol && valueSymbol.flags & ts.SymbolFlags.Alias ? this.#checker.getAliasedSymbol(valueSymbol) : valueSymbol; const declaration = value?.valueDeclaration; if (!value || !declaration) return; return this.#importValue(value, declaration, param.type.typeName, source); } // A class, or a value named like the type that can be a token: Prisma's `PrismaClient` (a // constructor and a type), or `createToken()` next to `interface Db`. if (!(symbol.flags & ts.SymbolFlags.Value) || !this.#canBeToken(symbol)) return; const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0]; if (!declaration) return; return this.#importValue(symbol, declaration, param.type.typeName, source); } /** A class, a constructor, or a token made by `createToken` or `defineConfig`. */ #canBeToken(symbol: ts.Symbol): boolean { if (symbol.flags & ts.SymbolFlags.Class) return true; const declaration = symbol.valueDeclaration; if (!declaration) return false; const type = this.#checker.getTypeOfSymbolAtLocation(symbol, declaration); if (type.getConstructSignatures().length > 0) return true; if (!ts.isVariableDeclaration(declaration) || !declaration.initializer) return false; const call = unwrap(declaration.initializer); if (!call || !ts.isCallExpression(call)) return false; const callee = ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : ts.isIdentifier(call.expression) ? call.expression.text : undefined; return callee === 'createToken' || callee === 'defineConfig'; } #importClass(node: ts.ClassDeclaration, source: ts.SourceFile): string | undefined { const symbol = node.name && this.#checker.getSymbolAtLocation(node.name); const name = symbol && this.#exportName(symbol, source); if (!symbol || !name) { this.#report( source, node.name ?? node, `Export ${node.name?.text ?? 'this class'} so its dependency list can be registered, or add static inject`, ); return undefined; } return this.#add(this.#specifier(source.fileName), name); } /** Imports a token for the generated file: from its file in the project, or as the class imports it. */ #importValue( symbol: ts.Symbol, declaration: ts.Declaration, usedAt: ts.EntityName, from: ts.SourceFile, ): string | undefined { const file = declaration.getSourceFile(); if (this.#inProject(file)) { const name = this.#exportName(symbol, file); return name ? this.#add(this.#specifier(file.fileName), name) : undefined; } // A library class, such as PrismaClient: import it the way the class's file does. const local = ts.isQualifiedName(usedAt) ? undefined : usedAt.text; for (const statement of from.statements) { if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue; const bindings = statement.importClause?.namedBindings; if (!bindings || !ts.isNamedImports(bindings)) continue; for (const element of bindings.elements) { if (element.name.text !== local) continue; const specifier = statement.moduleSpecifier.text; if (specifier.startsWith('.')) return undefined; // a relative path outside the project return this.#add(specifier, (element.propertyName ?? element.name).text); } } return undefined; } #exportName(symbol: ts.Symbol, file: ts.SourceFile): string | undefined { const moduleSymbol = this.#checker.getSymbolAtLocation(file); if (!moduleSymbol) return undefined; for (const exported of this.#checker.getExportsOfModule(moduleSymbol)) { const target = exported.flags & ts.SymbolFlags.Alias ? this.#checker.getAliasedSymbol(exported) : exported; if (target === symbol) return exported.name; } return undefined; } #add(specifier: string, name: string): string { const key = `${specifier}#${name}`; const existing = this.#imports.get(key); if (existing) return existing.alias; const taken = new Set([...this.#imports.values()].map((i) => i.alias)); let alias = name === 'default' ? 'Default' : name; for (let n = 2; taken.has(alias) || alias === 'registerInjects'; n++) { alias = `${name}_${String(n)}`; } this.#imports.set(key, { specifier, name, alias }); return alias; } #specifier(file: string): string { let relative = path.relative(path.dirname(this.out), file).split(path.sep).join('/'); if (!relative.startsWith('.')) relative = `./${relative}`; return relative.replace(/\.(m|c)?tsx?$/, (_, kind: string | undefined) => `.${kind ?? ''}js`); } #inProject(source: ts.SourceFile): boolean { return !source.isDeclarationFile && this.roots.has(path.resolve(source.fileName)); } /** * Why each project file needs a devDependency: it imports one, or imports a project file that * does. Code that runs in an imported file is fine: the app loads that file anyway. */ #devReasons(devOnly: ReadonlySet): Map { const options = this.program.getCompilerOptions(); const cache = ts.createModuleResolutionCache( this.program.getCurrentDirectory(), (file) => (ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase()), options, ); const reasons = new Map(); const importers = new Map(); const queue: string[] = []; for (const source of this.program.getSourceFiles()) { const file = path.resolve(source.fileName); if (!this.#inProject(source) || file === this.out) continue; const direct = importsDevOnly(source, devOnly); if (direct) { reasons.set(file, direct); queue.push(file); } // Relative imports, `paths` aliases and `#imports` alike: whatever resolves to a project // file. Each is resolved as the file loads it: `import` or `require` conditions. for (const literal of runtimeSpecifiers(source)) { const mode = ts.getModeForUsageLocation(source, literal, options); const resolved = ts.resolveModuleName( literal.text, source.fileName, options, ts.sys, cache, undefined, mode, ).resolvedModule?.resolvedFileName; const target = resolved && this.program.getSourceFile(resolved); if (!target || !this.#inProject(target)) continue; const to = path.resolve(target.fileName); if (to === this.out) continue; const list = importers.get(to); const edge = { file, specifier: literal.text }; if (list) list.push(edge); else importers.set(to, [edge]); } } // Breadth first, so import cycles end and the shortest chain is the one named. // A for-of also visits what the loop appends. for (const file of queue) { const reason = reasons.get(file) as string; for (const { file: by, specifier } of importers.get(file) ?? []) { if (reasons.has(by)) continue; reasons.set(by, `imports ${specifier}, which ${reason}`); queue.push(by); } } return reasons; } #report(source: ts.SourceFile, at: ts.Node, message: string, code = 'AVI201'): void { const { line, character } = source.getLineAndCharacterOfPosition(at.getStart(source)); this.#diagnostics.push({ file: source.fileName, line: line + 1, column: character + 1, severity: 'warning', code, message, }); } } /** `X` in `TokenType`. */ function configTarget(type: ts.TypeNode): ts.EntityName | undefined { if (!ts.isTypeReferenceNode(type) || type.typeArguments?.length !== 1) return undefined; const name = ts.isIdentifier(type.typeName) ? type.typeName.text : type.typeName.right.text; const arg = type.typeArguments[0]; if (name !== 'TokenType' || !arg || !ts.isTypeQueryNode(arg)) return undefined; return arg.exprName; } function isDecorated(node: ts.ClassDeclaration): boolean { return (ts.getDecorators(node) ?? []).length > 0; } // Functions that start a worker, a cluster or a timer, by the module they are imported from. const STARTERS: Record = { runWorker: /^@avijs\//, cluster: /^@avijs\//, setInterval: /^(node:)?timers/, setTimeout: /^(node:)?timers/, }; /** * Whether a call or `new` starts something: a server's `listen`, a worker, a cluster, a timer. * A function or method the project defines itself, such as an event bus's `listen`, does not. */ function starts(node: ts.Node, checker: ts.TypeChecker, own: Own): boolean { if (ts.isNewExpression(node)) { const callee = node.expression; return ( (ts.isIdentifier(callee) && callee.text === 'Worker') || (ts.isPropertyAccessExpression(callee) && callee.name.text === 'Worker') ); } if (!ts.isCallExpression(node)) return false; const callee = node.expression; if (ts.isPropertyAccessExpression(callee)) { // `workers.cluster(...)` through `import * as workers`. const namespace = ts.isIdentifier(callee.expression) ? origin(callee.expression, checker, callee.name.text) : undefined; const from = STARTERS[callee.name.text]; if (namespace?.name === '*' && from && namespace.modules.some((m) => from.test(m))) { return true; } return callee.name.text === 'listen' && !definedByProject(callee.name, checker, own); } if (!ts.isIdentifier(callee)) return false; const imported = origin(callee, checker); if (imported) { const from = STARTERS[imported.name]; return from !== undefined && imported.modules.some((m) => from.test(m)); } // A global such as setInterval, or a name nothing declares. return STARTERS[callee.text] !== undefined && !definedByProject(callee, checker, own); } /** * Where an imported name comes from: its name there (`*` for a namespace) and every module on the * way, following re-exports through the project's own files. `member` is the name used on a * namespace, to follow `export *` from its module. */ function origin( id: ts.Identifier, checker: ts.TypeChecker, member?: string, ): { name: string; modules: string[] } | undefined { let symbol = checker.getSymbolAtLocation(id); let name = id.text; const modules: string[] = []; for (let hops = 0; symbol && hops < 20; hops++) { const d = symbol.declarations?.[0]; let specifier: ts.Expression | undefined; if (d && ts.isImportSpecifier(d)) { name = (d.propertyName ?? d.name).text; specifier = d.parent.parent.parent.moduleSpecifier; } else if (d && ts.isExportSpecifier(d)) { name = (d.propertyName ?? d.name).text; specifier = d.parent.parent.moduleSpecifier; } else if (d && ts.isNamespaceImport(d)) { name = '*'; specifier = d.parent.parent.moduleSpecifier; } else if (d && ts.isNamespaceExport(d)) { name = '*'; specifier = d.parent.moduleSpecifier; } else { break; } if (specifier && ts.isStringLiteral(specifier)) { modules.push(specifier.text); const exported = name === '*' ? member : name; if (exported) modules.push(...throughStars(specifier, exported, checker, new Set())); } if ((symbol.flags & ts.SymbolFlags.Alias) === 0) break; symbol = checker.getImmediateAliasedSymbol(symbol); } return modules.length > 0 ? { name, modules } : undefined; } /** The modules a name comes through when a module re-exports it with `export * from`. */ function throughStars( specifier: ts.StringLiteral, name: string, checker: ts.TypeChecker, seen: Set, ): string[] { const module = checker.getSymbolAtLocation(specifier); if (!module || seen.has(module)) return []; seen.add(module); // Declared or re-exported by name: the alias chain continues from there. if (module.exports?.has(ts.escapeLeadingUnderscores(name))) return []; for (const declaration of module.declarations ?? []) { if (!ts.isSourceFile(declaration)) continue; for (const statement of declaration.statements) { if (!ts.isExportDeclaration(statement) || statement.exportClause) continue; const from = statement.moduleSpecifier; if (!from || !ts.isStringLiteral(from)) continue; const target = checker.getSymbolAtLocation(from); if (!target || !checker.tryGetMemberInModuleExports(name, target)) continue; return [from.text, ...throughStars(from, name, checker, seen)]; } } return []; } type Own = (source: ts.SourceFile) => boolean; /** * Declared in the project's own code, as opposed to a library, a global or a `declare`. An * interface of the project counts: its `listen` is usually an event bus the project implements. */ function definedByProject(name: ts.Node, checker: ts.TypeChecker, own: Own): boolean { const declarations = checker.getSymbolAtLocation(name)?.declarations ?? []; return ( declarations.length > 0 && declarations.every((d) => own(d.getSourceFile()) && !isAmbient(d)) ); } /** Inside a `declare`: a type only, with no code behind it in this project. */ function isAmbient(node: ts.Node): boolean { let current = node; while (!ts.isSourceFile(current)) { const modifiers = ts.canHaveModifiers(current) ? ts.getModifiers(current) : undefined; if (modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword)) return true; current = current.parent; } return false; } /** * Whether a file does more than declare things when imported: a call statement, a loop, a * top-level await, or a value that starts a server, worker or timer. */ function runsCode(source: ts.SourceFile, checker: ts.TypeChecker, own: Own): boolean { const awaits = (node: ts.Node): boolean => ts.isAwaitExpression(node) || starts(node, checker, own) || (!ts.isFunctionLike(node) && !ts.isClassLike(node) && ts.forEachChild(node, awaits) === true); return source.statements.some((statement) => { if ( ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement) || ts.isExportDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement) || ts.isEmptyStatement(statement) ) { return false; } if (ts.isVariableStatement(statement) || ts.isExportAssignment(statement)) { return awaits(statement); } // 'use strict' and other directives. if (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) return false; return true; }); } /** Packages the project only has as devDependencies, from the package.json next to its tsconfig. */ function devOnlyPackages(program: ts.Program): Set { const config = program.getCompilerOptions()['configFilePath']; let dir = typeof config === 'string' ? path.dirname(config) : program.getCurrentDirectory(); for (;;) { const file = path.join(dir, 'package.json'); if (ts.sys.fileExists(file)) { try { const pkg = JSON.parse(ts.sys.readFile(file) ?? '{}') as Record< string, Record | undefined >; const runtime = new Set([ ...Object.keys(pkg['dependencies'] ?? {}), ...Object.keys(pkg['peerDependencies'] ?? {}), ...Object.keys(pkg['optionalDependencies'] ?? {}), ]); return new Set( Object.keys(pkg['devDependencies'] ?? {}).filter((name) => !runtime.has(name)), ); } catch { return new Set(); } } const parent = path.dirname(dir); if (parent === dir) return new Set(); dir = parent; } } /** Why a file cannot be imported in production: it imports a package from devDependencies. */ function importsDevOnly(source: ts.SourceFile, devOnly: ReadonlySet): string | undefined { for (const { text: specifier } of runtimeSpecifiers(source)) { const name = specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]; if (name && devOnly.has(name)) return `imports ${name}, a devDependency`; } return undefined; } /** Modules a file loads at runtime: imports and re-exports, without type-only ones. */ function runtimeSpecifiers(source: ts.SourceFile): ts.StringLiteral[] { const specifiers: ts.StringLiteral[] = []; for (const statement of source.statements) { if (ts.isImportDeclaration(statement)) { const clause = statement.importClause; // Type-only imports are erased. if (clause && (clause.getText(source).startsWith('type ') || isTypeOnlyClause(clause))) { continue; } } else if (ts.isExportDeclaration(statement)) { const named = statement.exportClause; if (statement.isTypeOnly) continue; if (named && ts.isNamedExports(named) && named.elements.length > 0) { if (named.elements.every((element) => element.isTypeOnly)) continue; } } else { continue; } if (statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) { specifiers.push(statement.moduleSpecifier); } } return specifiers; } function isTypeOnlyClause(clause: ts.ImportClause): boolean { const named = clause.namedBindings; return ( clause.name === undefined && named !== undefined && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly) ); } export const plural = (count: number, noun: string): string => `${String(count)} ${noun}${count === 1 ? '' : 's'}`;