|
| 1 | +import { execFile as executeFile } from 'node:child_process'; |
| 2 | +import { existsSync } from 'node:fs'; |
| 3 | +import { createRequire } from 'node:module'; |
| 4 | +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; |
| 5 | +import { promisify } from 'node:util'; |
| 6 | + |
| 7 | +import type { Diagnostic } from '../core/diagnostics.ts'; |
| 8 | + |
| 9 | +const execFile = promisify(executeFile); |
| 10 | + |
| 11 | +/** |
| 12 | + * Declaration generation rides rsbuild-plugin-dts, which aborts a failed pass |
| 13 | + * with one prose line naming only the Rslib environment — the TypeScript |
| 14 | + * diagnostics that actually failed the emit stay inside the forked worker. |
| 15 | + * This module recovers them by replaying declaration emit over the very |
| 16 | + * tsconfig the failed build used, so the CLI reports the file, line, and TS |
| 17 | + * code instead of a catch-all. |
| 18 | + * |
| 19 | + * `AB4716` joins the `AB471x` package-build `lib` family (see |
| 20 | + * `docs/diagnostics.md`); it is never `AB5000`, whose dev-lock meaning |
| 21 | + * misdirected triage of exactly this failure. |
| 22 | + */ |
| 23 | +export const declarationBuildCode = 'AB4716'; |
| 24 | + |
| 25 | +const emitOnlyRecovery = 'Fix the reported TypeScript declaration errors and rebuild. ' |
| 26 | + + 'Declaration-emit errors such as TS4023 (an exported value naming a type its module does not export) ' |
| 27 | + + 'never appear under `tsc --noEmit`; replay them with `tsc --declaration --emitDeclarationOnly` ' |
| 28 | + + 'over the lib entry source directory.'; |
| 29 | + |
| 30 | +export interface TypeScriptEmitLocation { |
| 31 | + readonly column: number; |
| 32 | + /** As printed by `tsc`: relative to the project root, or absolute. */ |
| 33 | + readonly file: string; |
| 34 | + readonly line: number; |
| 35 | +} |
| 36 | + |
| 37 | +export interface TypeScriptEmitDiagnostic { |
| 38 | + /** Absent for whole-program diagnostics such as option errors. */ |
| 39 | + readonly location?: TypeScriptEmitLocation; |
| 40 | + readonly message: string; |
| 41 | + /** The TypeScript diagnostic code, e.g. `TS4023`. */ |
| 42 | + readonly tsCode: string; |
| 43 | +} |
| 44 | + |
| 45 | +const locatedDiagnostic = |
| 46 | + /^(?<file>[^(]+)\((?<line>\d+),(?<column>\d+)\): (?:error|warning) (?<tsCode>TS\d+): (?<message>.+)$/u; |
| 47 | +const programWideDiagnostic = /^(?:error|warning) (?<tsCode>TS\d+): (?<message>.+)$/u; |
| 48 | + |
| 49 | +/** |
| 50 | + * Parses the `--pretty false` diagnostic format, which is stable across |
| 51 | + * TypeScript 5 and the TypeScript 7 native compiler. Continuation and |
| 52 | + * related-information lines are indented and carry no code, so they are |
| 53 | + * skipped rather than misparsed. |
| 54 | + */ |
| 55 | +export const parseTypeScriptDiagnostics = (output: string): readonly TypeScriptEmitDiagnostic[] => { |
| 56 | + const diagnostics: TypeScriptEmitDiagnostic[] = []; |
| 57 | + for (const line of output.split(/\r?\n/u)) { |
| 58 | + const located = locatedDiagnostic.exec(line)?.groups; |
| 59 | + if (located !== undefined) { |
| 60 | + diagnostics.push({ |
| 61 | + location: { |
| 62 | + column: Number(located.column), |
| 63 | + file: located.file!, |
| 64 | + line: Number(located.line), |
| 65 | + }, |
| 66 | + message: located.message!.trim(), |
| 67 | + tsCode: located.tsCode!, |
| 68 | + }); |
| 69 | + continue; |
| 70 | + } |
| 71 | + const programWide = programWideDiagnostic.exec(line)?.groups; |
| 72 | + if (programWide !== undefined) { |
| 73 | + diagnostics.push({ message: programWide.message!.trim(), tsCode: programWide.tsCode! }); |
| 74 | + } |
| 75 | + } |
| 76 | + return Object.freeze(diagnostics); |
| 77 | +}; |
| 78 | + |
| 79 | +/** |
| 80 | + * The consumer project's own compiler, resolved exactly like the dts build |
| 81 | + * resolves it: a project pinning TypeScript 5 must never be replayed through |
| 82 | + * a different copy hoisted somewhere above it. |
| 83 | + */ |
| 84 | +const typeScriptCli = (projectRoot: string): string | undefined => { |
| 85 | + let manifest: string; |
| 86 | + try { |
| 87 | + manifest = createRequire(join(projectRoot, 'package.json')).resolve('typescript/package.json'); |
| 88 | + } catch { |
| 89 | + return undefined; |
| 90 | + } |
| 91 | + const cli = join(dirname(manifest), 'lib', 'tsc.js'); |
| 92 | + return existsSync(cli) ? cli : undefined; |
| 93 | +}; |
| 94 | + |
| 95 | +const processOutput = (error: unknown): string => { |
| 96 | + const streams = error as { readonly stderr?: unknown; readonly stdout?: unknown }; |
| 97 | + return [streams.stdout, streams.stderr] |
| 98 | + .filter((stream): stream is string => typeof stream === 'string') |
| 99 | + .join('\n'); |
| 100 | +}; |
| 101 | + |
| 102 | +/** |
| 103 | + * Replays `tsc --declaration --emitDeclarationOnly` over the synthesized dts |
| 104 | + * project. The overrides pin emit on regardless of what the consumer |
| 105 | + * tsconfig this project extends declares (`noEmit`, `declarationDir`, and |
| 106 | + * incremental build info all belong to the consumer's own type check), and |
| 107 | + * the declarations land in a throwaway sibling of the synthesized project so |
| 108 | + * the replay never touches the package output or the project tree. |
| 109 | + * |
| 110 | + * A replay that cannot run (no resolvable compiler) or that passes returns no |
| 111 | + * diagnostics; the caller still reports the failure, just without detail. |
| 112 | + */ |
| 113 | +export const replayDeclarationEmit = async (options: { |
| 114 | + readonly projectRoot: string; |
| 115 | + readonly tsconfigPath: string; |
| 116 | +}): Promise<readonly TypeScriptEmitDiagnostic[]> => { |
| 117 | + const cli = typeScriptCli(options.projectRoot); |
| 118 | + if (cli === undefined) return Object.freeze([]); |
| 119 | + const outDir = join(dirname(options.tsconfigPath), 'declaration-replay'); |
| 120 | + try { |
| 121 | + await execFile(process.execPath, [ |
| 122 | + cli, |
| 123 | + '--project', options.tsconfigPath, |
| 124 | + '--declaration', |
| 125 | + '--declarationDir', outDir, |
| 126 | + '--emitDeclarationOnly', |
| 127 | + '--incremental', 'false', |
| 128 | + '--noEmit', 'false', |
| 129 | + '--outDir', outDir, |
| 130 | + '--pretty', 'false', |
| 131 | + ], { cwd: options.projectRoot, maxBuffer: 32 * 1024 * 1024 }); |
| 132 | + return Object.freeze([]); |
| 133 | + } catch (error) { |
| 134 | + return parseTypeScriptDiagnostics(processOutput(error)); |
| 135 | + } |
| 136 | +}; |
| 137 | + |
| 138 | +/** Project-relative when the file lives inside the project, absolute otherwise. */ |
| 139 | +const formatLocation = (projectRoot: string, location: TypeScriptEmitLocation): { |
| 140 | + readonly display: string; |
| 141 | + readonly sourcePath: string; |
| 142 | +} => { |
| 143 | + const sourcePath = isAbsolute(location.file) ? location.file : resolve(projectRoot, location.file); |
| 144 | + const relativePath = relative(projectRoot, sourcePath).replaceAll('\\', '/'); |
| 145 | + const shown = relativePath.length === 0 || relativePath.startsWith('..') ? sourcePath : relativePath; |
| 146 | + return { display: `${shown}(${location.line},${location.column}): `, sourcePath }; |
| 147 | +}; |
| 148 | + |
| 149 | +/** |
| 150 | + * One `AB4716` error per recovered TypeScript diagnostic, each carrying the |
| 151 | + * file, position, and TS code so `--json` consumers and the terminal see the |
| 152 | + * same detail the manual `tsc --emitDeclarationOnly` replay produced. When |
| 153 | + * nothing could be recovered the failure still reports under `AB4716` with |
| 154 | + * the bundler's own message, never the `AB5000` catch-all. |
| 155 | + */ |
| 156 | +export const declarationBuildDiagnostics = (options: { |
| 157 | + readonly entryName: string; |
| 158 | + readonly failure: string; |
| 159 | + readonly projectRoot: string; |
| 160 | + readonly typeScriptDiagnostics: readonly TypeScriptEmitDiagnostic[]; |
| 161 | +}): readonly Diagnostic[] => { |
| 162 | + const prefix = `Declaration generation for lib entry ${JSON.stringify(options.entryName)} failed`; |
| 163 | + if (options.typeScriptDiagnostics.length === 0) { |
| 164 | + return Object.freeze([{ |
| 165 | + code: declarationBuildCode, |
| 166 | + message: `${prefix}: ${options.failure}`, |
| 167 | + recovery: emitOnlyRecovery, |
| 168 | + severity: 'error' as const, |
| 169 | + }]); |
| 170 | + } |
| 171 | + return Object.freeze(options.typeScriptDiagnostics.map((diagnostic): Diagnostic => { |
| 172 | + const location = diagnostic.location === undefined |
| 173 | + ? undefined |
| 174 | + : formatLocation(options.projectRoot, diagnostic.location); |
| 175 | + return { |
| 176 | + code: declarationBuildCode, |
| 177 | + message: `${prefix}: ${location?.display ?? ''}${diagnostic.tsCode}: ${diagnostic.message}`, |
| 178 | + recovery: emitOnlyRecovery, |
| 179 | + severity: 'error' as const, |
| 180 | + ...(location === undefined ? {} : { sourcePath: location.sourcePath }), |
| 181 | + }; |
| 182 | + })); |
| 183 | +}; |
0 commit comments