Skip to content

Commit 20ffff7

Browse files
committed
feat: support tsgo content mappers
1 parent 54ad599 commit 20ffff7

14 files changed

Lines changed: 275 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -164,19 +164,20 @@ dts({
164164
Experimental. Requires `typescript@7.1.0-beta` or a compatible version and a
165165
`tsconfig.json`.
166166

167-
| Option | Description | Default |
168-
| ---------------- | ------------------------------------------------------------ | ----------------------------------- |
169-
| `tsgo.moduleUrl` | File URL of the TypeScript package that provides the Go API. | `import.meta.resolve('typescript')` |
170-
| `tsgo.path` | Custom API server executable, passed as `tsserverPath`. | Provided by the selected package |
171-
| `tsgo.vfs` | Supply transformed source code through a virtual filesystem. | `false` |
167+
| Option | Description | Default |
168+
| ---------------------- | ------------------------------------------------------------ | ----------------------------------- |
169+
| `tsgo.moduleUrl` | File URL of the TypeScript package that provides the Go API. | `import.meta.resolve('typescript')` |
170+
| `tsgo.path` | Custom API server executable, passed as `tsserverPath`. | Provided by the selected package |
171+
| `tsgo.runExternalCode` | Allow execution of content mappers configured in tsconfig. | `false` |
172+
| `tsgo.vfs` | Supply transformed source code through a virtual filesystem. | `false` |
172173

173174
- The plugin's current `tsgo` implementation reads compiler settings from the
174175
config file; `tsconfigRaw` and `compilerOptions` do not override them.
175176
- Declaration maps require `compilerOptions.declarationMap: true` in the config
176177
file; setting only the plugin's `sourcemap: true` produces a warning.
177178
- With `tsgo.vfs: true`, source transforms must run before the dts transform hook.
178-
Non-Volar custom languages also require a `toTsFilename` mapping; Vue and
179-
Volar integrations require `tsc`.
179+
Non-Volar custom languages also require a `toTsFilename` mapping.
180+
Volar integrations, including `tsc.vue`, require `tsc`.
180181

181182
```ts
182183
dts({
@@ -188,6 +189,22 @@ dts({
188189
})
189190
```
190191

192+
#### Content mappers
193+
194+
Configure `contentMappers` in your tsconfig and enable `tsgo.runExternalCode`:
195+
196+
```ts
197+
dts({
198+
generator: 'tsgo',
199+
tsgo: { runExternalCode: true },
200+
})
201+
```
202+
203+
Extensions declared by content mappers (including inherited tsconfig settings)
204+
are recognized automatically; `customLanguages` is not needed. Content mappers
205+
read files from disk and cannot be combined with `tsgo.vfs`. If you also emit
206+
JavaScript, use your framework's Rolldown plugin to transform these source files.
207+
191208
## Vite
192209

193210
Exclude generated declarations from Oxc transformation. Because `oxc.exclude`

‎__snapshots__/tsnapi/index.snapshot.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ type OptionsResolved = Overwrite<Required<Omit<Options, "compilerOptions" | "cus
7676
}>;
7777
}>;
7878
interface TsgoOptions {
79+
runExternalCode?: boolean;
7980
moduleUrl?: string;
8081
path?: string;
8182
vfs?: boolean;

‎src/custom-language.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ export interface CustomLanguage {
3535
export class LanguageContext {
3636
languages: CustomLanguage[]
3737
patterns: RegExp[]
38+
/** @internal */
39+
contentMapperExtensions: string[] = []
3840

3941
constructor(languages: CustomLanguage[]) {
4042
this.languages = languages
@@ -99,7 +101,15 @@ export class LanguageContext {
99101
})
100102
}
101103

104+
/** @internal */
105+
isContentMappedFile(id: string): boolean {
106+
return this.contentMapperExtensions.some((extension) =>
107+
id.endsWith(extension),
108+
)
109+
}
110+
102111
toTsFilename(id: string): string {
112+
if (this.isContentMappedFile(id)) return `${id}.ts`
103113
for (const language of this.languages) {
104114
if (
105115
language.toTsFilename &&

‎src/generator/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export function createGenerator(
6666
return new TsgoGenerator({
6767
moduleUrl: tsgo.moduleUrl,
6868
tsgoPath: tsgo.path,
69+
runExternalCode: tsgo.runExternalCode,
6970
cwd,
7071
tsconfig: tsconfig!,
7172
vfs: !!tsgo.vfs,

‎src/generator/tsgo.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const debug = createDebug('rolldown-plugin-dts:tsgo')
1414
export interface TsgoGeneratorOptions {
1515
moduleUrl?: string
1616
tsgoPath?: string
17+
runExternalCode?: boolean
1718
cwd: string
1819
tsconfig: string
1920
vfs: boolean
@@ -50,10 +51,24 @@ export class TsgoGenerator implements Generator {
5051
this.api = new this.apiModule.API({
5152
cwd,
5253
tsserverPath: tsgoPath,
54+
runExternalCode: this.options.runExternalCode,
5355
})
5456
this.snapshot = await this.api.createSnapshot({
5557
openProjects: [tsconfig],
5658
})
59+
if (!this.options.languageContext.contentMapperExtensions.length) return
60+
// Mapper setup and transform errors can otherwise produce empty declarations.
61+
const project = this.snapshot.getConfiguredProject(tsconfig)
62+
if (!project) return
63+
const diagnostics = (
64+
await Promise.all([
65+
project.program.getConfigFileParsingDiagnostics(),
66+
project.program.getSyntacticDiagnostics(),
67+
])
68+
).flat()
69+
if (diagnostics.length) {
70+
throw new Error(this.apiModule.formatDiagnostics(diagnostics, this.api))
71+
}
5772
}
5873

5974
addFile(code: string, fileName: string): void {
@@ -162,7 +177,11 @@ export class TsgoGenerator implements Generator {
162177
throw new Error('TsgoGenerator has not been initialized.')
163178
}
164179

165-
const tsFileName = this.toTsFilename(fileName)
180+
const tsFileName = this.options.languageContext.isContentMappedFile(
181+
fileName,
182+
)
183+
? path.resolve(fileName)
184+
: this.toTsFilename(fileName)
166185
let project = await this.snapshot
167186
.getDefaultProjectForFile(tsFileName)
168187
.catch((error: unknown) => {

‎src/options.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from 'get-tsconfig'
99
import { createDebug } from 'obug'
1010
import { LanguageContext, type CustomLanguage } from './custom-language.ts'
11+
import { escapeRegExp } from './regexp.ts'
1112
import { requireTSApi } from './require.ts'
1213
import {
1314
createVueLanguage,
@@ -233,6 +234,14 @@ export interface TscOptions {
233234
}
234235

235236
export interface TsgoOptions {
237+
/**
238+
* Allows TypeScript to execute content mappers configured in tsconfig.
239+
* Cannot be combined with `tsgo.vfs` when content mappers are configured.
240+
*
241+
* @default false
242+
*/
243+
runExternalCode?: boolean
244+
236245
/**
237246
* A `file://` URL of the TypeScript module that provides the TypeScript Go API.
238247
*
@@ -422,6 +431,27 @@ export function resolveOptions({
422431
)
423432
}
424433
loadTsgoApi(tsgo.moduleUrl, logger)
434+
435+
const contentMappers: { extensions: string[] }[] | undefined = (
436+
resolvedTsconfig as any
437+
)?.contentMappers
438+
if (contentMappers?.length) {
439+
if (!tsgo.runExternalCode) {
440+
throw new Error('Content mappers require `tsgo.runExternalCode: true`.')
441+
}
442+
if (tsgo.vfs) {
443+
throw new Error('Content mappers cannot be combined with `tsgo.vfs`.')
444+
}
445+
languageContext.contentMapperExtensions = [
446+
...new Set(contentMappers.flatMap((mapper) => mapper.extensions)),
447+
]
448+
languageContext.patterns.push(
449+
...languageContext.contentMapperExtensions.map(
450+
(extension) => new RegExp(`${escapeRegExp(extension)}$`),
451+
),
452+
)
453+
}
454+
425455
if (sourcemap && !resolvedTsconfig?.compilerOptions?.declarationMap) {
426456
logger.warn(
427457
"The `tsgo` generator requires `compilerOptions.declarationMap: true` in your tsconfig file for source mappings. The plugin's `sourcemap` option does not override the tsconfig.",

‎src/regexp.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Based on https://github.com/sindresorhus/escape-string-regexp
2+
export function escapeRegExp(value: string): string {
3+
return value
4+
.replaceAll(/[|\\{}()[\]^$+*?.]/g, String.raw`\$&`)
5+
.replaceAll('-', String.raw`\x2d`)
6+
}

‎tests/content-mapper.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import {
2+
cp,
3+
mkdir,
4+
mkdtemp,
5+
realpath,
6+
rm,
7+
symlink,
8+
writeFile,
9+
} from 'node:fs/promises'
10+
import os from 'node:os'
11+
import path from 'node:path'
12+
import { rolldownBuild } from '@sxzz/test-utils'
13+
import { afterEach, beforeEach, expect, test } from 'vitest'
14+
import { dts } from '../src/index.ts'
15+
import { findSourceMapChunk } from './utils.ts'
16+
17+
const fixture = path.resolve(import.meta.dirname, 'fixtures/content-mapper')
18+
const root = await realpath(
19+
await mkdtemp(path.join(os.tmpdir(), 'dts-content-mapper-')),
20+
)
21+
beforeEach(async () => {
22+
await cp(fixture, root, { recursive: true })
23+
await mkdir(path.join(root, 'node_modules'))
24+
await symlink(
25+
path.join(root, 'mapper'),
26+
path.join(root, 'node_modules/test-content-mapper'),
27+
'dir',
28+
)
29+
})
30+
afterEach(() => rm(root, { recursive: true, force: true }))
31+
const moduleUrl = import.meta.resolve('typescript-next')
32+
const options = {
33+
generator: 'tsgo' as const,
34+
tsconfig: path.join(root, 'tsconfig.json'),
35+
emitDtsOnly: true,
36+
tsgo: { moduleUrl, runExternalCode: true },
37+
}
38+
39+
test.each(['index.ts', 'Example.component'])(
40+
'content mapper: %s',
41+
async (entry) => {
42+
const { chunks } = await rolldownBuild(path.join(root, entry), [
43+
dts(options),
44+
])
45+
const declarations = chunks.filter((chunk) => chunk.type === 'chunk')
46+
expect(declarations.length).toBeGreaterThan(0)
47+
expect(declarations.map((chunk) => chunk.code).join('\n')).toContain(
48+
'name: string',
49+
)
50+
},
51+
)
52+
53+
test('content mappers require external code permission', () => {
54+
expect(() => dts({ ...options, tsgo: { moduleUrl } })).toThrow(
55+
'tsgo.runExternalCode',
56+
)
57+
})
58+
59+
test('content mappers reject VFS', () => {
60+
expect(() =>
61+
dts({ ...options, tsgo: { ...options.tsgo, vfs: true } }),
62+
).toThrow('tsgo.vfs')
63+
})
64+
65+
test('reports a missing mapper package', async () => {
66+
await writeFile(
67+
path.join(root, 'base.json'),
68+
JSON.stringify({
69+
contentMappers: [
70+
{ package: 'nonexistent-content-mapper', extensions: ['.component'] },
71+
],
72+
}),
73+
)
74+
await expect(
75+
rolldownBuild(path.join(root, 'index.ts'), [dts(options)]),
76+
).rejects.toThrow('could not be resolved')
77+
})
78+
79+
test('reports mapper failures', async () => {
80+
await writeFile(path.join(root, 'Example.component'), 'MAPPER_ERROR')
81+
await expect(
82+
rolldownBuild(path.join(root, 'Example.component'), [dts(options)]),
83+
).rejects.toThrow('failed to transform this file')
84+
})
85+
86+
test('declaration maps point to the original mapper source', async () => {
87+
const { chunks } = await rolldownBuild(
88+
path.join(root, 'Example.component'),
89+
[dts(options)],
90+
{},
91+
{ dir: path.join(root, 'dist') },
92+
)
93+
const map = findSourceMapChunk(chunks, 'Example.component.d.ts.map')
94+
expect(map.sources).toEqual(['../Example.component'])
95+
expect(map.mappings).not.toBe('')
96+
})
97+
98+
test('rebuilds mapped sources from disk', async () => {
99+
const plugins = [dts(options)]
100+
const entry = path.join(root, 'Example.component')
101+
const first = await rolldownBuild(entry, plugins)
102+
expect(first.snapshot).toContain('name: string')
103+
await writeFile(
104+
entry,
105+
'export default function greet(count: number): number { return count }',
106+
)
107+
const rebuilt = await rolldownBuild(entry, plugins)
108+
expect(rebuilt.snapshot).toContain('count: number')
109+
expect(rebuilt.snapshot).not.toContain('name: string')
110+
})
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default function greet(name: string): string { return `Hello ${name}` }
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"compilerOptions": {
3+
"declaration": true,
4+
"declarationMap": true,
5+
"strict": true,
6+
"skipLibCheck": true
7+
},
8+
"contentMappers": [
9+
{ "package": "test-content-mapper", "extensions": [".component"] }
10+
]
11+
}

0 commit comments

Comments
 (0)