diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 59afc942..f01d006e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -36,7 +36,7 @@ The package has three entry points:
| `src/commands/` | The CLI subcommands, plus `config-file.ts`, which finds the module's tsdown config and reads the `builder()` options from it. |
| `src/tsdown/` | The `builder()` plugin. `plugin.ts` creates it, and `setup.ts` turns the tsdown config into a build. It adds the plugins, hooks into tsdown's lifecycle, and handles watch mode. `externals.ts`, `unchanged.ts` and `report.ts` are the plugins and helpers that `setup.ts` uses, and `dts.ts` generates the declarations of the bundled entries. `build.ts` runs tsdown for `nuxt-module-build build`. |
| `src/build/` | The build itself, independent of tsdown's plugin API:
`options.ts` resolves `builder()` options.
`build.ts` resolves a `BuildPlan` and runs the steps before and after the bundle.
`loader.ts` imports module code and checks that Node can load it.
`package.ts` holds the `package.json` checks.
`types.ts` and `module-declarations.ts` write `types.d.mts` and the declarations `prepare` generates.
`aliases.ts` rewrites `#app` in declarations.
`directives.ts` wraps the oxc transform of runtime files so that TypeScript directive comments are left out.
`unchecked.ts` finds the TypeScript files that no tsconfig the module references includes, for `prepare`'s note.
`engine.ts` loads the declaration engine that `declarations.engine` selects, with its diagnostics. |
-| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, and resolves the tsconfig of each file with `tsconfig.ts`. It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. |
+| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, resolves the tsconfig of each file with `tsconfig.ts`. `oxc.ts` loads the oxc bindings of the `rolldown` that `tsdown` depends on, whose parser the whole package parses scripts with, and `typescript.ts` loads the JavaScript API of TypeScript that the whole package uses (the module's own `typescript` when it has one, or else `@typescript/typescript6`). The directory imports nothing outside it but `src/utils.ts`, so it can be extracted later. |
| `src/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). |
| `src/diagnostics.ts` | The codes of every error and warning the builder reports (see [Diagnostics](#diagnostics)). |
| `src/utils.ts` | Path, file and regex helpers shared across directories, and `logger`, which prints diagnostics outside a tsdown build. |
diff --git a/docs/4.configuration.md b/docs/4.configuration.md
index dcdb1ea4..52369111 100644
--- a/docs/4.configuration.md
+++ b/docs/4.configuration.md
@@ -163,6 +163,12 @@ The native compilers are several times faster, and run in one process for the wh
pnpm add -D @typescript/typescript7@npm:typescript@beta
```
+To make TypeScript 7 the module's `tsc` too, install `@typescript/typescript6` as its `typescript`. It provides the JavaScript API of TypeScript 6, which the build, `vue-tsc` 3.3.8 or later and other tools that import `typescript` use:
+
+```bash [Terminal]
+pnpm add -D typescript@npm:@typescript/typescript6 @typescript/typescript7@npm:typescript@beta
+```
+
The build checks that the package it finds is `typescript` 7.1 or later before it runs anything from it. Declarations of `.vue` files always come from `@vue/language-core`, the tooling that `vue-tsc` uses.
TypeScript 7 prints some types differently from TypeScript 6, such as string literal types with the quotes of the source, and reports some declaration errors with other codes, such as TS2883 instead of TS2742. They fail the build in the same way. See [Declarations](/docs/api/module-builder/typescript#declarations).
diff --git a/knip.json b/knip.json
index fed466aa..3773f17d 100644
--- a/knip.json
+++ b/knip.json
@@ -1,9 +1,11 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"ignore": [
- "test/__snapshots__/**"
+ "test/__snapshots__/**",
+ "test/typescript-from.cjs"
],
"ignoreDependencies": [
+ "@typescript/typescript6",
"@typescript/typescript7",
"rolldown-plugin-dts",
"tsrs"
diff --git a/package.json b/package.json
index 8a80944c..32fe0171 100644
--- a/package.json
+++ b/package.json
@@ -69,12 +69,16 @@
},
"peerDependencies": {
"@nuxt/cli": "^3.37.0 || ^4.0.0",
+ "@typescript/typescript6": "^6.0.0",
"@typescript/typescript7": "npm:typescript@>=7.1.0-beta",
"tsdown": "^0.23.7",
"tsrs": ">=7.1.0-beta.tsrs3",
"typescript": "^5.9.3 || ^6.0.0"
},
"peerDependenciesMeta": {
+ "@typescript/typescript6": {
+ "optional": true
+ },
"@typescript/typescript7": {
"optional": true
},
@@ -88,7 +92,9 @@
"@nuxt/cli": "^4.0.3",
"@nuxt/eslint-config": "^1.17.0",
"@nuxt/schema": "~4.6.4",
+ "@oxc-project/types": "^0.157.0",
"@types/node": "^26.6.6",
+ "@typescript/typescript6": "6.0.2",
"@typescript/typescript7": "npm:typescript@7.1.0-beta",
"@vitest/coverage-v8": "^5.1.0",
"eslint": "^10.14.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2c207f25..7e04b710 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -221,9 +221,15 @@ importers:
'@nuxt/schema':
specifier: ~4.6.4
version: 4.6.4
+ '@oxc-project/types':
+ specifier: ^0.157.0
+ version: 0.157.0
'@types/node':
specifier: ^26.6.6
version: 26.6.6
+ '@typescript/typescript6':
+ specifier: 6.0.2
+ version: 6.0.2
'@typescript/typescript7':
specifier: npm:typescript@7.1.0-beta
version: typescript@7.1.0-beta
@@ -2061,6 +2067,10 @@ packages:
cpu: [x64]
os: [win32]
+ '@typescript/typescript6@6.0.2':
+ resolution: {integrity: sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==}
+ hasBin: true
+
'@unhead/bundler@3.4.3':
resolution: {integrity: sha512-noUTzazRB4fMgO/nluoirrZJXngNbNb3sQzIslA805tKkwakRv2fib4Xe4EdiTuNB7V5XmpUFvfQkKRdBQ9qAA==}
peerDependencies:
@@ -7141,6 +7151,10 @@ snapshots:
'@typescript/typescript-win32-x64@7.1.0-beta':
optional: true
+ '@typescript/typescript6@6.0.2':
+ dependencies:
+ '@typescript/old': typescript@6.0.3
+
'@unhead/bundler@3.4.3(@oxc-project/types@0.157.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup@4.68.2)(unhead@3.4.3(esbuild@0.28.2)(rolldown@1.2.18)(rollup@4.68.2)(vite@8.3.7(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.1)(terser@5.51.2)(yaml@2.9.1)))(vite@8.3.7(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.1)(terser@5.51.2)(yaml@2.9.1))':
dependencies:
magic-string: 1.4.5
diff --git a/src/build/build.ts b/src/build/build.ts
index 77195852..dcc11f59 100644
--- a/src/build/build.ts
+++ b/src/build/build.ts
@@ -9,6 +9,7 @@ import { glob, globSync } from 'tinyglobby'
import builderPkg from '../../package.json' with { type: 'json' }
import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts'
+import { loadOxc } from '../transpile/oxc.ts'
import { EXCLUDE } from '../transpile/transpile-dir.ts'
import type { ResolveExternal } from '../transpile/transpile-dir.ts'
import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, TsconfigError, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts'
@@ -17,7 +18,7 @@ import { errors, warnings } from '../diagnostics.ts'
import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts'
import type { PackageJson } from '../utils.ts'
import { rewriteRuntimeDeclarations } from './aliases.ts'
-import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts'
+import { assertLoadableModuleCode, importModule } from './loader.ts'
import { bundledEntries, NUXT_EXTERNALS } from './options.ts'
import type { DirectoryEntry, ModuleConfig } from './options.ts'
import { checkPublishedPaths, importsKeyFor, publishedPackage, selfReferencePaths, unpublishableImportsError } from './package.ts'
diff --git a/src/build/directives.ts b/src/build/directives.ts
index c260b273..5818f022 100644
--- a/src/build/directives.ts
+++ b/src/build/directives.ts
@@ -1,37 +1,28 @@
-import type ts from 'typescript'
-
+import { parseModule } from '../transpile/oxc.ts'
import type { Transform } from '../transpile/transpile-dir.ts'
-const DIRECTIVE_RE = /@ts-(?:expect-error|ignore|nocheck|check)\b/g
+const DIRECTIVE_RE = /@ts-(?:expect-error|ignore|nocheck|check)\b/
const LINE_DIRECTIVE_RE = /^\/\/\/?[\t ]*@ts-(?:expect-error|ignore|nocheck|check)\b/
const BLOCK_DIRECTIVE_RE = /^[\t /*]*@ts-(?:expect-error|ignore)\b/
const LINE_TERMINATOR_RE = /\r\n?|[\n\u2028\u2029]/
const NOT_LINE_TERMINATOR_RE = /[^\n\r\u2028\u2029]/g
-const SCRIPT_KINDS: Record = { js: 'JS', jsx: 'JSX', ts: 'TS', tsx: 'TSX' }
-
/**
* `transform` with the TypeScript directive comments of the source, such as `// @ts-ignore`
* and `// @ts-expect-error`, replaced by spaces, so that the output leaves them out and its
* source map still matches the source. Other comments are kept.
*/
export function withoutDirectiveComments(transform: Transform): Transform {
- return async (filename, source, options) => transform(filename, source.search(DIRECTIVE_RE) === -1 ? source : await blankDirectiveComments(source, options?.lang ?? 'ts'), options)
+ return async (filename, source, options) => transform(filename, source.search(DIRECTIVE_RE) === -1 ? source : blankDirectiveComments(source, options?.lang ?? 'ts'), options)
}
-async function blankDirectiveComments(source: string, lang: string) {
- const { default: ts } = await import('typescript')
- const sourceFile = ts.createSourceFile(`source.${lang}`, source, ts.ScriptTarget.Latest, false, ts.ScriptKind[SCRIPT_KINDS[lang] ?? 'TS'])
- const comments = new Map()
- for (const { index } of source.matchAll(DIRECTIVE_RE)) {
- const comment = commentAt(ts, sourceFile, index)
- if (comment && isDirective(source.slice(comment.pos, comment.end))) {
- comments.set(comment.pos, comment.end)
- }
- }
+function blankDirectiveComments(source: string, lang: string) {
let result = source
- for (const [pos, end] of comments) {
- result = result.slice(0, pos) + source.slice(pos, end).replace(NOT_LINE_TERMINATOR_RE, ' ') + result.slice(end)
+ for (const { start, end } of parseModule(source, `source.${lang}`).comments) {
+ const comment = source.slice(start, end)
+ if (isDirective(comment)) {
+ result = result.slice(0, start) + comment.replace(NOT_LINE_TERMINATOR_RE, ' ') + result.slice(end)
+ }
}
return result
}
@@ -40,44 +31,3 @@ async function blankDirectiveComments(source: string, lang: string) {
function isDirective(comment: string) {
return comment.startsWith('/*') ? BLOCK_DIRECTIVE_RE.test(comment.split(LINE_TERMINATOR_RE).at(-1)!) : LINE_DIRECTIVE_RE.test(comment)
}
-
-/**
- * The comment that holds `offset`, or `undefined` when `offset` is not in a comment, such as in
- * a string, a template or JSX text.
- */
-function commentAt(ts: typeof import('typescript'), sourceFile: ts.SourceFile, offset: number) {
- const text = sourceFile.text
- const holding = (pos: number) => [...ts.getTrailingCommentRanges(text, pos) ?? [], ...ts.getLeadingCommentRanges(text, pos) ?? []].find(range => range.pos <= offset && offset < range.end)
- let node: ts.Node = sourceFile
- for (;;) {
- let containing: ts.Node | undefined
- let before: ts.Node | undefined
- ts.forEachChild(node, (child) => {
- if (child.end <= offset) {
- before = child
- return
- }
- if (child.pos <= offset) {
- containing = child
- }
- return true
- })
- if (!containing) {
- if (!before && node.kind < ts.SyntaxKind.FirstNode) {
- return
- }
- // Between its children, a node holds only punctuation, keywords and trivia.
- const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, sourceFile.languageVariant, text, undefined, before ? before.end : node.getStart(sourceFile))
- for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken && scanner.getTokenStart() <= offset; kind = scanner.scan()) {
- if ((kind === ts.SyntaxKind.SingleLineCommentTrivia || kind === ts.SyntaxKind.MultiLineCommentTrivia) && offset < scanner.getTokenEnd()) {
- return { pos: scanner.getTokenStart(), end: scanner.getTokenEnd() }
- }
- }
- return
- }
- if (offset < containing.getStart(sourceFile)) {
- return holding(containing.pos)
- }
- node = containing
- }
-}
diff --git a/src/build/engine.ts b/src/build/engine.ts
index bc324ffa..c7e68842 100644
--- a/src/build/engine.ts
+++ b/src/build/engine.ts
@@ -3,6 +3,7 @@ import { ENGINES } from '../transpile/engine.ts'
import type { DeclarationEngine, DeclarationEngineName } from '../transpile/engine.ts'
import { createNativeEngine, hasNativeTypescript, installedNativeEngine, NativeEngineError } from '../transpile/native.ts'
import type { NativeEngineName } from '../transpile/native.ts'
+import { loadTypescript, TYPESCRIPT6, TypescriptApiError } from '../transpile/typescript.ts'
import { isDeclarationEngine } from './options.ts'
import type { ModuleConfig } from './options.ts'
@@ -26,11 +27,16 @@ function selectedEngine(config: Pick): { engi
return config.declarationEngine && { engine: config.declarationEngine, setting: '`declarations.engine`' }
}
-/** Fails when the module's own `typescript` has no JavaScript API, as TypeScript 7 has none. */
+/** Fails when neither the module's own `typescript` nor `@typescript/typescript6` has the JavaScript API of TypeScript 6, see `loadTypescript`. */
export async function assertSupportedTypescript(): Promise {
- const ts = (await import('typescript')).default as Partial & { version: string }
- if (typeof ts.createProgram !== 'function') {
- throw errors.NUXT_MB_B0005({ version: ts.version, install: INSTALL[ENGINES.typescript7] })
+ try {
+ loadTypescript()
+ }
+ catch (error) {
+ if (error instanceof TypescriptApiError) {
+ throw errors.NUXT_MB_B0005({ found: error.found, fallback: error.fallback, install: `pnpm add -D ${TYPESCRIPT6}` })
+ }
+ throw error
}
}
diff --git a/src/build/loader.ts b/src/build/loader.ts
index ab774180..30c0bc93 100644
--- a/src/build/loader.ts
+++ b/src/build/loader.ts
@@ -1,14 +1,15 @@
import { existsSync, readFileSync } from 'node:fs'
-import { createRequire, registerHooks } from 'node:module'
+import { registerHooks } from 'node:module'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { dirname, join, relative, resolve } from 'pathe'
import { createPathsMatcher, getTsconfig } from 'get-tsconfig'
import type { Diagnostic } from 'nostics'
-import type ts from 'typescript'
+import type { Expression, ImportDeclaration, ObjectExpression, TSGlobalDeclaration, TSModuleDeclaration } from '@oxc-project/types'
-import type { Transform } from '../transpile/transpile-dir.ts'
+import { literalText, parseModule, walk } from '../transpile/oxc.ts'
+import type { Node } from '../transpile/oxc.ts'
import { packageName } from '../transpile/tsconfig.ts'
-import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts'
+import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE } from '../utils.ts'
import type { PackageJson } from '../utils.ts'
import { errors } from '../diagnostics.ts'
import { importsKeyFor } from './package.ts'
@@ -63,26 +64,6 @@ export async function importModule(path: string, { cwd, stubs = {}, version }: I
}
}
-interface Oxc {
- transform: Transform
- transformSync: (...args: Parameters) => Awaited>
-}
-
-let oxc: Oxc | null | undefined
-
-/** The oxc bindings of the `rolldown` that `tsdown` depends on, or `null` when `tsdown` is not installed. */
-export function loadOxc(): Oxc | null {
- if (oxc === undefined) {
- try {
- oxc = createRequire(import.meta.resolve('tsdown'))('rolldown/utils') as Oxc
- }
- catch {
- oxc = null
- }
- }
- return oxc
-}
-
export interface ModuleCodeIssue {
/** Path relative to the module root. */
file: string
@@ -96,14 +77,14 @@ export interface ModuleCodeIssue {
unfollowed?: true
}
-const NON_ERASABLE: Array<[message: string, matches: (ts: typeof import('typescript'), node: ts.Node) => boolean]> = [
- ['`enum` (use an `as const` object and a union type of its values)', (ts, node) => ts.isEnumDeclaration(node)],
- ['`namespace` (use plain exports or an object)', (ts, node) => ts.isModuleDeclaration(node) && ts.isIdentifier(node.name) && !(node.flags & (ts.NodeFlags.NestedNamespace | ts.NodeFlags.GlobalAugmentation)) && hasRuntimeCode(ts, node)],
- ['angle-bracket type assertion (write `value as Type`)', (ts, node) => ts.isTypeAssertionExpression(node)],
- ['parameter property (declare the field and assign it in the constructor)', (ts, node) => ts.isParameter(node) && ts.isParameterPropertyDeclaration(node, node.parent)],
- ['`import =` (use `import`, or `createRequire` for CommonJS)', (ts, node) => ts.isImportEqualsDeclaration(node) && !node.isTypeOnly],
- ['`export =` (use `export default`)', (ts, node) => ts.isExportAssignment(node) && !!node.isExportEquals],
- ['decorator (call the decorator as a function)', (ts, node) => ts.isDecorator(node)],
+const NON_ERASABLE: Array<[message: string, matches: (node: Node, parent: Node | undefined, grandparent: Node | undefined) => boolean]> = [
+ ['`enum` (use an `as const` object and a union type of its values)', node => node.type === 'TSEnumDeclaration'],
+ ['`namespace` (use plain exports or an object)', node => node.type === 'TSModuleDeclaration' && node.id.type !== 'Literal' && node.kind !== 'global' && hasRuntimeCode(node)],
+ ['angle-bracket type assertion (write `value as Type`)', node => node.type === 'TSTypeAssertion'],
+ ['parameter property (declare the field and assign it in the constructor)', (node, _, method) => node.type === 'TSParameterProperty' && method?.type === 'MethodDefinition' && method.kind === 'constructor'],
+ ['`import =` (use `import`, or `createRequire` for CommonJS)', node => node.type === 'TSImportEqualsDeclaration' && node.importKind !== 'type'],
+ ['`export =` (use `export default`)', node => node.type === 'TSExportAssignment'],
+ ['decorator (call the decorator as a function)', node => node.type === 'Decorator'],
]
/**
@@ -319,90 +300,95 @@ function importTarget(target: unknown, match: string | undefined): string | unde
}
}
-let typescript: typeof ts | undefined
-
-function scriptKind(ts: typeof import('typescript'), filename: string) {
- if (TYPESCRIPT_RE.test(filename)) {
- return filename.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
- }
- return filename.endsWith('x') ? ts.ScriptKind.JSX : ts.ScriptKind.JS
+function hasRuntimeCode(node: TSModuleDeclaration | TSGlobalDeclaration): boolean {
+ return !!node.body?.body.some((statement) => {
+ const declaration = statement.type === 'ExportNamedDeclaration' && statement.declaration ? statement.declaration : statement
+ return !(declaration.type === 'TSInterfaceDeclaration' || declaration.type === 'TSTypeAliasDeclaration' || (declaration.type === 'TSModuleDeclaration' && !hasRuntimeCode(declaration)))
+ })
}
-function hasRuntimeCode(ts: typeof import('typescript'), node: ts.ModuleDeclaration): boolean {
- const { body } = node
- if (!body) {
- return false
- }
- if (ts.isModuleDeclaration(body)) {
- return hasRuntimeCode(ts, body)
+const LINE_BREAK_RE = /\r\n?|[\n\u2028\u2029]/g
+
+/** The 1-based line and column of each offset of `source`, in UTF-16 code units. */
+function lineColumns(source: string) {
+ const starts = [0, ...[...source.matchAll(LINE_BREAK_RE)].map(({ index, 0: lineBreak }) => index + lineBreak.length)]
+ return (offset: number) => {
+ let low = 0
+ let high = starts.length - 1
+ while (low < high) {
+ const middle = (low + high + 1) >> 1
+ if (starts[middle]! <= offset) {
+ low = middle
+ }
+ else {
+ high = middle - 1
+ }
+ }
+ return { line: low + 1, column: offset - starts[low]! + 1 }
}
- return ts.isModuleBlock(body) && body.statements.some(statement => !(
- ts.isInterfaceDeclaration(statement)
- || ts.isTypeAliasDeclaration(statement)
- || (ts.isModuleDeclaration(statement) && !hasRuntimeCode(ts, statement))
- ))
}
+type ImportAttributes = ImportDeclaration['attributes']
+
function analyseSource(filename: string, source: string): SourceAnalysis {
- const ts = typescript ??= createRequire(import.meta.url)('typescript') as typeof import('typescript')
- const { SyntaxKind } = ts
- const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(ts, filename))
+ const position = lineColumns(source)
const found: SourceAnalysis = { nonErasable: [], imports: [] }
- const position = (node: ts.Node) => {
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
- return { line: line + 1, column: character + 1 }
- }
- const isJson = (attributes: ts.ImportAttributes | undefined) => !!attributes?.elements.some(element => element.name.text === 'type' && ts.isStringLiteral(element.value) && element.value.text === 'json')
+ const isJson = (attributes: ImportAttributes) => attributes.some(({ key, value }) => (key.type === 'Literal' ? key.value : key.name) === 'type' && value.value === 'json')
// `true` when the value is not known statically.
- const property = (object: ts.ObjectLiteralExpression, name: string): ts.Expression | true | undefined => {
+ const property = (object: ObjectExpression, name: string): Expression | true | undefined => {
for (const property of [...object.properties].reverse()) {
- if (ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))) {
- if (property.name.text === name) {
- return property.initializer
+ const key = property.type === 'Property' && !property.computed ? property.key : undefined
+ const keyName = key?.type === 'Identifier' ? key.name : key?.type === 'Literal' && typeof key.value === 'string' ? key.value : undefined
+ if (property.type === 'Property' && property.kind === 'init' && !property.method && !property.shorthand && keyName !== undefined) {
+ if (keyName === name) {
+ return property.value as Expression
}
}
- else if (!ts.isShorthandPropertyAssignment(property) || property.name.text === name) {
+ else if (!(property.type === 'Property' && property.shorthand) || keyName === name) {
return true
}
}
}
- const isJsonOptions = (options: ts.Expression | undefined) => {
- if (!options || !ts.isObjectLiteralExpression(options)) {
+ const isJsonOptions = (options: Expression | null) => {
+ if (options?.type !== 'ObjectExpression') {
return !!options
}
const attributes = property(options, 'with')
- if (!attributes || attributes === true || !ts.isObjectLiteralExpression(attributes)) {
+ if (!attributes || attributes === true || attributes.type !== 'ObjectExpression') {
return !!attributes
}
const type = property(attributes, 'type')
- return !!type && (type === true || !ts.isStringLiteralLike(type) || type.text === 'json')
+ return !!type && (type === true || literalText(type) === undefined || literalText(type) === 'json')
}
- const specifierOf = (node: ts.Node) => {
- if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
- return { specifier: node.moduleSpecifier, typeOnly: node.importClause?.isTypeOnly ?? false, json: isJson(node.attributes) }
+ const specifierOf = (node: Node) => {
+ if (node.type === 'ImportDeclaration') {
+ return { specifier: node.source, typeOnly: node.importKind === 'type', json: isJson(node.attributes) }
}
- if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
- return { specifier: node.moduleSpecifier, typeOnly: node.isTypeOnly, json: isJson(node.attributes) }
+ if ((node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') && node.source) {
+ return { specifier: node.source, typeOnly: node.exportKind === 'type', json: isJson(node.attributes) }
}
- if (ts.isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) {
- return { specifier: node.arguments[0], typeOnly: false, json: isJsonOptions(node.arguments[1]) }
+ if (node.type === 'ImportExpression' && literalText(node.source) !== undefined) {
+ return { specifier: node.source, typeOnly: false, json: isJsonOptions(node.options) }
}
}
- const visit = (node: ts.Node) => {
- if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) {
- return
+ const parents = new Map()
+ walk(parseModule(source, filename).program, (node, parent) => {
+ if ('declare' in node && node.declare) {
+ return false
+ }
+ if (parent) {
+ parents.set(node, parent)
}
- const nonErasable = NON_ERASABLE.find(([, matches]) => matches(ts, node))
+ const nonErasable = NON_ERASABLE.find(([, matches]) => matches(node, parent, parent && parents.get(parent)))
if (nonErasable) {
- found.nonErasable.push({ ...position(node), message: nonErasable[0] })
+ found.nonErasable.push({ ...position(parent?.type === 'ExportNamedDeclaration' ? parent.start : node.start), message: nonErasable[0] })
}
const imported = specifierOf(node)
if (imported) {
- found.imports.push({ specifier: imported.specifier.text, typeOnly: imported.typeOnly, json: imported.json, ...position(imported.specifier) })
+ found.imports.push({ specifier: literalText(imported.specifier)!, typeOnly: imported.typeOnly, json: imported.json, ...position(imported.specifier.start) })
}
- ts.forEachChild(node, visit)
- }
- visit(sourceFile)
+ })
+ found.imports.sort((a, b) => a.line - b.line || a.column - b.column)
return found
}
diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts
index f3a794d1..2d3ac34e 100644
--- a/src/build/module-declarations.ts
+++ b/src/build/module-declarations.ts
@@ -5,10 +5,10 @@ import { dirname, join, normalize, relative, resolve } from 'pathe'
import { warnings } from '../diagnostics.ts'
import { createDeclarationProgram } from '../transpile/declarations.ts'
import type { DeclarationEngine } from '../transpile/engine.ts'
+import { loadOxc } from '../transpile/oxc.ts'
import { moduleSpecifiers, rewriteSpecifiers } from '../transpile/specifiers.ts'
import { hasIsolatedDeclarations, isModuleFile } from '../transpile/tsconfig.ts'
import { isInside, isSourceScript, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts'
-import { loadOxc } from './loader.ts'
import { writeSourceTypes } from './types.ts'
const NUXT_DIR_RE = /^\.nuxt(?:\/|$)/
diff --git a/src/build/types.ts b/src/build/types.ts
index 13c5026b..175bddbf 100644
--- a/src/build/types.ts
+++ b/src/build/types.ts
@@ -1,8 +1,8 @@
import { existsSync, promises as fsp, readFileSync } from 'node:fs'
import { dirname, relative, resolve } from 'pathe'
-import type ts from 'typescript'
+import type { BindingPattern, Declaration, ModuleExportName, TSTypeName } from '@oxc-project/types'
-import { parseModule } from '../transpile/specifiers.ts'
+import { parseModule } from '../transpile/oxc.ts'
import { probe, writeIfChanged } from '../utils.ts'
interface ExportedName {
@@ -155,47 +155,50 @@ function probeWithDeclarations(path: string) {
}
function parseExports(code: string, filename: string): ModuleExport[] {
- const { ts, sourceFile } = parseModule(code, filename)
const exports: ModuleExport[] = []
- const hasModifier = (node: ts.Node, kind: ts.SyntaxKind) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(modifier => modifier.kind === kind)
- for (const statement of sourceFile.statements) {
- if (ts.isExportDeclaration(statement)) {
- const specifier = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : undefined
- const clause = statement.exportClause
- if (clause && ts.isNamedExports(clause)) {
- exports.push({ specifier, names: clause.elements.map(element => ({ name: element.name.text, typeOnly: statement.isTypeOnly || element.isTypeOnly })) })
- }
- else if (specifier) {
- exports.push({ specifier, star: { typeOnly: statement.isTypeOnly }, names: clause ? [{ name: clause.name.text, typeOnly: statement.isTypeOnly }] : [] })
- }
+ for (const statement of parseModule(code, filename).program.body) {
+ if (statement.type === 'ExportNamedDeclaration' && statement.declaration) {
+ const { declaration } = statement
+ const typeOnly = declaration.type === 'TSInterfaceDeclaration' || declaration.type === 'TSTypeAliasDeclaration'
+ exports.push({ names: declaredNames(declaration).map(name => ({ name, typeOnly })) })
}
- else if (ts.isExportAssignment(statement)) {
- if (!statement.isExportEquals) {
- exports.push({ names: [{ name: 'default', typeOnly: false }] })
- }
+ else if (statement.type === 'ExportNamedDeclaration') {
+ exports.push({ specifier: statement.source?.value, names: statement.specifiers.map(element => ({ name: moduleExportName(element.exported), typeOnly: statement.exportKind === 'type' || element.exportKind === 'type' })) })
}
- else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword)) {
- const typeOnly = ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)
- const names = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? ['default'] : declaredNames(ts, statement)
- exports.push({ names: names.map(name => ({ name, typeOnly })) })
+ else if (statement.type === 'ExportAllDeclaration') {
+ const typeOnly = statement.exportKind === 'type'
+ exports.push({ specifier: statement.source.value, star: { typeOnly }, names: statement.exported ? [{ name: moduleExportName(statement.exported), typeOnly }] : [] })
+ }
+ else if (statement.type === 'ExportDefaultDeclaration') {
+ exports.push({ names: [{ name: 'default', typeOnly: statement.declaration.type === 'TSInterfaceDeclaration' }] })
}
}
return exports
}
-function declaredNames(ts: typeof import('typescript'), statement: ts.Statement): string[] {
- if (ts.isVariableStatement(statement)) {
- return statement.declarationList.declarations.flatMap(declaration => bindingNames(ts, declaration.name))
+const moduleExportName = (name: ModuleExportName) => name.type === 'Literal' ? name.value : name.name
+
+const leftmost = (name: TSTypeName): TSTypeName => name.type === 'TSQualifiedName' ? leftmost(name.left) : name
+
+function declaredNames(declaration: Declaration): string[] {
+ if (declaration.type === 'VariableDeclaration') {
+ return declaration.declarations.flatMap(declarator => bindingNames(declarator.id))
}
- const name = (statement as ts.DeclarationStatement).name
- return name && ts.isIdentifier(name) ? [name.text] : []
+ const id = 'id' in declaration && declaration.id ? declaration.id.type === 'TSQualifiedName' ? leftmost(declaration.id) : declaration.id : undefined
+ return id?.type === 'Identifier' ? [id.name] : []
}
-function bindingNames(ts: typeof import('typescript'), name: ts.BindingName): string[] {
- if (ts.isIdentifier(name)) {
- return [name.text]
+function bindingNames(pattern: BindingPattern): string[] {
+ switch (pattern.type) {
+ case 'Identifier':
+ return [pattern.name]
+ case 'AssignmentPattern':
+ return bindingNames(pattern.left)
+ case 'ObjectPattern':
+ return pattern.properties.flatMap(property => bindingNames(property.type === 'RestElement' ? property.argument : property.value))
+ case 'ArrayPattern':
+ return pattern.elements.flatMap(element => !element ? [] : bindingNames(element.type === 'RestElement' ? element.argument : element))
}
- return name.elements.flatMap(element => ts.isBindingElement(element) ? bindingNames(ts, element.name) : [])
}
/** The names that `exports` declare or re-export by name, sorted with `default` last. */
diff --git a/src/build/unchecked.ts b/src/build/unchecked.ts
index 96720159..8b88fa8f 100644
--- a/src/build/unchecked.ts
+++ b/src/build/unchecked.ts
@@ -4,6 +4,7 @@ import { glob } from 'tinyglobby'
import { warnings } from '../diagnostics.ts'
import type { TsconfigResolver } from '../transpile/tsconfig.ts'
+import { loadTypescript } from '../transpile/typescript.ts'
import { moduleTsconfigs } from './build.ts'
const NUXT_BUILD_DIR_RE = /[\\/]\.nuxt(?:[\\/]|$)/
@@ -30,7 +31,7 @@ async function uncheckedFiles(cwd: string, tsconfigs: TsconfigResolver, { outDir
if (!root?.config.references?.length || tsconfigs.replaced) {
return groups
}
- const { default: ts } = await import('typescript')
+ const { ts } = loadTypescript()
const ownExcludes = root.config.references.flatMap(({ path }) => {
const file = resolve(dirname(root.path), path)
const config = file.endsWith('.json') ? file : join(file, 'tsconfig.json')
diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts
index 4fca71bf..3aa93073 100644
--- a/src/commands/prepare.ts
+++ b/src/commands/prepare.ts
@@ -17,6 +17,8 @@ import { augmentsNuxtTypes, writeSourceTypes } from '../build/types.ts'
import { noteUncheckedFiles } from '../build/unchecked.ts'
import { loadBuildConfig } from '../legacy/build-config.ts'
import { hasIsolatedDeclarations, isModuleFile, rootTsconfig, writeDependencyImports } from '../transpile/tsconfig.ts'
+import { parseModule, walk } from '../transpile/oxc.ts'
+import type { Program } from '../transpile/oxc.ts'
import { isInside, probe, readPackageJson, resolveFrom } from '../utils.ts'
import type { PackageJson } from '../utils.ts'
import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts'
@@ -54,8 +56,19 @@ async function declaresModules(cwd: string, runtimeDirs: string[], entries: stri
return sources.some(source => DECLARE_RE.test(source))
}
+const MODULE_STATEMENTS = new Set(['ImportDeclaration', 'ExportNamedDeclaration', 'ExportDefaultDeclaration', 'ExportAllDeclaration', 'TSExportAssignment'])
+
+/** Whether TypeScript reads `program` as a module, rather than as a script that declares globals. */
+function isExternalModule(program: Program) {
+ let importMeta = false
+ walk(program, (node) => {
+ importMeta ||= node.type === 'MetaProperty' && node.meta.name === 'import'
+ return !importMeta
+ })
+ return importMeta || program.body.some(statement => MODULE_STATEMENTS.has(statement.type) || (statement.type === 'TSImportEqualsDeclaration' && statement.moduleReference.type === 'TSExternalModuleReference'))
+}
+
async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude: string[]) {
- const { default: ts } = await import('typescript')
const ignore = [...runtimeDirs, ...exclude].flatMap((pattern) => {
const path = relative(cwd, pattern)
return [path, `${path}/**`]
@@ -64,11 +77,11 @@ async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude:
const globals: string[] = []
const augmentations: string[] = []
for (const file of files.filter(file => isModuleFile(file, cwd)).sort()) {
- const source = ts.createSourceFile(file, await readFile(file, 'utf8'), ts.ScriptTarget.Latest)
- if (!ts.isExternalModule(source)) {
+ const { program } = parseModule(await readFile(file, 'utf8'), file)
+ if (!isExternalModule(program)) {
globals.push(file)
}
- else if (source.statements.some(statement => ts.isModuleDeclaration(statement))) {
+ else if (program.body.some(statement => (statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement)?.type === 'TSModuleDeclaration')) {
augmentations.push(file)
}
}
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
index ea744370..b8c10864 100644
--- a/src/diagnostics.ts
+++ b/src/diagnostics.ts
@@ -73,8 +73,8 @@ export const errorCodes = {
docs: '#bundled-packages',
},
NUXT_MB_B0005: {
- why: (p: { version: string }): string => `\`@nuxt/module-builder\` uses the JavaScript API of the module's \`typescript\`, which needs \`${pkg.peerDependencies.typescript}\`, and the module has \`typescript@${p.version}\`, which has no JavaScript API.`,
- fix: (p: { install: string }): string => `Install TypeScript 6 as the module's \`typescript\` with \`pnpm add -D typescript@^6.0.0\`. To generate declarations with TypeScript 7, install it next to TypeScript 6 with \`${p.install}\`.`,
+ why: (p: { found?: string, fallback?: string }): string => `\`@nuxt/module-builder\` uses the JavaScript API of TypeScript, from the module's \`typescript\` (\`${pkg.peerDependencies.typescript}\`) or else from \`@typescript/typescript6\`. ${p.found ? `The module has \`${p.found}\`, which has no JavaScript API` : 'The module has no `typescript`'}, and ${p.fallback ? `\`@typescript/typescript6\` resolves to \`${p.fallback}\`, which is not \`@typescript/typescript6@^6.0.0\`` : '`@typescript/typescript6` is not installed'}.`,
+ fix: (p: { install: string }): string => `Install the JavaScript API of TypeScript 6 next to TypeScript 7 with \`${p.install}\`, or install TypeScript 6 as the module's \`typescript\` with \`pnpm add -D typescript@^6.0.0\`.`,
docs: false,
},
diff --git a/src/transpile/declarations.ts b/src/transpile/declarations.ts
index 01727fba..c195d8be 100644
--- a/src/transpile/declarations.ts
+++ b/src/transpile/declarations.ts
@@ -1,11 +1,13 @@
import { readFile } from 'node:fs/promises'
import type { TsConfigResult } from 'get-tsconfig'
import { relative } from 'pathe'
-import type ts from 'typescript'
+import type { ImportDeclaration, ImportSpecifier, ModuleExportName, TSQualifiedName } from '@oxc-project/types'
import { contentCache } from './cache.ts'
import { createTscEngine } from './engine.ts'
import type { DeclarationEngine, DeclarationProject, EngineDiagnostic, ProjectOptions, SourceFileCache } from './engine.ts'
+import { parseModule, walk } from './oxc.ts'
+import type { Node } from './oxc.ts'
import { isModuleFile, writeDeclarationPaths } from './tsconfig.ts'
export type { SourceFileCache } from './engine.ts'
@@ -164,7 +166,124 @@ function formatDiagnostic(diagnostic: EngineDiagnostic, cwd: string): string {
return diagnostic.file && diagnostic.line !== undefined ? `${relative(cwd, diagnostic.file)}(${diagnostic.line},${diagnostic.column}): ${prefix}` : prefix
}
-const SFC_SCRIPT_RE = /