|
| 1 | +import { spawn } from 'node:child_process' |
| 2 | +import { existsSync } from 'node:fs' |
| 3 | +import { mkdtemp, readFile, rm } from 'node:fs/promises' |
| 4 | +import { tmpdir } from 'node:os' |
| 5 | +import path from 'node:path' |
| 6 | +import { styleText } from 'node:util' |
| 7 | +import { createDebug } from 'obug' |
| 8 | +import { filename_to_dts } from '../filename.ts' |
| 9 | +import { require, tryResolve } from '../require.ts' |
| 10 | +import type { LanguageContext } from '../custom-language.ts' |
| 11 | +import type { Logger } from '../options.ts' |
| 12 | +import type { Generator, GeneratorResult } from './index.ts' |
| 13 | +import type { SourceMapInput } from 'rolldown' |
| 14 | + |
| 15 | +// Deprecated backend for TypeScript 7.0, which only ships the `tsgo` CLI. |
| 16 | +// TypeScript 7.1+ uses the API generator. To be removed in the next minor. |
| 17 | +const debug = createDebug('rolldown-plugin-dts:tsgo') |
| 18 | + |
| 19 | +const spawnAsync = (...args: Parameters<typeof spawn>) => |
| 20 | + new Promise<void>((resolve, reject) => { |
| 21 | + const child = spawn(...args) |
| 22 | + child.on('close', (code, signal) => { |
| 23 | + if (code === 0) resolve() |
| 24 | + else if (signal) |
| 25 | + reject(new Error(`tsgo process terminated by signal ${signal}`)) |
| 26 | + else reject(new Error(`tsgo process exited with code ${code}`)) |
| 27 | + }) |
| 28 | + child.on('error', (error) => reject(error)) |
| 29 | + }) |
| 30 | + |
| 31 | +let tsgoPathCache: string | undefined |
| 32 | + |
| 33 | +export function resolveTsgoPath(logger: Logger): string { |
| 34 | + if (tsgoPathCache) return tsgoPathCache |
| 35 | + |
| 36 | + const pkgJsonPath = tryResolve('typescript/package.json') |
| 37 | + if (!pkgJsonPath) { |
| 38 | + throw new Error( |
| 39 | + 'TypeScript Go is not installed. Please install the `typescript@7.0` package to use the `tsgo` generator.', |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + const { version } = require(pkgJsonPath) as { version: string } |
| 44 | + logger.info( |
| 45 | + `Emit types with ${styleText('underline', `typescript@${version}`)}`, |
| 46 | + ) |
| 47 | + |
| 48 | + const getExePath: any = require( |
| 49 | + path.join(path.dirname(pkgJsonPath), 'lib/getExePath.js'), |
| 50 | + ) |
| 51 | + const tsgoPath = ( |
| 52 | + typeof getExePath === 'function' ? getExePath : getExePath.default |
| 53 | + )() |
| 54 | + if (import.meta.TEST) { |
| 55 | + return tsgoPath |
| 56 | + } |
| 57 | + return (tsgoPathCache = tsgoPath) |
| 58 | +} |
| 59 | + |
| 60 | +interface TsgoContext { |
| 61 | + path: string |
| 62 | + dispose: () => Promise<void> |
| 63 | +} |
| 64 | + |
| 65 | +export interface TsgoCliGeneratorOptions { |
| 66 | + tsgoPath: string |
| 67 | + rootDir: string |
| 68 | + tsconfig: string |
| 69 | + sourcemap?: boolean |
| 70 | + languageContext: LanguageContext |
| 71 | +} |
| 72 | + |
| 73 | +export class TsgoCliGenerator implements Generator { |
| 74 | + private options: TsgoCliGeneratorOptions |
| 75 | + private context?: TsgoContext |
| 76 | + |
| 77 | + constructor(options: TsgoCliGeneratorOptions) { |
| 78 | + this.options = options |
| 79 | + } |
| 80 | + |
| 81 | + async init(): Promise<void> { |
| 82 | + const { tsgoPath, rootDir, tsconfig, sourcemap } = this.options |
| 83 | + this.context = await runTsgo(tsgoPath, rootDir, tsconfig, sourcemap) |
| 84 | + } |
| 85 | + |
| 86 | + async emit(_code: string, fileName: string): Promise<GeneratorResult> { |
| 87 | + const { rootDir, languageContext } = this.options |
| 88 | + if (languageContext.isCustomLanguageFile(fileName)) { |
| 89 | + return { |
| 90 | + error: `tsgo does not support ${path.extname(fileName)} files.`, |
| 91 | + } |
| 92 | + } |
| 93 | + if (!this.context) { |
| 94 | + throw new Error('TsgoCliGenerator has not been initialized.') |
| 95 | + } |
| 96 | + |
| 97 | + const dtsPath = path.resolve( |
| 98 | + this.context.path, |
| 99 | + path.relative( |
| 100 | + path.resolve(rootDir), |
| 101 | + filename_to_dts(fileName, languageContext), |
| 102 | + ), |
| 103 | + ) |
| 104 | + if (!existsSync(dtsPath)) { |
| 105 | + debug('[tsgo]', dtsPath, 'is missing') |
| 106 | + return { |
| 107 | + error: `tsgo did not generate dts file for ${fileName}, please check your tsconfig.`, |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + const code = await readFile(dtsPath, 'utf8') |
| 112 | + let map: SourceMapInput | undefined |
| 113 | + const mapPath = `${dtsPath}.map` |
| 114 | + if (existsSync(mapPath)) { |
| 115 | + const mapRaw = await readFile(mapPath, 'utf8') |
| 116 | + map = { |
| 117 | + ...JSON.parse(mapRaw), |
| 118 | + sources: [fileName], |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return { code, map } |
| 123 | + } |
| 124 | + |
| 125 | + async dispose(): Promise<void> { |
| 126 | + await this.context?.dispose() |
| 127 | + this.context = undefined |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +async function runTsgo( |
| 132 | + tsgoPath: string, |
| 133 | + rootDir: string, |
| 134 | + tsconfig: string, |
| 135 | + sourcemap?: boolean, |
| 136 | +): Promise<TsgoContext> { |
| 137 | + debug('[tsgo] rootDir', rootDir) |
| 138 | + debug('[tsgo] using tsgo binary', tsgoPath) |
| 139 | + |
| 140 | + const tsgoDist = await mkdtemp(path.join(tmpdir(), 'rolldown-plugin-dts-')) |
| 141 | + debug('[tsgo] tsgoDist', tsgoDist) |
| 142 | + |
| 143 | + const args = [ |
| 144 | + '--noEmit', |
| 145 | + 'false', |
| 146 | + '--declaration', |
| 147 | + '--emitDeclarationOnly', |
| 148 | + '-p', |
| 149 | + tsconfig, |
| 150 | + '--outDir', |
| 151 | + tsgoDist, |
| 152 | + '--rootDir', |
| 153 | + rootDir, |
| 154 | + '--noCheck', |
| 155 | + ...(sourcemap ? ['--declarationMap'] : []), |
| 156 | + ] |
| 157 | + debug('[tsgo] args %o', args) |
| 158 | + |
| 159 | + await spawnAsync(tsgoPath, args, { stdio: 'inherit' }) |
| 160 | + |
| 161 | + return { |
| 162 | + path: tsgoDist, |
| 163 | + async dispose() { |
| 164 | + if (debug.enabled) { |
| 165 | + debug('[tsgo] skip cleanup of tsgoDist', tsgoDist) |
| 166 | + } else { |
| 167 | + debug('[tsgo] disposing tsgoDist', tsgoDist) |
| 168 | + await rm(tsgoDist, { recursive: true, force: true }).catch(() => {}) |
| 169 | + } |
| 170 | + }, |
| 171 | + } |
| 172 | +} |
0 commit comments