From 9c19f748b290079b22b65d10cc101dafafd03383 Mon Sep 17 00:00:00 2001 From: ocavue Date: Thu, 5 Jun 2025 06:13:21 +1000 Subject: [PATCH] feat: support `tsc -b` (#42) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 三咲智子 Kevin Deng --- src/generate.ts | 16 ++-- src/index.ts | 38 ++++++++- src/utils/tsc-system.ts | 73 ++++++++++++++++ src/utils/tsc.ts | 83 +++++++++++++++++-- tests/__snapshots__/index.test.ts.snap | 50 +++++++++++ .../composite-refs-incremental/dir1/input1.ts | 1 + .../composite-refs-incremental/dir2/input2.ts | 1 + .../tsconfig.1.json | 11 +++ .../tsconfig.2.json | 11 +++ .../tsconfig.incremental.json | 6 ++ .../composite-refs-incremental/tsconfig.json | 16 ++++ tests/fixtures/composite-refs/dir1/input1.ts | 1 + tests/fixtures/composite-refs/dir2/input2.ts | 1 + tests/fixtures/composite-refs/tsconfig.1.json | 11 +++ tests/fixtures/composite-refs/tsconfig.2.json | 11 +++ tests/fixtures/composite-refs/tsconfig.json | 15 ++++ tests/index.test.ts | 69 +++++++++++++++ vitest.config.ts | 9 ++ 18 files changed, 407 insertions(+), 16 deletions(-) create mode 100644 src/utils/tsc-system.ts create mode 100644 tests/fixtures/composite-refs-incremental/dir1/input1.ts create mode 100644 tests/fixtures/composite-refs-incremental/dir2/input2.ts create mode 100644 tests/fixtures/composite-refs-incremental/tsconfig.1.json create mode 100644 tests/fixtures/composite-refs-incremental/tsconfig.2.json create mode 100644 tests/fixtures/composite-refs-incremental/tsconfig.incremental.json create mode 100644 tests/fixtures/composite-refs-incremental/tsconfig.json create mode 100644 tests/fixtures/composite-refs/dir1/input1.ts create mode 100644 tests/fixtures/composite-refs/dir2/input2.ts create mode 100644 tests/fixtures/composite-refs/tsconfig.1.json create mode 100644 tests/fixtures/composite-refs/tsconfig.2.json create mode 100644 tests/fixtures/composite-refs/tsconfig.json create mode 100644 vitest.config.ts diff --git a/src/generate.ts b/src/generate.ts index 9515bfc..d490b1b 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -14,7 +14,7 @@ import { import type { TscFunctions } from './utils/tsc-worker.ts' import type { TscOptions, TscResult } from './utils/tsc.ts' import type { OptionsResolved } from './index.ts' -import type { Plugin } from 'rolldown' +import type { Plugin, SourceMapInput } from 'rolldown' const debug = Debug('rolldown-plugin-dts:generate') @@ -31,8 +31,10 @@ export interface TsModule { export type DtsMap = Map export function createGeneratePlugin({ + tsconfig, tsconfigRaw, - tsconfigDir, + incremental, + cwd, isolatedDeclarations, emitDtsOnly, vue, @@ -40,8 +42,10 @@ export function createGeneratePlugin({ eager, }: Pick< OptionsResolved, + | 'cwd' + | 'tsconfig' | 'tsconfigRaw' - | 'tsconfigDir' + | 'incremental' | 'isolatedDeclarations' | 'emitDtsOnly' | 'vue' @@ -169,7 +173,7 @@ export function createGeneratePlugin({ const { code, id } = dtsMap.get(dtsId)! let dtsCode: string | undefined - let map: any + let map: SourceMapInput | undefined debug('generate dts %s from %s', dtsId, id) if (isolatedDeclarations && !RE_VUE.test(id)) { @@ -193,8 +197,10 @@ export function createGeneratePlugin({ .filter((v) => v.isEntry) .map((v) => v.id) const options: Omit = { + tsconfig, tsconfigRaw, - tsconfigDir, + incremental, + cwd, entries, id, vue, diff --git a/src/index.ts b/src/index.ts index fac7c2b..3e7f864 100644 --- a/src/index.ts +++ b/src/index.ts @@ -63,6 +63,37 @@ export interface Options { */ tsconfigRaw?: Omit + /** + * If your tsconfig.json has + * [`references`](https://www.typescriptlang.org/tsconfig/#references) option, + * `rolldown-plugin-dts` will use [`tsc + * -b`](https://www.typescriptlang.org/docs/handbook/project-references.html#build-mode-for-typescript) + * to build the project and all referenced projects before emitting `.d.ts` + * files. + * + * In such case, if this option is `true`, `rolldown-plugin-dts` will write + * down all built files into your disk, including + * [`.tsbuildinfo`](https://www.typescriptlang.org/tsconfig/#tsBuildInfoFile) + * and other built files. This is equivalent to running `tsc -b` in your + * project. + * + * Otherwise, if this option is `false`, `rolldown-plugin-dts` will write + * built files only into memory and leave a small footprint in your disk. + * + * Enabling this option will decrease the build time by caching previous build + * results. This is helpful when you have a large project with multiple + * referenced projects. + * + * By default, `incremental` is `true` if your tsconfig has + * [`incremental`](https://www.typescriptlang.org/tsconfig/#incremental) or + * [`tsBuildInfoFile`](https://www.typescriptlang.org/tsconfig/#tsBuildInfoFile) + * enabled. + * + * This option is only used when {@link Options.isolatedDeclarations} is + * `false`. + */ + incremental?: boolean + /** * Override the `compilerOptions` specified in `tsconfig.json`. * @@ -117,7 +148,6 @@ export type OptionsResolved = Overwrite< tsconfig: string | undefined isolatedDeclarations: IsolatedDeclarationsOptions | false tsconfigRaw: TsConfigJson - tsconfigDir: string } > @@ -141,6 +171,7 @@ export { createFakeJsPlugin, createGeneratePlugin } export function resolveOptions({ cwd = process.cwd(), tsconfig, + incremental = false, compilerOptions = {}, tsconfigRaw: overriddenTsconfigRaw = {}, isolatedDeclarations, @@ -169,6 +200,8 @@ export function resolveOptions({ ...compilerOptions, } + incremental ||= + compilerOptions.incremental || !!compilerOptions.tsBuildInfoFile sourcemap ??= !!compilerOptions.declarationMap compilerOptions.declarationMap = sourcemap @@ -177,7 +210,6 @@ export function resolveOptions({ ...overriddenTsconfigRaw, compilerOptions, } - const tsconfigDir = tsconfig ? path.dirname(tsconfig) : cwd if (isolatedDeclarations == null) { isolatedDeclarations = !!compilerOptions?.isolatedDeclarations @@ -194,8 +226,8 @@ export function resolveOptions({ return { cwd, tsconfig, - tsconfigDir, tsconfigRaw, + incremental, isolatedDeclarations, sourcemap, dtsInput, diff --git a/src/utils/tsc-system.ts b/src/utils/tsc-system.ts new file mode 100644 index 0000000..15bb766 --- /dev/null +++ b/src/utils/tsc-system.ts @@ -0,0 +1,73 @@ +import Debug from 'debug' +import ts from 'typescript' + +const debug = Debug('rolldown-plugin-dts:tsc-system') + +const files: Map = new Map() + +// A system that writes files to both memory and disk. It will try read files +// from memory firstly and fallback to disk if not found.ƒ +export const fsSystem: ts.System = { + ...ts.sys, + + // Hide the output of tsc by default + write(message: string): void { + debug(message) + }, + + // Copied from + // https://github.com/microsoft/TypeScript-Website/blob/b0e9a5c0/packages/typescript-vfs/src/index.ts#L571C5-L574C7 + resolvePath(path) { + if (files.has(path)) { + return path + } + return ts.sys.resolvePath(path) + }, + + // Copied from + // https://github.com/microsoft/TypeScript-Website/blob/b0e9a5c0/packages/typescript-vfs/src/index.ts#L532C1-L534C8 + directoryExists(directory) { + if (Array.from(files.keys()).some((path) => path.startsWith(directory))) { + return true + } + return ts.sys.directoryExists(directory) + }, + + fileExists(fileName) { + if (files.has(fileName)) { + return true + } + return ts.sys.fileExists(fileName) + }, + + readFile(fileName, ...args) { + if (files.has(fileName)) { + return files.get(fileName) + } + return ts.sys.readFile(fileName, ...args) + }, + + writeFile(path, data, ...args) { + files.set(path, data) + ts.sys.writeFile(path, data, ...args) + }, + + deleteFile(fileName, ...args) { + files.delete(fileName) + ts.sys.deleteFile?.(fileName, ...args) + }, +} + +// A system that only writes files to memory. It will read files from both +// memory and disk. +export const memorySystem: ts.System = { + ...fsSystem, + + writeFile(path, data) { + files.set(path, data) + }, + + deleteFile(fileName) { + files.delete(fileName) + }, +} diff --git a/src/utils/tsc.ts b/src/utils/tsc.ts index 8baa796..e7793b7 100644 --- a/src/utils/tsc.ts +++ b/src/utils/tsc.ts @@ -1,7 +1,10 @@ +import path from 'node:path' import Debug from 'debug' import ts from 'typescript' +import { fsSystem, memorySystem } from './tsc-system.ts' import { createVueProgramFactory } from './vue.ts' import type { TsConfigJson } from 'get-tsconfig' +import type { SourceMapInput } from 'rolldown' const debug = Debug('rolldown-plugin-dts:tsc') debug(`loaded typescript: ${ts.version}`) @@ -35,8 +38,10 @@ export interface TscModule { } export interface TscOptions { + tsconfig?: string tsconfigRaw: TsConfigJson - tsconfigDir: string + cwd: string + incremental: boolean entries?: string[] id: string vue?: boolean @@ -66,18 +71,52 @@ function createOrGetTsModule(options: TscOptions): TscModule { return module } +/** + * Build the root project and all its dependencies projects. + * This is designed for a project (e.g. tsconfig.json) that has "references" to + * other composite projects (e.g., tsconfig.node.json and tsconfig.app.json). + * If `incremental` is `true`, the build result will be cached in the + * `.tsbuildinfo` file so that the next time the project is built (without + * changes) the build will be super fast. If `incremental` is `false`, the + * `.tsbuildinfo` file will only be written to the memory. + */ +function buildSolution(tsconfig: string, incremental: boolean) { + debug(`building projects for ${tsconfig} with incremental: ${incremental}`) + const system = incremental ? fsSystem : memorySystem + + const host = ts.createSolutionBuilderHost(system) + const builder = ts.createSolutionBuilder(host, [tsconfig], { + // If `incremental` is `false`, we want to force the builder to rebuild the + // project even if the project is already built (i.e., `.tsbuildinfo` exists + // on the disk). + force: !incremental, + verbose: true, + }) + + const exitStatus = builder.build() + debug(`built solution for ${tsconfig} with exit status ${exitStatus}`) +} + function createTsProgram({ entries, id, + tsconfig, tsconfigRaw, - tsconfigDir, + incremental, vue, + cwd, }: TscOptions): TscModule { const parsedCmd = ts.parseJsonConfigFileContent( tsconfigRaw, - ts.sys, - tsconfigDir, + fsSystem, + tsconfig ? path.dirname(tsconfig) : cwd, ) + + // If the tsconfig has project references, build the project tree. + if (tsconfig && parsedCmd.projectReferences?.length) { + buildSolution(tsconfig, incremental) + } + const compilerOptions: ts.CompilerOptions = { ...defaultCompilerOptions, ...parsedCmd.options, @@ -85,12 +124,18 @@ function createTsProgram({ const rootNames = [ ...new Set( [id, ...(entries || parsedCmd.fileNames)].map((f) => - ts.sys.resolvePath(f), + fsSystem.resolvePath(f), ), ), ] const host = ts.createCompilerHost(compilerOptions, true) + + // Try to read files from memory first, which was added by `buildSolution` + host.readFile = fsSystem.readFile + host.fileExists = fsSystem.fileExists + host.directoryExists = fsSystem.directoryExists + const createProgram = vue ? createVueProgramFactory(ts) : ts.createProgram const program = createProgram({ rootNames, @@ -100,8 +145,18 @@ function createTsProgram({ }) const sourceFile = program.getSourceFile(id) + if (!sourceFile) { - throw new Error(`Source file not found: ${id}`) + debug(`source file not found in program: ${id}`) + if (!fsSystem.fileExists(id)) { + debug(`File ${id} does not exist on disk.`) + throw new Error(`Source file not found: ${id}`) + } else { + debug(`File ${id} exists on disk.`) + throw new Error( + `Unable to load file ${id} from the program. This seems like a bug of rolldown-plugin-dts. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts/issues`, + ) + } } return { @@ -112,15 +167,17 @@ function createTsProgram({ export interface TscResult { code?: string - map?: any + map?: SourceMapInput error?: string } export function tscEmit(tscOptions: TscOptions): TscResult { + debug(`running tscEmit ${tscOptions.id}`) const module = createOrGetTsModule(tscOptions) const { program, file } = module + debug(`got source file: ${file.fileName}`) let dtsCode: string | undefined - let map: any + let map: SourceMapInput | undefined const { emitSkipped, diagnostics } = program.emit( file, (fileName, code) => { @@ -141,5 +198,15 @@ export function tscEmit(tscOptions: TscOptions): TscResult { if (emitSkipped && diagnostics.length) { return { error: ts.formatDiagnostics(diagnostics, formatHost) } } + + // If TypeScript skipped emitting because the file is already a .d.ts (e.g. a + // redirected output from a composite project build), the emit callback above + // will never be invoked. In that case, fall back to the text of the source + // file itself so that callers still receive a declaration string. + if (!dtsCode && file.isDeclarationFile) { + debug('nothing was emitted. fallback to sourceFile text.') + dtsCode = file.getFullText() + } + return { code: dtsCode, map } } diff --git a/tests/__snapshots__/index.test.ts.snap b/tests/__snapshots__/index.test.ts.snap index 401d41b..f354355 100644 --- a/tests/__snapshots__/index.test.ts.snap +++ b/tests/__snapshots__/index.test.ts.snap @@ -38,6 +38,56 @@ var Cls = class { export { Cls, Enum, fn, foo };" `; +exports[`composite references 1`] = ` +"// input1.d.ts +//#region tests/fixtures/composite-refs/dir1/input1.d.ts +declare const input1 = "input1"; +//#endregion +export { input1 }; +// input1.js +//#region tests/fixtures/composite-refs/dir1/input1.ts +const input1 = "input1"; + +//#endregion +export { input1 }; +// input2.d.ts +//#region tests/fixtures/composite-refs/dir2/input2.d.ts +declare const input2 = "input2"; +//#endregion +export { input2 }; +// input2.js +//#region tests/fixtures/composite-refs/dir2/input2.ts +const input2 = "input2"; + +//#endregion +export { input2 };" +`; + +exports[`composite references incremental 1`] = ` +"// input1.d.ts +//#region tests/fixtures/composite-refs-incremental/dir1/input1.d.ts +declare const input1 = "input1"; +//#endregion +export { input1 }; +// input1.js +//#region tests/fixtures/composite-refs-incremental/dir1/input1.ts +const input1 = "input1"; + +//#endregion +export { input1 }; +// input2.d.ts +//#region tests/fixtures/composite-refs-incremental/dir2/input2.d.ts +declare const input2 = "input2"; +//#endregion +export { input2 }; +// input2.js +//#region tests/fixtures/composite-refs-incremental/dir2/input2.ts +const input2 = "input2"; + +//#endregion +export { input2 };" +`; + exports[`dts input 1`] = ` "// index.d.ts //#region tests/fixtures/dts-input.d.ts diff --git a/tests/fixtures/composite-refs-incremental/dir1/input1.ts b/tests/fixtures/composite-refs-incremental/dir1/input1.ts new file mode 100644 index 0000000..9b9b554 --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/dir1/input1.ts @@ -0,0 +1 @@ +export const input1 = 'input1' diff --git a/tests/fixtures/composite-refs-incremental/dir2/input2.ts b/tests/fixtures/composite-refs-incremental/dir2/input2.ts new file mode 100644 index 0000000..97d351e --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/dir2/input2.ts @@ -0,0 +1 @@ +export const input2 = 'input2' diff --git a/tests/fixtures/composite-refs-incremental/tsconfig.1.json b/tests/fixtures/composite-refs-incremental/tsconfig.1.json new file mode 100644 index 0000000..4bd7f43 --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/tsconfig.1.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "composite": true, + "types": [], + "outDir": "${configDir}/temp/dir1" + }, + "include": [ + "${configDir}/dir1/**/*.ts" + ] +} diff --git a/tests/fixtures/composite-refs-incremental/tsconfig.2.json b/tests/fixtures/composite-refs-incremental/tsconfig.2.json new file mode 100644 index 0000000..9adaccb --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/tsconfig.2.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "composite": true, + "types": [], + "outDir": "${configDir}/temp/dir2" + }, + "include": [ + "${configDir}/dir2/**/*.ts" + ] +} diff --git a/tests/fixtures/composite-refs-incremental/tsconfig.incremental.json b/tests/fixtures/composite-refs-incremental/tsconfig.incremental.json new file mode 100644 index 0000000..3187ec4 --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/tsconfig.incremental.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "incremental": true, + }, +} diff --git a/tests/fixtures/composite-refs-incremental/tsconfig.json b/tests/fixtures/composite-refs-incremental/tsconfig.json new file mode 100644 index 0000000..6349ffb --- /dev/null +++ b/tests/fixtures/composite-refs-incremental/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "./tsconfig.incremental.json", + "references": [ + { + "path": "./tsconfig.1.json" + }, + { + "path": "./tsconfig.2.json" + } + ], + "compilerOptions": { + "composite": true, + }, + "include": [] +} diff --git a/tests/fixtures/composite-refs/dir1/input1.ts b/tests/fixtures/composite-refs/dir1/input1.ts new file mode 100644 index 0000000..9b9b554 --- /dev/null +++ b/tests/fixtures/composite-refs/dir1/input1.ts @@ -0,0 +1 @@ +export const input1 = 'input1' diff --git a/tests/fixtures/composite-refs/dir2/input2.ts b/tests/fixtures/composite-refs/dir2/input2.ts new file mode 100644 index 0000000..97d351e --- /dev/null +++ b/tests/fixtures/composite-refs/dir2/input2.ts @@ -0,0 +1 @@ +export const input2 = 'input2' diff --git a/tests/fixtures/composite-refs/tsconfig.1.json b/tests/fixtures/composite-refs/tsconfig.1.json new file mode 100644 index 0000000..4bd7f43 --- /dev/null +++ b/tests/fixtures/composite-refs/tsconfig.1.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "composite": true, + "types": [], + "outDir": "${configDir}/temp/dir1" + }, + "include": [ + "${configDir}/dir1/**/*.ts" + ] +} diff --git a/tests/fixtures/composite-refs/tsconfig.2.json b/tests/fixtures/composite-refs/tsconfig.2.json new file mode 100644 index 0000000..9adaccb --- /dev/null +++ b/tests/fixtures/composite-refs/tsconfig.2.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "composite": true, + "types": [], + "outDir": "${configDir}/temp/dir2" + }, + "include": [ + "${configDir}/dir2/**/*.ts" + ] +} diff --git a/tests/fixtures/composite-refs/tsconfig.json b/tests/fixtures/composite-refs/tsconfig.json new file mode 100644 index 0000000..bf0c473 --- /dev/null +++ b/tests/fixtures/composite-refs/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "references": [ + { + "path": "./tsconfig.1.json" + }, + { + "path": "./tsconfig.2.json" + } + ], + "compilerOptions": { + "composite": true, + }, + "include": [] +} diff --git a/tests/index.test.ts b/tests/index.test.ts index f1c22d6..d2c3cd0 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,6 +1,8 @@ +import fs from 'node:fs/promises' import path from 'node:path' import { fileURLToPath } from 'node:url' import { rolldownBuild } from '@sxzz/test-utils' +import { glob } from 'tinyglobby' import { expect, test } from 'vitest' import { dts } from '../src/index.ts' @@ -176,3 +178,70 @@ test('multi declarations', async () => { ) expect(snapshot).toMatchSnapshot() }) + +test('composite references', async () => { + const root = path.resolve(dirname, 'fixtures/composite-refs') + + // The outDir in tsconfig files. + const tempDir = path.resolve(root, 'temp') + + // Ensure .tsbuildinfo files do not exist before the test + await fs.rm(tempDir, { recursive: true, force: true }) + + const { snapshot } = await rolldownBuild( + [ + path.resolve(root, 'dir1/input1.ts'), + path.resolve(root, 'dir2/input2.ts'), + ], + [ + dts({ + tsconfig: path.resolve(root, 'tsconfig.json'), + compilerOptions: { isolatedDeclarations: false }, + }), + ], + ) + expect(snapshot).toMatchSnapshot() + + // Ensure .tsbuildinfo files are not created after the test + const tsBuildInfoFiles = await glob('**/*.tsbuildinfo', { + cwd: tempDir, + absolute: false, + }) + expect(tsBuildInfoFiles).toHaveLength(0) +}) + +test('composite references incremental', async () => { + const root = path.resolve(dirname, 'fixtures/composite-refs-incremental') + + // The outDir in tsconfig files. + const tempDir = path.resolve(root, 'temp') + + // Ensure .tsbuildinfo files do not exist before the test + await fs.rm(tempDir, { recursive: true, force: true }) + + const { snapshot } = await rolldownBuild( + [ + path.resolve(root, 'dir1/input1.ts'), + path.resolve(root, 'dir2/input2.ts'), + ], + [ + dts({ + tsconfig: path.resolve(root, 'tsconfig.json'), + compilerOptions: { isolatedDeclarations: false }, + }), + ], + ) + expect(snapshot).toMatchSnapshot() + + // Ensure .tsbuildinfo files are created after the test + const tsBuildInfoFiles = await glob('**/*.tsbuildinfo', { + cwd: tempDir, + absolute: false, + }) + expect(tsBuildInfoFiles).toMatchInlineSnapshot(` + [ + "dir1/tsconfig.1.tsbuildinfo", + "dir2/tsconfig.2.tsbuildinfo", + ] + `) +}) diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..31299f1 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + server: { + watch: { + ignored: ['**/temp/**'], + }, + }, +}) -- knotmirror 0.0.1