Skip to content

Commit 8408fe1

Browse files
authored
feat: restore deprecated TypeScript 7.0 tsgo CLI backend (#331)
1 parent 50e4282 commit 8408fe1

7 files changed

Lines changed: 353 additions & 69 deletions

File tree

‎README.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,19 @@ See [rolldown.config.ts](./rolldown.config.ts) for the project's own setup.
5656
When `generator` is omitted, the plugin selects:
5757

5858
1. `oxc` when `compilerOptions.isolatedDeclarations` is enabled.
59-
2. `tsgo` when `typescript` exposes `Program.prototype.getDeclarationEmit`.
59+
2. `tsgo` when `typescript` exposes `Program.prototype.getDeclarationEmit`, or
60+
when TypeScript 7.0 is installed (deprecated, see below).
6061
3. `tsc` otherwise.
6162

6263
Automatic selection only inspects `typescript` and never selects `tsrs`.
63-
Selecting `tsgo` explicitly requires TypeScript 7.1 or later.
64+
Selecting `tsgo` explicitly requires TypeScript 7.1 or later, or the
65+
deprecated TypeScript 7.0 backend below.
66+
67+
> [!WARNING]
68+
> With TypeScript 7.0, `tsgo` falls back to running the `tsgo` CLI. This backend
69+
> is deprecated and will be removed in the next minor; upgrade to TypeScript
70+
> 7.1 or later. It does not support custom languages, and among the `tsgo.*`
71+
> options only `tsgo.path` (the executable to run) applies.
6472
6573
`generator` also accepts an object implementing the exported `Generator`
6674
interface.

‎__snapshots__/tsnapi/tsc.snapshot.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22
* Generated by tsnapi — public API snapshot of `rolldown-plugin-dts/tsc`
33
*/
44
// #region Re-exports
5-
export { t as tscEmit } from "./tsc-DwJ6Cn9n.mjs";
5+
export { t as tscEmit } from "./tsc-CxhUHgu3.mjs";
66
// #endregion

‎src/generator/index.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import path from 'node:path'
2+
import { isLegacyTsgo } from '../tsgo.ts'
13
import { OxcGenerator } from './oxc.ts'
24
import { TscGenerator } from './tsc.ts'
5+
import { TsgoCliGenerator } from './tsgo-cli.ts'
36
import { TsgoGenerator } from './tsgo.ts'
47
import type { OptionsResolved } from '../options.ts'
58
import type { RollupError, SourceMapInput } from 'rolldown'
@@ -64,6 +67,16 @@ export function createGenerator(
6467
return new OxcGenerator(oxc, languageContext)
6568
}
6669

70+
if (generator === 'tsgo' && isLegacyTsgo(tsgo.moduleUrl)) {
71+
return new TsgoCliGenerator({
72+
tsgoPath: tsgo.path!,
73+
rootDir: path.dirname(tsconfig!),
74+
tsconfig: tsconfig!,
75+
sourcemap,
76+
languageContext,
77+
})
78+
}
79+
6780
if (generator === 'tsgo' || generator === 'tsrs') {
6881
const native = generator === 'tsrs' ? tsrs : tsgo
6982
return new TsgoGenerator({
@@ -94,4 +107,4 @@ export function createGenerator(
94107
})
95108
}
96109

97-
export { OxcGenerator, TscGenerator, TsgoGenerator }
110+
export { OxcGenerator, TscGenerator, TsgoCliGenerator, TsgoGenerator }

‎src/generator/tsgo-cli.ts‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
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+
}

‎src/options.ts‎

Lines changed: 52 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
} from 'get-tsconfig'
1010
import { createDebug } from 'obug'
1111
import { LanguageContext, type CustomLanguage } from './custom-language.ts'
12+
import { resolveTsgoPath } from './generator/tsgo-cli.ts'
1213
import { escapeRegExp } from './regexp.ts'
1314
import { requireTSApi } from './require.ts'
1415
import {
@@ -18,6 +19,7 @@ import {
1819
} from './tsc/vue.ts'
1920
import {
2021
getDefaultTsgoModuleUrl,
22+
isLegacyTsgo,
2123
loadTsgoApi,
2224
tryLoadTsgoApi,
2325
type NativeCompiler,
@@ -47,8 +49,8 @@ export interface Options extends DeprecatedOptions {
4749
* - A custom {@link Generator} implementation can be provided directly.
4850
*
4951
* When omitted, the plugin selects `'oxc'` for `isolatedDeclarations`,
50-
* `'tsgo'` when TypeScript exposes the declaration emit API, and `'tsc'`
51-
* otherwise. Volar-based custom languages require `'tsc'`.
52+
* `'tsgo'` when TypeScript exposes the declaration emit API or is 7.0
53+
* (deprecated CLI backend), and `'tsc'` otherwise. Volar-based custom languages require `'tsc'`.
5254
*
5355
* @default Inferred from the TypeScript configuration and installed compiler.
5456
*/
@@ -290,6 +292,7 @@ export interface TsgoOptions {
290292

291293
/**
292294
* Path passed to the TypeScript Go API as `tsserverPath`.
295+
* With the deprecated TypeScript 7.0 backend, the `tsgo` executable to run.
293296
*/
294297
path?: string
295298

@@ -488,7 +491,11 @@ export function resolveOptions({
488491
if (compilerOptions.isolatedDeclarations) {
489492
generator = 'oxc'
490493
} else {
491-
generator = tryLoadTsgoApi(defaultTsgoModuleUrl) ? 'tsgo' : 'tsc'
494+
generator =
495+
tryLoadTsgoApi(defaultTsgoModuleUrl) ||
496+
isLegacyTsgo(defaultTsgoModuleUrl)
497+
? 'tsgo'
498+
: 'tsc'
492499
}
493500
}
494501

@@ -505,6 +512,13 @@ export function resolveOptions({
505512
)
506513
}
507514

515+
const legacyTsgo = generator === 'tsgo' && isLegacyTsgo(tsgo.moduleUrl)
516+
if (legacyTsgo && customLanguages.length) {
517+
throw new Error(
518+
"The `tsgo` generator on TypeScript 7.0 does not support custom languages. Upgrade to TypeScript >=7.1, enable `isolatedDeclarations` or set `generator: 'oxc'` to use Oxc instead, or install TypeScript 6.0 or below.",
519+
)
520+
}
521+
508522
const native =
509523
generator === 'tsgo' ? tsgo : generator === 'tsrs' ? tsrs : undefined
510524
if (customLanguages.length && !isUsingVolar && native && !native.vfs) {
@@ -525,44 +539,52 @@ export function resolveOptions({
525539
`The \`${compiler}\` generator requires a tsconfig file to be specified.`,
526540
)
527541
}
528-
if (!warnedNative.has(compiler)) {
542+
if (legacyTsgo) {
543+
logger.warn(
544+
'The `tsgo` generator on TypeScript 7.0 is deprecated and will be removed in the next minor. Upgrade to TypeScript 7.1 or later.',
545+
)
546+
} else if (!warnedNative.has(compiler)) {
529547
warnedNative.add(compiler)
530548
logger.warn(
531549
compiler === 'tsrs'
532550
? 'tsrs support is highly experimental and may change or break without notice. Some options will be unavailable.'
533551
: 'TypeScript Go is experimental. Some options will be unavailable.',
534552
)
535553
}
536-
loadTsgoApi(native.moduleUrl, logger, compiler)
537-
538-
const contentMappers: { extensions: string[] }[] | undefined = (
539-
resolvedTsconfig as any
540-
)?.contentMappers
541-
if (contentMappers?.length) {
542-
if (!native.runExternalCode) {
543-
throw new Error(
544-
`Content mappers require \`${compiler}.runExternalCode: true\`.`,
554+
if (legacyTsgo) {
555+
tsgo.path ??= resolveTsgoPath(logger)
556+
} else {
557+
loadTsgoApi(native.moduleUrl, logger, compiler)
558+
559+
const contentMappers: { extensions: string[] }[] | undefined = (
560+
resolvedTsconfig as any
561+
)?.contentMappers
562+
if (contentMappers?.length) {
563+
if (!native.runExternalCode) {
564+
throw new Error(
565+
`Content mappers require \`${compiler}.runExternalCode: true\`.`,
566+
)
567+
}
568+
if (native.vfs) {
569+
throw new Error(
570+
`Content mappers cannot be combined with \`${compiler}.vfs\`.`,
571+
)
572+
}
573+
languageContext.contentMapperExtensions = [
574+
...new Set(contentMappers.flatMap((mapper) => mapper.extensions)),
575+
]
576+
languageContext.patterns.push(
577+
...languageContext.contentMapperExtensions.map(
578+
(extension) => new RegExp(`${escapeRegExp(extension)}$`),
579+
),
545580
)
546581
}
547-
if (native.vfs) {
548-
throw new Error(
549-
`Content mappers cannot be combined with \`${compiler}.vfs\`.`,
582+
583+
if (sourcemap && !resolvedTsconfig?.compilerOptions?.declarationMap) {
584+
logger.warn(
585+
`The \`${compiler}\` generator requires \`compilerOptions.declarationMap: true\` in your tsconfig file for source mappings. The plugin's \`sourcemap\` option does not override the tsconfig.`,
550586
)
551587
}
552-
languageContext.contentMapperExtensions = [
553-
...new Set(contentMappers.flatMap((mapper) => mapper.extensions)),
554-
]
555-
languageContext.patterns.push(
556-
...languageContext.contentMapperExtensions.map(
557-
(extension) => new RegExp(`${escapeRegExp(extension)}$`),
558-
),
559-
)
560-
}
561-
562-
if (sourcemap && !resolvedTsconfig?.compilerOptions?.declarationMap) {
563-
logger.warn(
564-
`The \`${compiler}\` generator requires \`compilerOptions.declarationMap: true\` in your tsconfig file for source mappings. The plugin's \`sourcemap\` option does not override the tsconfig.`,
565-
)
566588
}
567589
}
568590
oxc.stripInternal ??= !!compilerOptions.stripInternal

0 commit comments

Comments
 (0)