diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..e535a648
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,137 @@
+# Contributing
+
+## Setup
+
+`package.json` pins Node and pnpm in `devEngines`, and pnpm downloads them when they are missing.
+
+```bash
+pnpm install
+pnpm dev:prepare
+```
+
+| Script | What it runs |
+|---|---|
+| `pnpm build` | `tsdown`, building this package into `dist` |
+| `pnpm test` | the vitest suite (`pnpm vitest run` for one pass) |
+| `pnpm test:types` | `vue-tsc` over the package and the example |
+| `pnpm test:knip` | unused files, exports and dependencies |
+| `pnpm test:pack` | packs the example and checks it with attw and publint |
+| `pnpm lint` | ESLint |
+| `pnpm nuxt-module-build` | the CLI from source, for example `pnpm nuxt-module-build build ./example` |
+
+Pages in [`docs/`](./docs) are published on [nuxt.com](https://nuxt.com), so links between them use nuxt.com paths. Build messages link to headings of [`docs/upgrade-v2.md`](./docs/upgrade-v2.md) through `guide()` in `src/build/guide.ts`. A unit test checks that every linked heading exists.
+
+## Architecture
+
+The package has three entry points:
+
+- **`src/cli.ts`** is the `nuxt-module-build` binary, also run as `nuxt build-module`. It has two subcommands, `build` and `prepare`.
+- **`src/tsdown/index.ts`** exports `builder()`, the tsdown plugin that builds a module. This is how modules build: `tsdown` with `plugins: [builder()]`.
+- **`src/index.ts`** exports `build`, `prepare` and the unbuild-compatible `defineBuildConfig`.
+
+### Layout
+
+| Directory | Contents |
+|---|---|
+| `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. `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. |
+| `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`, 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/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). |
+| `src/utils.ts` | Path, file and regex helpers shared across directories. |
+
+### `tsdown` with `builder()`
+
+`builder()` acts in tsdown's `tsdownConfig` hook. `setupBuilder` then:
+
+1. Refuses tsdown options that `builder()` sets itself, resolves the module root (following symlinks) and the output directory, and checks the published `package.json` paths.
+2. Resolves the `builder()` options into a `ModuleConfig` (`src/build/options.ts`). When `.nuxt` is missing, it runs `prepare` first.
+3. Resolves a `BuildPlan` (`resolveBuild` in `src/build/build.ts`), with these parts:
+ - the bundled entries (`src/module` and `entries`);
+ - the transpiled directories (`src/runtime` and directory entries);
+ - the tsconfigs for declarations;
+ - the module's self-reference paths;
+ - a cache key for `.vue` declarations.
+4. Sets `entry`, `format`, `dts`, `clean` and `deps.neverBundle`. Adds `runtimeExternals` (bundled code imports runtime files from `dist` instead of inlining them), the declaration externals, replacements, and one `transpileDir()` per directory.
+
+Then, once per build:
+
+- **`build:prepare`** runs `prepareBuild`:
+ - the `build:before` hook;
+ - the check that module code loads with Node;
+ - emptying the output directory;
+ - the derived tsconfig that declaration generation reads.
+- **During the bundle**, the bundled entries and each `transpileDir()` emit their files.
+- **After writing**, `finishBuild` does the rest. Any failure removes the output directory, except in watch mode.
+ - Imports the built `module.mjs` to write `module.json`.
+ - Writes `types.d.mts`.
+ - Rewrites `#app` in declarations.
+ - Checks the package `imports` that the output uses.
+ - Runs the `build:done` hook.
+
+In watch mode the output directory is kept, unchanged files aren't rewritten (`unchanged.ts`), and files a rebuild no longer emits are removed.
+
+### `nuxt-module-build build`
+
+`src/tsdown/build.ts` runs tsdown programmatically. With a tsdown config in the module root, it builds with that config and fails unless it uses `builder()`. Without one, it builds with `createBuilder()` and `loadLegacyModuleConfig`. That reads `build.config.*` or the `build` field of `package.json`, so a v1 module builds without a tsdown config.
+
+### `nuxt-module-build prepare`
+
+`src/commands/prepare.ts` does the following:
+
+1. Loads the same options as a build.
+2. Checks that module code loads with Node, then imports `src/module.ts` with `importModule`.
+3. Runs `nuxt prepare` on the module root with that module installed.
+
+That writes `.nuxt`, including:
+
+- the tsconfigs of each context;
+- `.nuxt/module-builder/types.d.mts`, which source exports point at;
+- the declarations that resolve the module's own package name inside its type checks.
+
+### Module code loads with Node
+
+Nuxt 5, and a playground that loads the module from its sources, import `src/module.ts` with Node as written. Node strips types and resolves imports exactly as they are written. `findModuleCodeIssues` in `src/build/loader.ts` reports each import and each piece of syntax that breaks this, with its file, line, column and fix. `build`, `tsdown` and `prepare` all stop on these findings. Keep this check strict: code that passes it has to run under Node.
+
+### Legacy code
+
+`src/legacy/` holds what only v1 and unbuild users need:
+
+- `build-config.ts` reads and translates `build.config.*` and the `build`/`unbuild` fields of `package.json`, and emulates the unbuild hooks.
+- `define.ts` contains `defineBuildConfig` and its types.
+- `package-paths.ts` explains v1 `package.json` paths such as `module.cjs`.
+
+Core code doesn't import legacy types. The call sites are:
+
+- `src/index.ts`
+- `src/tsdown/build.ts`
+- `src/commands/prepare.ts`
+- `src/build/options.ts`
+- `src/build/package.ts`
+
+Their tests live in `test/legacy.spec.ts`. To drop unbuild compatibility, delete the directory and that spec, then fix the call sites.
+
+## Tests
+
+| Spec | Surface |
+|---|---|
+| `test/cli.spec.ts` | `nuxt-module-build build` and `prepare` |
+| `test/builder.spec.ts` | `tsdown` with `builder()`, and tsconfig `references` |
+| `test/watch.spec.ts` | `tsdown --watch` |
+| `test/transpile-dir.spec.ts` | `transpileDir()` on its own |
+| `test/legacy.spec.ts` | `build.config.*`, the `build` field, `defineBuildConfig` |
+| `test/unit.spec.ts` | pure helpers |
+
+Each e2e spec builds its fixtures in one `beforeAll`, in parallel, and its `it` blocks only read the results:
+
+- `fixture()` in `test/utils.ts` copies `example/` (or another fixture) into a gitignored `.temp-*` directory, with files, `package.json` fields and tsconfig `paths` changed.
+- `cli()`, `tsdown()` and `run()` start processes, and the number running at once is capped at one per CPU.
+
+Add a case to an existing fixture when it doesn't conflict with that fixture's other cases, and create a new fixture only when it does. Name tests `it('should ...')`.
+
+Coverage of the CLI processes:
+
+```bash
+NODE_V8_COVERAGE=/tmp/cov pnpm vitest run
+pnpm dlx c8@10 report --temp-directory /tmp/cov --include 'src/**' --reporter text --all --src .
+```
diff --git a/README.md b/README.md
index f3ee94d8..4779d142 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ Create a module from the [module starter](https://github.com/nuxt/starter/tree/m
npm create nuxt -- -t module my-module
```
-Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `typescript` installed alongside `@nuxt/module-builder`. Apps that install a built module need Nuxt 3 or later.
+Building a module requires Node `^22.18.0 || ^24.11.0 || >=26.0.0`, with `tsdown` and `typescript` installed alongside `@nuxt/module-builder`. Apps that install a built module need Nuxt 3 or later.
## Documentation
@@ -35,19 +35,13 @@ Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `types
- [TypeScript](./docs/5.typescript.md): the module's `tsconfig.json`, and its declarations
- [Build output](./docs/6.output.md)
- [Exports](./docs/7.exports.md): subpath exports, including runtime components
-- [Transpiling a directory](./docs/8.transpile-dir.md): the `transpileDir` rolldown plugin
- [Upgrading to v2](./docs/upgrade-v2.md)
For writing the module itself, read the [Nuxt Module Author Guide](https://nuxt.com/docs/guide/modules).
## 💻 Development
-- Clone repository
-- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
-- Install dependencies using `pnpm install`
-- Try building [example module](./example) using `pnpm example:build`
-
-Pages in [`docs/`](./docs) are written for [nuxt.com](https://nuxt.com), so links between them use nuxt.com paths.
+See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, the architecture and the tests.
## License
diff --git a/docs/2.commands.md b/docs/2.commands.md
index 6649a6b1..87471992 100644
--- a/docs/2.commands.md
+++ b/docs/2.commands.md
@@ -13,7 +13,7 @@ You build a module with `tsdown`, which reads the [`builder()` plugin](/docs/gui
- `build` builds the module, with or without a `tsdown.config.ts`.
- `prepare` generates the `.nuxt` directory that types the module.
-Name the subcommand every time. `nuxt-module-build` without a subcommand runs `build` and prints a warning.
+Name the subcommand every time: `nuxt-module-build` without one prints its usage.
The Nuxt CLI runs the same subcommands as [`nuxt build-module`](/docs/api/commands/build-module), so `nuxt build-module build` is the same as `nuxt-module-build build`. To see how a module's scripts combine these commands, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish).
diff --git a/docs/4.configuration.md b/docs/4.configuration.md
index e748c809..62ba5a92 100644
--- a/docs/4.configuration.md
+++ b/docs/4.configuration.md
@@ -54,7 +54,7 @@ An entry is either bundled into one file, like `src/module.ts`, or transpiled fi
| Option | Description |
|---|---|
| `input` | The entry file, relative to the module root. You can leave out the extension. |
-| `name` | The output name. Defaults to `input` without `src/` and without its extension. |
+| `name` | The output name. Defaults to `input` without `src/` and without its extension. It can't be `types`, as the build writes `dist/types.d.mts` itself. |
The build writes each bundled entry to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries in the example above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries).
diff --git a/docs/8.transpile-dir.md b/docs/8.transpile-dir.md
deleted file mode 100644
index 9b684e07..00000000
--- a/docs/8.transpile-dir.md
+++ /dev/null
@@ -1,120 +0,0 @@
----
-title: Transpiling a Directory
-description: Use the `transpileDir` rolldown plugin to transpile a directory file by file in any tsdown or rolldown build.
----
-
-`builder()` transpiles the runtime directory with a rolldown plugin, `transpileDir`, which `@nuxt/module-builder/rolldown` exports. Use it in any tsdown or rolldown build that transpiles a directory file by file instead of bundling it, such as a library that isn't a Nuxt module:
-
-```ts [tsdown.config.ts]
-import { defineConfig } from 'tsdown'
-import { transpileDir } from '@nuxt/module-builder/rolldown'
-
-export default defineConfig({
- entry: ['src/index.ts'],
- plugins: [
- transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }),
- ],
-})
-```
-
-The plugin emits every file under `srcDir` under `outBase` in the build's output directory. It keeps each file's name, apart from the extension:
-
-- Scripts become `.js`, or `.mjs` with `extension: 'mjs'`.
-- `.tsx` and `.jsx` files become `.jsx`, with their JSX kept.
-- Sass files compile to `.css`.
-- Test and story files are left out by default.
-
-Scripts are transpiled with oxc, and keep their imports as written. Relative imports are the exception: they get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build Output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program per tsconfig project: the nearest `tsconfig.json`, or the project in its `references` that includes the file.
-
-By default, the plugin transpiles scripts with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. `builder()` passes the `transform` of the `rolldown` that `tsdown` installs, so a module that builds with `builder()` needs neither.
-
-## Options
-
-| Option | Default | Description |
-|---|---|---|
-| `srcDir` | | The directory whose files are transpiled one by one. |
-| `outBase` | the output directory | Where the outputs go, relative to the build's output directory. |
-| `cwd` | the build's `cwd` | The project root: where `srcDir` is resolved, the tsconfig search starts, and `node_modules` is read. |
-| `include` | every file | Globs of files to include, relative to `srcDir`. |
-| `exclude` | test and story files | Globs of files to exclude. |
-| `extension` | `'js'` | The extension of emitted scripts: `'js'` or `'mjs'`. Declarations follow, as `.d.ts` or `.d.mts`. |
-| `tsconfig` | the nearest above `cwd` | The tsconfig to compile with, or `false` for none. |
-| `paths` | | `paths` added to the tsconfig's when generating declarations. |
-| `jsx` | `'preserve'` | JSX compilation for `.tsx` and `.jsx` files, or a function of the source path that returns it. `'preserve'` emits them as `.jsx` with types stripped, next to a `.d.ts`. |
-| `transform` | the one of the installed `rolldown` | The oxc `transform` to use. |
-| `sourcemap` | `false` | Emit source maps next to scripts. |
-| `declaration` | `true` | Generate declarations. |
-| `stylesheets` | `true` | Process `.css` with lightningcss and compile Sass. `false` copies stylesheets as they are. |
-| `vue` | enabled | Options for `.vue` files, or `false` to leave them out. |
-| `resolveExternal` | | Decides what happens to relative imports that resolve outside `srcDir`. |
-
-The options are documented in full on the `TranspileDirOptions` type.
-
-## Imports outside `srcDir`
-
-By default, the plugin keeps a relative import that resolves outside `srcDir` as written. To change that, pass `resolveExternal`, which the plugin calls for each such import. Its third argument describes the import:
-
-- `file`: the absolute path of the imported file.
-- `kind`: `'value'`, or `'type'` for an import that's only used for its type.
-- `from` and `output`: the paths where the importer and the imported file would be emitted.
-
-`resolveExternal` returns one of these values:
-
-- A string: the specifier to write instead.
-- `{ mirror: 'value' }` or `{ mirror: 'type' }`: emit the file alongside the directory, as a script and a declaration, or as a declaration only. An `output` path, relative to the output directory, overrides where the file goes.
-- `undefined`: keep the specifier as written.
-
-This config emits every imported file outside `srcDir` next to the directory:
-
-```ts [tsdown.config.ts]
-import { defineConfig } from 'tsdown'
-import { transpileDir } from '@nuxt/module-builder/rolldown'
-
-export default defineConfig({
- entry: ['src/index.ts'],
- plugins: [
- transpileDir({
- srcDir: 'src/runtime',
- outBase: 'runtime',
- resolveExternal: (_specifier, _importer, { kind }) => ({ mirror: kind }),
- }),
- ],
-})
-```
-
-## A build with nothing to bundle
-
-A build that only transpiles directories can pass `emptyEntry`, from the same export, as its `entry`. `transpileDir` removes its chunk from the output:
-
-```ts [tsdown.config.ts]
-import { defineConfig } from 'tsdown'
-import { emptyEntry, transpileDir } from '@nuxt/module-builder/rolldown'
-
-export default defineConfig({
- entry: emptyEntry,
- plugins: [
- transpileDir({ srcDir: 'src' }),
- ],
-})
-```
-
-## Type errors
-
-Errors that would leave a declaration missing or wrong fail the build. The plugin reports other type errors as one warning per directory. The warning's `pluginCode` equals the `TYPE_ERRORS_WARNING` constant from `@nuxt/module-builder/rolldown`. An `onLog` handler can then filter the warning, or turn it into an error:
-
-```ts [tsdown.config.ts]
-import { defineConfig } from 'tsdown'
-import { transpileDir, TYPE_ERRORS_WARNING } from '@nuxt/module-builder/rolldown'
-
-export default defineConfig({
- entry: ['src/index.ts'],
- inputOptions: {
- onLog(level, log, handler) {
- handler(log.pluginCode === TYPE_ERRORS_WARNING ? 'error' : level, log)
- },
- },
- plugins: [
- transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }),
- ],
-})
-```
diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md
index 886f07a0..5481dcac 100644
--- a/docs/cli/build-module/index.md
+++ b/docs/cli/build-module/index.md
@@ -13,7 +13,7 @@ npx nuxt build-module build [ROOTDIR] [--cwd=] [--outDir=]
npx nuxt build-module prepare [ROOTDIR] [--cwd=]
```
-The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/module-builder`](/docs/guide/modules/module-builder) installs in your module. It's the same CLI as `nuxt-module-build`, with two subcommands. Without a subcommand, it runs `build` and prints a warning.
+The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/module-builder`](/docs/guide/modules/module-builder) installs in your module. It's the same CLI as `nuxt-module-build`, with two subcommands. Without a subcommand, it prints its usage.
## `build`
diff --git a/docs/index.md b/docs/index.md
index 169cced6..3c06335e 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -13,7 +13,7 @@ navigation:
To build a module, you need:
-- Node `^22.18.0 || >=24.0.0`.
+- Node `^22.18.0 || ^24.11.0 || >=26.0.0`.
- `tsdown` and `typescript` (`^5.9.3 || ^6.0.0`), which are peer dependencies of `@nuxt/module-builder`.
- `nuxt`, which provides the `@nuxt/cli` that `nuxt-module-build prepare` runs.
@@ -104,5 +104,4 @@ The `dev:prepare` script in step 3 is for a module that you publish with pnpm or
- [TypeScript](/docs/guide/modules/module-builder/typescript): your module's `tsconfig.json`, its declarations, and the rules for module code.
- [Build Output](/docs/guide/modules/module-builder/output): the files in `dist`, and the size report.
- [Exports](/docs/guide/modules/module-builder/exports): subpath exports, including runtime components.
-- [Transpiling a Directory](/docs/guide/modules/module-builder/transpile-dir): the `transpileDir` rolldown plugin.
- [Upgrading to v2](/docs/guide/modules/module-builder/upgrade-v2): moving a module from v1.
diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md
index 1ae9d6d1..80331ee9 100644
--- a/docs/upgrade-v2.md
+++ b/docs/upgrade-v2.md
@@ -9,7 +9,7 @@ Most modules upgrade by running the build and following its output. Every messag
## Node engines
-v2 requires Node `^22.18.0 || >=24.0.0`. Use Node 22.18+ or 24+ locally and in CI:
+v2 requires Node `^22.18.0 || ^24.11.0 || >=26.0.0`. Use Node 22.18+, 24.11+, or 26+ locally and in CI:
```yaml
# .github/workflows/ci.yml
@@ -369,6 +369,10 @@ TypeScript resolves `typesVersions` entries with `node10` rules. A path without
Any other path in `exports`, `main`, `module`, `types`, or `typesVersions` that doesn't exist after the build is listed in a warning. Either add the entry that produces it (see [Build configuration](#build-configuration)), or remove the path.
+## Commands
+
+`nuxt-module-build` and `nuxt build-module` need a subcommand. Without one they print their usage, so a script such as `"prepack": "nuxt-module-build"` becomes `"prepack": "tsdown"`, or `nuxt-module-build build`.
+
## Stub builds
`nuxt-module-build build --stub` and `nuxt-module-build prepare --stub` have been removed, and fail with a link to this section. Replace the scripts that use them as described in [Developing a module](#developing-a-module):
@@ -611,7 +615,7 @@ Each file under `src/runtime` is still emitted under `dist/runtime` with its nam
## Output directory
-A one-off build empties `--outDir` (`dist` by default) before it writes to it. `tsdown --watch` removes the files in it that the build doesn't emit any more. The directory must therefore be inside your module. An `--outDir` of `.`, or of a directory that contains the module, fails the build.
+A one-off build empties `--outDir` (`dist` by default) before it writes to it. `tsdown --watch` removes the files in it that the build doesn't emit any more. The directory must therefore be inside your module. An `--outDir` outside the module, such as `../dist`, or the module root itself, fails the build.
## Module tsconfig
@@ -872,7 +876,7 @@ pnpm remove unbuild
Follow these steps in order to upgrade a module. Each step is mechanical until the build runs. Where a step says `pnpm`, use your module's own package manager.
-1. Use Node 22.18+ or 24+ locally and in CI.
+1. Use Node 22.18+, 24.11+, or 26+ locally and in CI.
2. Install v2 and tsdown, before step 3:
- Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`.
- Run `pnpm remove unbuild`. Also remove `mkdist` and `jiti`, if they only served the builder.
diff --git a/package.json b/package.json
index 4f68736f..a51822d5 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,6 @@
"type": "module",
"exports": {
".": "./dist/index.mjs",
- "./rolldown": "./dist/rolldown.mjs",
"./tsdown": "./dist/tsdown.mjs",
"./package.json": "./package.json"
},
@@ -16,9 +15,6 @@
"*": [
"./dist/*.d.mts"
],
- "rolldown": [
- "./dist/rolldown.d.mts"
- ],
"tsdown": [
"./dist/tsdown.d.mts"
],
@@ -43,7 +39,7 @@
"prepack": "pnpm build",
"test": "pnpm vitest",
"test:pack": "pnpm -C example pack --out ../.temp-pack/example.tgz && attw .temp-pack/example.tgz && publint .temp-pack/example.tgz",
- "test:engines": "pnpm exec installed-check -d -i tsdown --no-workspaces --ignore @nuxt/cli",
+ "test:engines": "pnpm exec installed-check -d --no-workspaces --ignore @nuxt/cli",
"test:knip": "knip --exclude unresolved",
"test:types": "vue-tsc --noEmit && pnpm -r test:types"
},
@@ -73,15 +69,9 @@
},
"peerDependencies": {
"@nuxt/cli": "^3.37.0 || ^4.0.0",
- "rolldown": "^1.2.6",
"tsdown": "^0.23.7",
"typescript": "^5.9.3 || ^6.0.0"
},
- "peerDependenciesMeta": {
- "rolldown": {
- "optional": true
- }
- },
"devDependencies": {
"@arethetypeswrong/cli": "^0.18.5",
"@arethetypeswrong/core": "^0.18.5",
@@ -97,7 +87,6 @@
"ofetch": "^1.5.1",
"pkg-pr-new": "^0.0.93",
"publint": "^0.3.25",
- "rolldown": "^1.3.0",
"sass": "^1.108.1",
"tinyexec": "^1.3.1",
"tsdown": "^0.23.7",
@@ -108,6 +97,6 @@
"vue-tsc": "^3.3.14"
},
"engines": {
- "node": "^22.18.0 || >=24.0.0"
+ "node": "^22.18.0 || ^24.11.0 || >=26.0.0"
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1fbf2145..6290a30a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -204,7 +204,7 @@ importers:
version: 0.2.17
vue-sfc-transformer:
specifier: ^0.3.3
- version: 0.3.3(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.3.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
+ version: 0.3.3(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.18)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
devDependencies:
'@arethetypeswrong/cli':
specifier: ^0.18.5
@@ -214,7 +214,7 @@ importers:
version: 0.18.5
'@nuxt/cli':
specifier: ^4.0.3
- version: 4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.3.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))
+ version: 4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.2.18)(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))
'@nuxt/eslint-config':
specifier: ^1.17.0
version: 1.17.0(@typescript-eslint/utils@8.72.2(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(@vue/compiler-sfc@3.5.45)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
@@ -241,7 +241,7 @@ importers:
version: runtime:26.13.0
nuxt:
specifier: ~4.6.4
- version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
ofetch:
specifier: ^1.5.1
version: 1.5.1
@@ -251,9 +251,6 @@ importers:
publint:
specifier: ^0.3.25
version: 0.3.25
- rolldown:
- specifier: ^1.3.0
- version: 1.3.1
sass:
specifier: ^1.108.1
version: 1.108.1
@@ -283,14 +280,14 @@ importers:
dependencies:
'@nuxt/kit':
specifier: ~4.6.4
- version: 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ version: 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
devDependencies:
'@nuxt/module-builder':
specifier: workspace:*
version: link:..
nuxt:
specifier: ~4.6.4
- version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
example/playground:
dependencies:
@@ -299,7 +296,7 @@ importers:
version: link:..
nuxt:
specifier: ~4.6.4
- version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ version: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
devDependencies:
typescript:
specifier: ~6.0.3
@@ -5512,17 +5509,17 @@ snapshots:
'@csstools/css-tokenizer@4.0.2': {}
- '@dxup/nuxt@0.5.11(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))':
+ '@dxup/nuxt@0.5.11(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.156.0)(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))':
dependencies:
'@dxup/unimport': 0.1.2
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
'@vue/compiler-dom': 3.5.45
chokidar: 6.0.0
knitwork: 1.3.0
magic-string: 1.4.5
pathe: 2.0.3
tinyglobby: 0.2.17
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
transitivePeerDependencies:
- '@farmfe/core'
- '@nuxt/schema'
@@ -5848,7 +5845,7 @@ snapshots:
dependencies:
which: 7.0.0
- '@nuxt/cli@4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.3.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))':
+ '@nuxt/cli@4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.2.18)(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:
'@clack/prompts': 1.9.0
args-tokenizer: 0.3.0
@@ -5877,15 +5874,15 @@ snapshots:
'@nuxt/schema': 4.6.4
jiti: 2.7.0
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
transitivePeerDependencies:
- vite
'@nuxt/devalue@2.0.2': {}
- '@nuxt/devtools-kit@3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))':
+ '@nuxt/devtools-kit@3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
execa: 8.0.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)
transitivePeerDependencies:
@@ -5911,11 +5908,11 @@ snapshots:
pkg-types: 2.4.0
semver: 7.8.6
- '@nuxt/devtools@3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))':
+ '@nuxt/devtools@3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))(vue@3.5.45(typescript@6.0.3))':
dependencies:
- '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))
'@nuxt/devtools-wizard': 3.4.4
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
'@vue/devtools-core': 8.2.1(vue@3.5.45(typescript@6.0.3))
'@vue/devtools-kit': 8.2.1
birpc: 4.2.0
@@ -5943,7 +5940,7 @@ snapshots:
tinyglobby: 0.2.17
unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.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-plugin-inspect: 11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ vite-plugin-inspect: 11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))
vite-plugin-vue-tracer: 1.7.0(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))(vue@3.5.45(typescript@6.0.3))
which: 6.0.1
ws: 8.22.2
@@ -6021,7 +6018,7 @@ snapshots:
- supports-color
- typescript
- '@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))':
+ '@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))':
dependencies:
consola: 3.4.2
defu: 6.1.7
@@ -6039,7 +6036,7 @@ snapshots:
std-env: 4.3.0
tinyexec: 1.3.1
tinyglobby: 0.2.17
- unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
verkit: 0.5.0
optionalDependencies:
'@nuxt/schema': 4.6.4
@@ -6049,15 +6046,15 @@ snapshots:
jiti: 2.7.0
mlly: 1.8.2
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
transitivePeerDependencies:
- magic-string
- unplugin
- '@nuxt/nitro-server@4.6.4(dd29e45c37758652c02fbdec81b76b42)':
+ '@nuxt/nitro-server@4.6.4(2973bf082bb4be1a8b27e354c9d175fc)':
dependencies:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
- '@unhead/vue': 3.4.3(@oxc-project/types@0.157.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
+ '@unhead/vue': 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)(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))(vue@3.5.45(typescript@6.0.3))
consola: 3.4.2
defu: 6.1.7
destr: 2.0.5
@@ -6067,20 +6064,20 @@ snapshots:
exsolve: 1.2.0
flru: 1.0.2
h3: 1.15.11
- impound: 1.2.1(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ impound: 1.2.1(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))
klona: 2.0.6
mocked-exports: 0.1.1
my-bad: 0.2.12(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))
- nitropack: 2.13.6(@parcel/watcher@2.6.0)(bare-buffer@3.7.1)(oxc-parser@0.156.0)(rolldown@1.3.1)(srvx@1.0.8)(supports-color@10.2.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))
+ nitropack: 2.13.6(@parcel/watcher@2.6.0)(bare-buffer@3.7.1)(oxc-parser@0.156.0)(rolldown@1.2.18)(srvx@1.0.8)(supports-color@10.2.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))
nostics: 1.3.0
- nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
ohash: 2.0.12
pathe: 2.0.3
radix3: 1.1.2
rou3: 0.9.2
std-env: 4.3.0
ufo: 1.6.4
- unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
unrouting: 0.3.2
unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))
vue: 3.5.45(typescript@6.0.3)
@@ -6156,17 +6153,17 @@ snapshots:
pkg-types: 2.4.0
std-env: 4.3.0
- '@nuxt/telemetry@2.9.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))))':
+ '@nuxt/telemetry@2.9.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))))':
dependencies:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
citty: 0.2.2
consola: 3.4.2
rc9: 3.1.0
std-env: 4.3.0
- '@nuxt/vite-builder@4.6.4(37c1076febb9c866901dbb15fc99e197)':
+ '@nuxt/vite-builder@4.6.4(0b4c6350f95b92c0d085180976953fa8)':
dependencies:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
'@vitejs/plugin-vue': 6.0.10(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))(vue@3.5.45(typescript@6.0.3))
'@vitejs/plugin-vue-jsx': 5.1.6(supports-color@10.2.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))(vue@3.5.45(typescript@6.0.3))
autoprefixer: 10.6.2(postcss@8.5.32)
@@ -6182,16 +6179,16 @@ snapshots:
knitwork: 1.3.0
mocked-exports: 0.1.1
my-bad: 0.2.12(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))
- nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
pathe: 2.0.3
pkg-types: 2.4.0
postcss: 8.5.32
- rolldown-string: 0.3.1(rolldown@1.3.1)
+ rolldown-string: 0.3.1(rolldown@1.2.18)
seroval: 1.8.0
std-env: 4.3.0
ufo: 1.6.4
unenv: 2.0.0-rc.24
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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)
vite-node: 6.0.0(@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-plugin-checker: 0.14.5(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(optionator@0.9.4)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))
@@ -6199,8 +6196,8 @@ snapshots:
vue-bundle-renderer: 2.5.0
optionalDependencies:
'@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.13(supports-color@10.2.2))
- rolldown: 1.3.1
- rollup-plugin-visualizer: 7.1.3(rolldown@1.3.1)(rollup@4.68.2)
+ rolldown: 1.2.18
+ rollup-plugin-visualizer: 7.1.3(rolldown@1.2.18)(rollup@4.68.2)
transitivePeerDependencies:
- '@biomejs/biome'
- '@farmfe/core'
@@ -6238,15 +6235,15 @@ snapshots:
- webpack
- yaml
- '@nuxt/vite-server@4.6.4(c6b45f5858202a6416ce08d1a2fadda6)':
+ '@nuxt/vite-server@4.6.4(a7a66b9558e7685b9c6c11ed864ba5dd)':
dependencies:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
clickable-path: 0.1.1
defu: 6.1.7
exsolve: 1.2.0
mocked-exports: 0.1.1
my-bad: 0.2.12(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))
- nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
+ nuxt: 4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1)
pathe: 2.0.3
rou3: 0.9.2
srvx: 1.0.5
@@ -6863,17 +6860,17 @@ snapshots:
'@typescript-eslint/types': 8.72.2
eslint-visitor-keys: 5.0.1
- '@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.3.1)(rollup@4.68.2)(unhead@3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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))':
+ '@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
- oxc-walker: 1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.3.1)
- unhead: 3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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))
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ oxc-walker: 1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.2.18)
+ 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))
+ unplugin: 3.7.0(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))
optionalDependencies:
esbuild: 0.28.2
lightningcss: 1.33.0
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
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)
transitivePeerDependencies:
- '@farmfe/core'
@@ -6884,12 +6881,12 @@ snapshots:
- rollup
- unloader
- '@unhead/vue@3.4.3(@oxc-project/types@0.157.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))':
+ '@unhead/vue@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)(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))(vue@3.5.45(typescript@6.0.3))':
dependencies:
- '@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.3.1)(rollup@4.68.2)(unhead@3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ '@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))
hookable: 6.1.2
- unhead: 3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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))
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ 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))
+ unplugin: 3.7.0(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))
vue: 3.5.45(typescript@6.0.3)
optionalDependencies:
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)
@@ -8165,12 +8162,12 @@ snapshots:
import-without-cache@0.4.1: {}
- impound@1.2.1(esbuild@0.28.2)(rolldown@1.3.1)(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)):
+ impound@1.2.1(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)):
dependencies:
'@jridgewell/trace-mapping': 0.3.31
es-module-lexer: 3.0.4
pathe: 2.0.3
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
unplugin-utils: 0.3.2
transitivePeerDependencies:
- '@farmfe/core'
@@ -8566,7 +8563,7 @@ snapshots:
natural-compare@1.4.0: {}
- nitropack@2.13.6(@parcel/watcher@2.6.0)(bare-buffer@3.7.1)(oxc-parser@0.156.0)(rolldown@1.3.1)(srvx@1.0.8)(supports-color@10.2.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)):
+ nitropack@2.13.6(@parcel/watcher@2.6.0)(bare-buffer@3.7.1)(oxc-parser@0.156.0)(rolldown@1.2.18)(srvx@1.0.8)(supports-color@10.2.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)):
dependencies:
'@cloudflare/kv-asset-handler': 0.4.2
'@rollup/plugin-alias': 6.0.1(rollup@4.68.2)
@@ -8619,7 +8616,7 @@ snapshots:
pretty-bytes: 7.2.0
radix3: 1.1.2
rollup: 4.68.2
- rollup-plugin-visualizer: 7.1.3(rolldown@1.3.1)(rollup@4.68.2)
+ rollup-plugin-visualizer: 7.1.3(rolldown@1.2.18)(rollup@4.68.2)
scule: 1.3.0
semver: 7.8.6
serve-placeholder: 2.0.2
@@ -8631,7 +8628,7 @@ snapshots:
uncrypto: 0.1.3
unctx: 2.5.0
unenv: 2.0.0-rc.24
- unimport: 6.5.0(esbuild@0.28.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))
+ unimport: 6.5.0(esbuild@0.28.2)(oxc-parser@0.156.0)(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))
unplugin-utils: 0.3.2
unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))
untyped: 2.0.0
@@ -8752,20 +8749,20 @@ snapshots:
dependencies:
boolbase: 1.0.0
- nuxt@4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.3.1)(rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1):
+ nuxt@4.6.4(@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@10.2.2)))(@oxc-project/types@0.157.0)(@parcel/watcher@2.6.0)(@types/node@26.6.6)(@vue/compiler-sfc@3.5.45)(acorn@8.19.0)(bare-buffer@3.7.1)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(lightningcss@1.33.0)(mlly@1.8.2)(optionator@0.9.4)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2))(rollup@4.68.2)(sass@1.108.1)(srvx@1.0.8)(supports-color@10.2.2)(terser@5.51.2)(typescript@6.0.3)(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))(vue-tsc@3.3.14(typescript@6.0.3))(yaml@2.9.1):
dependencies:
- '@dxup/nuxt': 0.5.11(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))
+ '@dxup/nuxt': 0.5.11(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.156.0)(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))
'@jridgewell/trace-mapping': 0.3.31
- '@nuxt/cli': 4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.3.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))
+ '@nuxt/cli': 4.0.3(@nuxt/schema@4.6.4)(jiti@2.7.0)(oxc-parser@0.156.0)(rolldown@1.2.18)(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))
'@nuxt/devalue': 2.0.2
- '@nuxt/devtools': 3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
- '@nuxt/nitro-server': 4.6.4(dd29e45c37758652c02fbdec81b76b42)
+ '@nuxt/devtools': 3.4.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))(vue@3.5.45(typescript@6.0.3))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
+ '@nuxt/nitro-server': 4.6.4(2973bf082bb4be1a8b27e354c9d175fc)
'@nuxt/schema': 4.6.4
- '@nuxt/telemetry': 2.9.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))))
- '@nuxt/vite-builder': 4.6.4(37c1076febb9c866901dbb15fc99e197)
- '@nuxt/vite-server': 4.6.4(c6b45f5858202a6416ce08d1a2fadda6)
- '@unhead/vue': 3.4.3(@oxc-project/types@0.157.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))
+ '@nuxt/telemetry': 2.9.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))))
+ '@nuxt/vite-builder': 4.6.4(0b4c6350f95b92c0d085180976953fa8)
+ '@nuxt/vite-server': 4.6.4(a7a66b9558e7685b9c6c11ed864ba5dd)
+ '@unhead/vue': 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)(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))(vue@3.5.45(typescript@6.0.3))
'@vue/shared': 3.5.45
chokidar: 5.0.0
clickable-path: 0.1.1
@@ -8782,7 +8779,7 @@ snapshots:
fnv1a-64: 0.1.2
hookable: 6.1.2
ignore: 7.0.14
- impound: 1.2.1(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ impound: 1.2.1(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))
iron-webcrypto: 2.0.0
jiti: 2.7.0
klona: 2.0.6
@@ -8795,13 +8792,13 @@ snapshots:
ofetch: 1.5.1
ohash: 2.0.12
on-change: 6.0.2
- oxc-walker: 1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.3.1)
+ oxc-walker: 1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.2.18)
pathe: 2.0.3
perfect-debounce: 2.1.0
picomatch: 4.0.7
pkg-types: 2.4.0
- rolldown: 1.3.1
- rolldown-string: 0.3.1(rolldown@1.3.1)
+ rolldown: 1.2.18
+ rolldown-string: 0.3.1(rolldown@1.2.18)
rou3: 0.9.2
scule: 1.3.0
std-env: 4.3.0
@@ -8809,18 +8806,18 @@ snapshots:
ufo: 1.6.4
ultrahtml: 1.7.0
uncrypto: 0.1.3
- unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ unctx: 3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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)))
undici: 8.12.4
- unhead: 3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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))
- unimport: 7.0.2(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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))
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ 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))
+ unimport: 7.0.2(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.156.0)(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))
+ unplugin: 3.7.0(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))
unrouting: 0.3.2
untyped: 2.0.0
verkit: 0.5.0
vue: 3.5.45(typescript@6.0.3)
vue-bundle-renderer: 2.5.0
vue-component-type-helpers: 3.3.14
- vue-router: 5.4.0(@vue/compiler-sfc@3.5.45)(esbuild@0.28.2)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3))
+ vue-router: 5.4.0(@vue/compiler-sfc@3.5.45)(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))(vue@3.5.45(typescript@6.0.3))
optionalDependencies:
'@parcel/watcher': 2.6.0
'@types/node': 26.6.6
@@ -8998,11 +8995,11 @@ snapshots:
'@oxc-resolver/binding-win32-arm64-msvc': 11.24.2
'@oxc-resolver/binding-win32-x64-msvc': 11.24.2
- oxc-walker@1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.3.1):
+ oxc-walker@1.1.1(@oxc-project/types@0.157.0)(oxc-parser@0.156.0)(rolldown@1.2.18):
optionalDependencies:
'@oxc-project/types': 0.157.0
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
p-event@6.0.1:
dependencies:
@@ -9252,11 +9249,11 @@ snapshots:
- '@yuku-toolchain/wasm'
- oxc-resolver
- rolldown-string@0.3.1(rolldown@1.3.1):
+ rolldown-string@0.3.1(rolldown@1.2.18):
dependencies:
magic-string: 1.4.5
optionalDependencies:
- rolldown: 1.3.1
+ rolldown: 1.2.18
rolldown@1.2.18:
dependencies:
@@ -9301,14 +9298,14 @@ snapshots:
'@rolldown/binding-win32-arm64-msvc': 1.3.1
'@rolldown/binding-win32-x64-msvc': 1.3.1
- rollup-plugin-visualizer@7.1.3(rolldown@1.3.1)(rollup@4.68.2):
+ rollup-plugin-visualizer@7.1.3(rolldown@1.2.18)(rollup@4.68.2):
dependencies:
open: 11.0.4
picomatch: 4.0.7
source-map: 0.8.0
yargs: 18.2.0
optionalDependencies:
- rolldown: 1.3.1
+ rolldown: 1.2.18
rollup: 4.68.2
rollup@4.68.2:
@@ -9724,12 +9721,12 @@ snapshots:
magic-string: 0.30.21
unplugin: 2.3.11
- unctx@3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))):
+ unctx@3.0.1(magic-string@1.4.5)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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))):
optionalDependencies:
magic-string: 1.4.5
oxc-parser: 0.156.0
- rolldown: 1.3.1
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ rolldown: 1.2.18
+ unplugin: 3.7.0(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))
undici-types@8.9.0: {}
@@ -9739,10 +9736,10 @@ snapshots:
dependencies:
pathe: 2.0.3
- unhead@3.4.3(esbuild@0.28.2)(rolldown@1.3.1)(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)):
+ 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)):
dependencies:
hookable: 6.1.2
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
optionalDependencies:
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)
transitivePeerDependencies:
@@ -9762,7 +9759,7 @@ snapshots:
unicorn-magic@0.4.1: {}
- unimport@6.5.0(esbuild@0.28.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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)):
+ unimport@6.5.0(esbuild@0.28.2)(oxc-parser@0.156.0)(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)):
dependencies:
acorn: 8.19.0
escape-string-regexp: 5.0.0
@@ -9776,11 +9773,11 @@ snapshots:
scule: 1.3.0
strip-literal: 4.0.0
tinyglobby: 0.2.17
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
unplugin-utils: 0.3.2
optionalDependencies:
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
transitivePeerDependencies:
- '@farmfe/core'
- '@rsbuild/core'
@@ -9792,7 +9789,7 @@ snapshots:
- vite
- webpack
- unimport@7.0.2(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(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)):
+ unimport@7.0.2(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.156.0)(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)):
dependencies:
escape-string-regexp: 5.0.0
estree-walker: 3.0.3
@@ -9805,12 +9802,12 @@ snapshots:
scule: 1.3.0
strip-literal: 4.0.0
tinyglobby: 0.2.17
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
unplugin-utils: 0.3.2
optionalDependencies:
acorn: 8.19.0
oxc-parser: 0.156.0
- rolldown: 1.3.1
+ rolldown: 1.2.18
transitivePeerDependencies:
- '@farmfe/core'
- '@rsbuild/core'
@@ -9834,7 +9831,7 @@ snapshots:
picomatch: 4.0.7
webpack-virtual-modules: 0.6.2
- unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)):
+ unplugin@3.7.0(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)):
dependencies:
'@jridgewell/remapping': 2.3.5
'@rolldown/pluginutils': 1.1.0
@@ -9842,7 +9839,7 @@ snapshots:
webpack-virtual-modules: 0.6.2
optionalDependencies:
esbuild: 0.28.2
- rolldown: 1.3.1
+ 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)
@@ -9984,7 +9981,7 @@ snapshots:
typescript: 6.0.3
vue-tsc: 3.3.14(typescript@6.0.3)
- vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)):
+ vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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:
ansis: 4.5.0
error-stack-parser-es: 1.0.5
@@ -9997,7 +9994,7 @@ snapshots:
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-dev-rpc: 2.0.0(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))
optionalDependencies:
- '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.3.1)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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)))
+ '@nuxt/kit': 4.6.4(@nuxt/schema@4.6.4)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.156.0)(rolldown@1.2.18)(unplugin@3.7.0(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-plugin-vue-tracer@1.7.0(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))(vue@3.5.45(typescript@6.0.3)):
dependencies:
@@ -10080,7 +10077,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- vue-router@5.4.0(@vue/compiler-sfc@3.5.45)(esbuild@0.28.2)(rolldown@1.3.1)(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))(vue@3.5.45(typescript@6.0.3)):
+ vue-router@5.4.0(@vue/compiler-sfc@3.5.45)(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))(vue@3.5.45(typescript@6.0.3)):
dependencies:
'@vue-macros/common': 3.1.4(vue@3.5.45(typescript@6.0.3))
'@vue/devtools-api': 8.2.1
@@ -10096,7 +10093,7 @@ snapshots:
picomatch: 4.0.7
scule: 1.3.0
tinyglobby: 0.2.17
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.1)(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))
+ unplugin: 3.7.0(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))
unplugin-utils: 0.3.2
vue: 3.5.45(typescript@6.0.3)
optionalDependencies:
@@ -10113,7 +10110,7 @@ snapshots:
- unloader
- webpack
- vue-sfc-transformer@0.3.3(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.3.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)):
+ vue-sfc-transformer@0.3.3(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.18)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)):
dependencies:
'@vue/compiler-core': 3.5.45
tinyglobby: 0.2.17
@@ -10122,7 +10119,7 @@ snapshots:
'@volar/typescript': 2.4.30(typescript@6.0.3)
'@vue/language-core': 3.3.14
esbuild: 0.28.2
- rolldown: 1.3.1
+ rolldown: 1.2.18
typescript: 6.0.3
vue-tsc@3.3.14(typescript@6.0.3):
diff --git a/src/build/advice.ts b/src/build/advice.ts
deleted file mode 100644
index 043a2607..00000000
--- a/src/build/advice.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-const shown = new Set()
-
-/** Advice is shown at most once per process, and never in CI. */
-export function shouldAdvise(key: string): boolean {
- if (process.env.CI || shown.has(key)) {
- return false
- }
- shown.add(key)
- return true
-}
diff --git a/src/build/aliases.ts b/src/build/aliases.ts
index e45e6a75..4a0d6ca6 100644
--- a/src/build/aliases.ts
+++ b/src/build/aliases.ts
@@ -1,6 +1,9 @@
import { existsSync, promises as fsp } from 'node:fs'
import { dirname, join, resolve } from 'pathe'
+import { DECLARATION_RE } from '../utils.ts'
+
+const APP_ALIAS_RE = /(\bfrom\s*|\bimport\s*\(\s*)(['"])#app(?:\/[^'"]*)?\2/g
const RELATIVE_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.\.?\/[^'"]*)\2/g
const DECLARATION_TARGETS = [
['.d.ts', '.js'],
@@ -15,20 +18,16 @@ const DECLARATION_TARGETS = [
*
* - Relative specifiers without an extension get the one of the file they resolve to in
* `outDir`, so they resolve under `node16` and `nodenext` module resolution.
- * - `#app` aliases, which tsc prints whenever the real path is not reachable through
- * `node_modules` and which only resolve inside a Nuxt app, become `nuxt/app`.
+ * - `#app` aliases become `nuxt/app`, see {@link rewriteAppAliases}.
*/
export async function rewriteRuntimeDeclarations(outDir: string, outputs: string[]): Promise {
const files = outputs.flatMap(output => declarationsOf(join(outDir, output))).filter(file => existsSync(file))
await Promise.all(files.map(async (file) => {
const contents = await fsp.readFile(file, 'utf8')
- const rewritten = contents
- .replace(RELATIVE_SPECIFIER_RE, (match, prefix: string, quote: string, specifier: string) => {
- const resolved = resolveDeclarationSpecifier(dirname(file), specifier) ?? specifier
- return resolved === specifier ? match : `${prefix}${quote}${resolved}${quote}`
- })
- .replace(/import\("#app(?:\/[^"]*)?"\)/g, 'import("nuxt/app")')
- .replace(/(\bfrom\s*)(['"])#app(?:\/[^'"]*)?\2/g, '$1$2nuxt/app$2')
+ const rewritten = rewriteAppAliases(contents.replace(RELATIVE_SPECIFIER_RE, (match, prefix: string, quote: string, specifier: string) => {
+ const resolved = resolveDeclarationSpecifier(dirname(file), specifier) ?? specifier
+ return resolved === specifier ? match : `${prefix}${quote}${resolved}${quote}`
+ }))
if (rewritten !== contents) {
await fsp.writeFile(file, rewritten, 'utf8')
@@ -36,6 +35,14 @@ export async function rewriteRuntimeDeclarations(outDir: string, outputs: string
}))
}
+/**
+ * `code` with `#app` aliases, which tsc prints whenever the real path is not reachable through
+ * `node_modules` and which only resolve inside a Nuxt app, written as `nuxt/app`.
+ */
+export function rewriteAppAliases(code: string): string {
+ return code.replace(APP_ALIAS_RE, '$1$2nuxt/app$2')
+}
+
/**
* The paths, relative to `outDir`, whose presence decides how {@link rewriteRuntimeDeclarations}
* rewrites the relative specifiers in `code`, the declaration emitted as `fileName`.
@@ -49,7 +56,7 @@ export function declarationTargets(fileName: string, code: string): string[] {
}
function declarationsOf(output: string) {
- if (/\.d\.[cm]?ts$/.test(output)) {
+ if (DECLARATION_RE.test(output)) {
return [output]
}
if (output.endsWith('.vue')) {
diff --git a/src/build/build-config.ts b/src/build/build-config.ts
deleted file mode 100644
index 6824d2da..00000000
--- a/src/build/build-config.ts
+++ /dev/null
@@ -1,517 +0,0 @@
-import { existsSync } from 'node:fs'
-import { readFile } from 'node:fs/promises'
-import { isAbsolute, normalize, relative, resolve } from 'pathe'
-import { consola } from 'consola'
-import type { PackageJson } from 'pkg-types'
-
-import type { BuildContext, BuildHook } from './define.ts'
-import { guide } from './guide.ts'
-import type { GuideSection } from './guide.ts'
-import { findModuleCodeIssues, formatModuleCodeIssues, importModule, probe } from './loader.ts'
-
-const BUILD_CONFIG_FILES = ['build.config.ts', 'build.config.mts', 'build.config.js', 'build.config.mjs']
-
-const DEFINE_BUILD_CONFIG_STUB = [
- 'export const defineBuildConfig = config => config',
- 'export const definePreset = preset => preset',
-].join('\n')
-
-const ACCEPTED_KEYS = new Set(['entries', 'externals', 'replace', 'rollup', 'declaration', 'failOnWarn', 'name', 'parallel', 'clean', 'rootDir', 'outDir', 'sourcemap'])
-const ENTRY_KEYS = new Set(['input', 'name', 'builder', 'outDir', 'declaration'])
-const DIRECTORY_EXTENSIONS = ['mjs', 'js'] as const
-
-const SUPPORTED_HOOKS = ['build:before', 'rollup:done', 'build:done'] as const
-export type SupportedHook = typeof SUPPORTED_HOOKS[number]
-const REPLACE_OPTION_KEYS = new Set(['values', 'delimiters', 'preventAssignment', 'objectGuards', 'sourcemap', 'sourceMap'])
-
-export interface BuildConfigSource {
- /** Where the config came from, used in diagnostics. */
- name: string
- config: unknown
-}
-
-export interface DirectoryEntry {
- srcDir: string
- outDir: string
- /** Script extension; declarations use the matching `.d.mts` or `.d.ts`. */
- ext: typeof DIRECTORY_EXTENSIONS[number]
-}
-
-export interface ReplaceOptions {
- values: Record
- delimiters?: [string, string]
- preventAssignment?: boolean
- objectGuards?: boolean
-}
-
-export interface TranslatedBuildConfig {
- /** Bundled entries keyed by output name, as paths relative to the module root. */
- entries: Record
- /** Directories built file by file, in the same way as `src/runtime`. */
- directories: DirectoryEntry[]
- neverBundle: RegExp[]
- replace?: ReplaceOptions
- sourcemap: boolean
- declaration?: unknown
- hooks: Record
- /** Hooks that are skipped because there is nothing for them to act on, as `: `. */
- ignoredHooks: string[]
- /** Options without an equivalent, as `: `. */
- unsupported: string[]
-}
-
-export interface TranslateBuildConfigOptions {
- cwd: string
- outDir: string
-}
-
-/**
- * Translate unbuild configs into the equivalent build options. Sources are given in
- * unbuild's precedence order: `build.config.*` first, then `package.json`'s `unbuild` or
- * `build`.
- */
-export function translateBuildConfig(sources: BuildConfigSource[], options: TranslateBuildConfigOptions): TranslatedBuildConfig {
- const cwd = resolve(options.cwd)
- const outDir = resolve(options.outDir)
- const result: TranslatedBuildConfig = {
- entries: {},
- directories: [],
- neverBundle: [],
- sourcemap: false,
- hooks: { 'build:before': [], 'rollup:done': [], 'build:done': [] },
- ignoredHooks: [],
- unsupported: [],
- }
- const replace: ReplaceOptions = { values: {}, preventAssignment: true }
- let replaceDisabled = false
- const runtime = { srcDir: resolve(cwd, 'src/runtime'), outDir: resolve(outDir, 'runtime') }
-
- for (const { name: source, config } of sources) {
- const unsupported = (option: string) => result.unsupported.push(`${source}: ${option}`)
-
- if (!isPlainObject(config)) {
- unsupported('(not an object)')
- continue
- }
-
- for (const [key, value] of Object.entries(config)) {
- switch (key) {
- case 'entries':
- for (const [index, entry] of (Array.isArray(value) ? value : [value]).entries()) {
- translateEntry(entry, `entries[${index}]`)
- }
- break
- case 'externals':
- for (const [index, external] of (Array.isArray(value) ? value : [value]).entries()) {
- if (typeof external === 'string') {
- result.neverBundle.push(new RegExp(`^${escapeRegExp(external)}(?:/|$)`))
- }
- else if (external instanceof RegExp) {
- result.neverBundle.push(external)
- }
- else {
- unsupported(`externals[${index}]`)
- }
- }
- break
- case 'replace':
- addReplaceValues(value, 'replace')
- break
- case 'rollup':
- translateRollup(value)
- break
- case 'sourcemap':
- result.sourcemap ||= value === true
- break
- case 'declaration':
- result.declaration ??= value
- break
- case 'clean':
- if (value === false) {
- unsupported('clean: false')
- }
- break
- case 'rootDir':
- if (typeof value !== 'string' || resolve(cwd, value) !== cwd) {
- unsupported('rootDir')
- }
- break
- case 'outDir':
- if (typeof value !== 'string' || resolve(cwd, value) !== outDir) {
- unsupported('outDir')
- }
- break
- case 'hooks':
- if (!isPlainObject(value)) {
- unsupported('hooks')
- break
- }
- for (const [hook, fn] of Object.entries(value)) {
- if (typeof fn !== 'function') {
- unsupported(`hooks['${hook}']`)
- }
- else if ((SUPPORTED_HOOKS as readonly string[]).includes(hook)) {
- result.hooks[hook as SupportedHook].push(fn as BuildHook)
- }
- else if (hook.startsWith('mkdist:')) {
- result.ignoredHooks.push(`${source}: hooks['${hook}']`)
- }
- else {
- unsupported(`hooks['${hook}']`)
- }
- }
- break
- default:
- if (!ACCEPTED_KEYS.has(key)) {
- unsupported(key)
- }
- }
- }
-
- function translateEntry(entry: unknown, path: string) {
- const normalised = typeof entry === 'string' ? { input: entry } : entry
- if (!isPlainObject(normalised) || typeof normalised.input !== 'string' || !normalised.input) {
- unsupported(path)
- return
- }
-
- const input = normalised.input
- const builder = normalised.builder ?? (input.endsWith('/') ? 'mkdist' : 'rollup')
-
- for (const [key, option] of Object.entries(normalised)) {
- if (ENTRY_KEYS.has(key)) {
- continue
- }
- // Relative declaration specifiers always carry their extension.
- if (builder === 'mkdist' && (key === 'addRelativeDeclarationExtensions' || (key === 'ext' && DIRECTORY_EXTENSIONS.includes(option as DirectoryEntry['ext'])))) {
- continue
- }
- unsupported(`${path}.${key}`)
- }
-
- const entryOutDir = typeof normalised.outDir === 'string' ? resolve(cwd, normalised.outDir) : outDir
-
- if (builder === 'mkdist') {
- const directory: DirectoryEntry = { srcDir: resolve(cwd, input), outDir: entryOutDir, ext: normalised.ext === 'js' ? 'js' : 'mjs' }
- if (relative(outDir, directory.outDir).startsWith('..')) {
- unsupported(`${path}.outDir`)
- }
- else if (directory.srcDir !== runtime.srcDir || directory.outDir !== runtime.outDir) {
- result.directories.push(directory)
- }
- return
- }
-
- if (builder !== 'rollup') {
- unsupported(`${path}.builder: '${String(builder)}'`)
- return
- }
- if (entryOutDir !== outDir) {
- unsupported(`${path}.outDir`)
- return
- }
-
- const name = typeof normalised.name === 'string' ? normalised.name : entryName(input, cwd)
- const file = probe(resolve(cwd, input)) ?? resolve(cwd, `${input}.ts`)
- result.entries[name] = `./${relative(cwd, file)}`
- }
-
- function translateRollup(value: unknown) {
- if (!isPlainObject(value)) {
- unsupported('rollup')
- return
- }
- for (const [key, option] of Object.entries(value)) {
- if ((key === 'emitCJS' || key === 'cjsBridge') && !option) {
- continue
- }
- if (key === 'replace') {
- translateRollupReplace(option)
- continue
- }
- // `output.exports` only affects CommonJS output, which is never emitted.
- if (key === 'output' && isPlainObject(option) && Object.keys(option).every(name => name === 'exports')) {
- continue
- }
- unsupported(key === 'emitCJS' || key === 'cjsBridge' ? `rollup.${key}: true` : `rollup.${key}`)
- }
- }
-
- function translateRollupReplace(option: unknown) {
- if (option === false) {
- replaceDisabled = true
- return
- }
- if (!isPlainObject(option)) {
- unsupported('rollup.replace')
- return
- }
- for (const [key, value] of Object.entries(option)) {
- if (!REPLACE_OPTION_KEYS.has(key)) {
- unsupported(`rollup.replace.${key}`)
- }
- else if (key === 'values') {
- addReplaceValues(value, 'rollup.replace.values')
- }
- else if (key === 'delimiters') {
- if (Array.isArray(value) && value.length === 2 && value.every(d => typeof d === 'string')) {
- replace.delimiters ??= value as [string, string]
- }
- else {
- unsupported('rollup.replace.delimiters')
- }
- }
- else if (key === 'preventAssignment' || key === 'objectGuards') {
- replace[key] = value === true
- }
- }
- }
-
- function addReplaceValues(values: unknown, path: string) {
- if (!isPlainObject(values)) {
- unsupported(path)
- return
- }
- for (const [search, replacement] of Object.entries(values)) {
- if (typeof replacement !== 'string') {
- unsupported(`${path}['${search}']`)
- }
- else if (!Object.hasOwn(replace.values, search)) {
- replace.values[search] = replacement
- }
- }
- }
- }
-
- if (!replaceDisabled && Object.keys(replace.values).length) {
- result.replace = replace
- }
-
- return result
-}
-
-/** The output name unbuild infers for an entry without an explicit `name`. */
-export function entryName(input: string, cwd: string): string {
- let relativeInput = isAbsolute(input) ? relative(cwd, input) : normalize(input)
- if (relativeInput.startsWith('./')) {
- relativeInput = relativeInput.slice(2)
- }
- return relativeInput.replace(/^src\//, '').replace(/\.(?:js|mjs|cjs|ts|mts|cts|json|jsx|tsx)$/, '')
-}
-
-export interface LoadedBuildConfig extends TranslatedBuildConfig {
- /** The `build.config.*` file that was read, if any. */
- file?: string
- /** Whether that file still imports from `unbuild`. */
- importsUnbuild?: boolean
- /** The `package.json` field that was read, if any. */
- field?: 'unbuild' | 'build'
-}
-
-const UNBUILD_IMPORT_RE = /\bfrom\s*['"]unbuild['"]/
-
-/** Resolves `outDir` against `cwd`, refusing a directory the build would empty the module root with. */
-export function resolveOutDir(cwd: string, outDir: string, label: string = `--outDir ${outDir}`): string {
- const resolved = resolve(cwd, outDir)
- if (!relative(resolved, cwd).startsWith('..')) {
- throw new Error(`\`${label}\` resolves to \`${resolved}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`)
- }
- return resolved
-}
-
-/**
- * Read `build.config.*` and `package.json`'s `unbuild` (or, failing that, `build`) field
- * and translate them. Neither `unbuild` nor this package is loaded to evaluate the file:
- * `defineBuildConfig` is replaced with the identity.
- */
-export async function loadBuildConfig(cwd: string, pkg: PackageJson, outDir: string): Promise {
- const sources: BuildConfigSource[] = []
- let configCount = 0
-
- const field = pkg.unbuild !== undefined ? 'unbuild' : pkg.build !== undefined ? 'build' : undefined
- const fieldSource = field ? [{ name: `package.json "${field}"`, config: pkg[field] }] : []
-
- let importsUnbuild: boolean | undefined
- const file = BUILD_CONFIG_FILES.find(file => existsSync(resolve(cwd, file)))
- if (file) {
- importsUnbuild = UNBUILD_IMPORT_RE.test(await readFile(resolve(cwd, file), 'utf8'))
- const stubs = { 'unbuild': DEFINE_BUILD_CONFIG_STUB, '@nuxt/module-builder': DEFINE_BUILD_CONFIG_STUB }
- const unresolvable = findModuleCodeIssues(cwd, [file], [])
- if (unresolvable.length) {
- const withoutFile = translateBuildConfig(fieldSource, { cwd, outDir })
- const runtimeDirs = [resolve(cwd, 'src/runtime'), ...withoutFile.directories.map(directory => directory.srcDir)]
- const entries = bundledEntries(cwd, withoutFile)
- unresolvable.push(...findModuleCodeIssues(cwd, [entries.module], runtimeDirs, Object.values(entries)))
- throw new Error(formatModuleCodeIssues(unresolvable))
- }
- const { default: config } = await importModule(resolve(cwd, file), { cwd, stubs })
- if (typeof config === 'function') {
- throw new TypeError(`\`${file}\` must export a config object, not a function. Replace the function with the object it returns. ${guide('other-options')}`)
- }
- const configs = (Array.isArray(config) ? config : [config]).filter(Boolean)
- sources.push(...configs.map(config => ({ name: file, config })))
- configCount = configs.length
- }
-
- sources.push(...fieldSource)
-
- const translated = translateBuildConfig(sources, { cwd, outDir })
- translated.neverBundle.push(...inferredExternals(pkg))
- if (configCount > 1) {
- translated.unsupported.unshift(`${file}: an array of ${configCount} configs`)
- }
- return { file, importsUnbuild, field, ...translated }
-}
-
-/** An entry of `builder({ entries })`. */
-export type BuilderEntry
- = | string
- | { input: string, name?: string, builder?: 'rollup' }
- | { input: string, builder?: 'mkdist', outDir?: string, ext?: 'mjs' | 'js' }
-
-/** The key `builder()` keeps its options under, so `prepare` can find them in a tsdown config. */
-export const BUILDER_OPTIONS: unique symbol = Symbol.for('@nuxt/module-builder:builder-options')
-
-export interface BuilderOptions {
- /**
- * Entries built besides `src/module`. A path, or `{ input, name }`, is bundled. An `input`
- * ending in `/` (or `builder: 'mkdist'`) is a directory transpiled file by file like
- * `src/runtime`, into `outDir` (inside the build's output directory) with the `ext` scripts
- * get: `mjs` (the default) or `js`.
- */
- entries?: BuilderEntry[]
- /** Imports that are never bundled. A string matches the package and its subpaths. */
- externals?: Array
- /** Compile-time replacements in bundled entries, as `{ search: replacement }` or the options of rolldown's replace plugin. */
- replace?: Record | ReplaceOptions
-}
-
-const MODULE_OPTION_KEYS = new Set(['entries', 'externals', 'replace'])
-
-/** Resolves the options of `builder()` into bundled entries, transpiled directories and build settings. */
-export function resolveModuleOptions(cwd: string, pkg: PackageJson, outDir: string, options: BuilderOptions): LoadedBuildConfig {
- if ('hooks' in options) {
- throw new Error(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`)
- }
- const { entries, externals, replace } = options
- const config: Record = {
- ...entries !== undefined && { entries },
- ...externals !== undefined && { externals },
- ...replace !== undefined && (isPlainObject(replace) && isPlainObject(replace.values) ? { rollup: { replace } } : { replace }),
- }
- const translated = translateBuildConfig([{ name: 'builder()', config }], { cwd, outDir })
- translated.unsupported.push(...Object.keys(options).filter(key => !MODULE_OPTION_KEYS.has(key)).map(key => `builder(): ${key}`))
- translated.neverBundle.push(...inferredExternals(pkg))
- return translated
-}
-
-/**
- * Fails when `build.config.*` or a `build` or `unbuild` field of `package.json` would
- * configure the build alongside `builder()`.
- */
-export function assertNoLegacyBuildConfig(cwd: string, pkg: PackageJson): void {
- const file = BUILD_CONFIG_FILES.find(file => existsSync(resolve(cwd, file)))
- const field = pkg.unbuild !== undefined ? 'unbuild' : pkg.build !== undefined ? 'build' : undefined
- if (file || field) {
- const source = file ? `\`${file}\`` : `The \`${field}\` field of \`package.json\``
- const advice = file ? 'delete the file' : 'remove the field'
- throw new Error(`${source} configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and ${advice}. ${guide('moving-from-buildconfigts')}`)
- }
-}
-
-/** `src/module` plus the translated extra entries, keyed by output name. */
-export function bundledEntries(cwd: string, config: TranslatedBuildConfig): { module: string, [name: string]: string } {
- const module = probe(resolve(cwd, 'src/module')) ?? resolve(cwd, 'src/module.ts')
- return { ...config.entries, module: `./${relative(cwd, module)}` }
-}
-
-export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void {
- for (const hook of config.ignoredHooks) {
- consola.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`)
- }
- if (config.file) {
- consola.warn([
- `\`${config.file}\` is deprecated. Its options are still applied.`,
- ...config.importsUnbuild ? ['Import `defineBuildConfig` from `@nuxt/module-builder` instead of `unbuild`.'] : [],
- 'Move them into `builder()` in `tsdown.config.ts`.',
- guide('moving-from-buildconfigts'),
- ].join(' '))
- }
- if (config.field === 'unbuild') {
- consola.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`)
- }
-}
-
-export interface BuildContextOptions {
- cwd: string
- outDir: string
- pkg: PackageJson
- config: TranslatedBuildConfig
- directories: DirectoryEntry[]
- sourcemap: boolean
-}
-
-export function createBuildContext({ cwd, outDir, pkg, config, directories, sourcemap }: BuildContextOptions): BuildContext {
- return {
- options: {
- name: (pkg.name || '').split('/').pop() || 'default',
- rootDir: cwd,
- outDir,
- entries: [
- ...Object.entries(bundledEntries(cwd, config)).map(([name, input]) => ({ input: resolve(cwd, input), name, builder: 'rollup' as const, outDir })),
- ...directories.map(({ srcDir, outDir }) => ({ input: `${srcDir}/`, name: entryName(relative(cwd, srcDir), cwd), builder: 'mkdist' as const, outDir })),
- ],
- declaration: config.declaration,
- stub: false,
- sourcemap,
- },
- pkg,
- }
-}
-
-export async function callBuildHook(config: TranslatedBuildConfig, hook: SupportedHook, ctx: BuildContext): Promise {
- for (const fn of config.hooks[hook]) {
- await fn(ctx)
- }
-}
-
-export function formatUnsupportedOptions(unsupported: string[]): string {
- return [
- 'The build config uses options that `@nuxt/module-builder` v2 does not support:',
- ...unsupported.map(option => ` - ${option} (${guide(unsupportedOptionSection(option))})`),
- `Remove each of them from the file named. ${guide('unsupported-build-options')}`,
- ].join('\n')
-}
-
-function unsupportedOptionSection(option: string): GuideSection {
- const name = option.slice(option.indexOf(': ') + 2)
- if (name.startsWith('hooks[')) {
- return 'hooks'
- }
- if (name.startsWith('rollup.emitCJS')) {
- return 'commonjs-output'
- }
- if (name.startsWith('rollup')) {
- return 'rollup-options'
- }
- if (/^entries\[\d+\]\.(?!outDir|builder)/.test(name)) {
- return 'mkdist-options'
- }
- return 'other-options'
-}
-
-/**
- * The module's own package name, which is never bundled. Self-referencing imports of the
- * runtime tree are left to `runtimeExternals`.
- */
-function inferredExternals(pkg: PackageJson) {
- return pkg.name ? [new RegExp(`^${escapeRegExp(pkg.name)}(?:$|/(?!runtime/))`)] : []
-}
-
-function isPlainObject(value: unknown): value is Record {
- return !!value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof RegExp)
-}
-
-function escapeRegExp(value: string) {
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
-}
diff --git a/src/build/build.ts b/src/build/build.ts
index 79ba695a..30210122 100644
--- a/src/build/build.ts
+++ b/src/build/build.ts
@@ -3,27 +3,23 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { readFile, rm } from 'node:fs/promises'
import { dirname, join, normalize, relative, resolve } from 'pathe'
import { consola } from 'consola'
+import type { NuxtModule } from '@nuxt/schema'
import type { TsConfigResult } from 'get-tsconfig'
import type { PackageJson } from 'pkg-types'
import { glob, globSync } from 'tinyglobby'
import builderPkg from '../../package.json' with { type: 'json' }
-import { probe as probeSource, scriptExtension, valueSpecifiers } from '../rolldown/resolve.ts'
-import { DEFAULT_EXCLUDE } from '../rolldown/transpile-dir.ts'
-import type { ResolveExternal } from '../rolldown/transpile-dir.ts'
-import { createTsconfigResolver, declarationPaths, findPackageDir, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../rolldown/tsconfig.ts'
-import { shouldAdvise } from './advice.ts'
+import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts'
+import { EXCLUDE } from '../transpile/transpile-dir.ts'
+import type { ResolveExternal } from '../transpile/transpile-dir.ts'
+import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts'
+import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts'
import { rewriteRuntimeDeclarations } from './aliases.ts'
-import { bundledEntries, callBuildHook, createBuildContext, formatUnsupportedOptions, warnDeprecatedBuildConfig } from './build-config.ts'
-import type { DirectoryEntry, LoadedBuildConfig } from './build-config.ts'
-import type { BuildContext } from './define.ts'
-import { checkDeprecatedPackageFields } from './deprecations.ts'
-import { NUXT_EXTERNALS } from './externals.ts'
import { guide } from './guide.ts'
-import { assertLoadableModuleCode, loadOxc, probe } from './loader.ts'
-import { writeModuleMeta } from './meta.ts'
-import { importsKeyFor, publishedPackage, unpublishableImportsError } from './package.ts'
-import { hasIsolatedDeclarations, selfReferencePaths } from './tsconfig.ts'
+import { assertLoadableModuleCode, importModule, loadOxc } 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'
import { writeTypes } from './types.ts'
const ISOLATED_DECLARATIONS_HINT = [
@@ -42,36 +38,32 @@ const TYPE_ERROR_HINT = [
`If \`.nuxt\` is out of date, run \`nuxt-module-build prepare\` and build again. ${guide('declaration-errors')}`,
].join('\n')
-const SCRIPT_RE = /\.[cm]?[jt]sx?$/
const SERVER_DIR_RE = /(?:^|\/)server\//
-export function shouldNudge(isolatedDeclarations: boolean): boolean {
- return !isolatedDeclarations && shouldAdvise('isolated-declarations')
-}
+let nudged = false
-export interface ResolveBuildOptions {
- cwd: string
- pkg: PackageJson
- /** Absolute path of the output directory, already checked with `resolveOutDir`. */
- outDir: string
- sourcemap: boolean
- /** Loads the translated build config once the module's tsconfig has been read. */
- loadConfig: () => Promise
+/** Whether to suggest `isolatedDeclarations`, which happens once per process and never in CI. */
+export function shouldNudge(isolatedDeclarations: boolean): boolean {
+ if (isolatedDeclarations || nudged || process.env.CI) {
+ return false
+ }
+ nudged = true
+ return true
}
/** Everything a build needs to know about the module, resolved before anything is written. */
export interface BuildPlan {
cwd: string
pkg: PackageJson
+ /** Absolute path of the output directory, already checked with `resolveOutDir`. */
outDir: string
- config: LoadedBuildConfig
+ config: ModuleConfig
/** `src/runtime` and every other directory transpiled file by file. */
directories: DirectoryEntry[]
/** Bundled entries keyed by output name, as paths relative to `cwd`. */
entries: { module: string, [name: string]: string }
runtimeDirs: string[]
sourcemap: boolean
- ctx: BuildContext
neverBundle: (string | RegExp)[]
moduleTsconfig: TsConfigResult | undefined
/** The nearest tsconfig, which may delegate files to `references`. */
@@ -90,8 +82,6 @@ export interface BuildPlan {
generatedTypesHash: string
/** Set by {@link prepareBuild}. */
prepared?: PreparedBuild
- /** Whether {@link finishBuild} writes `types.d.mts`, rather than a bundled entry named `types`. */
- writesTypes?: boolean
}
export interface PreparedBuild {
@@ -102,28 +92,19 @@ export interface PreparedBuild {
startedAt: number
}
-export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }: ResolveBuildOptions): Promise {
- const runtimeSrcDir = resolve(cwd, 'src/runtime')
+export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Pick): Promise {
const tsconfigs = await createTsconfigResolver(cwd)
if (tsconfigs.replaced) {
const path = relative(cwd, tsconfigs.replaced)
- const advice = path.startsWith('..') ? 'Add a `tsconfig.json` in the module directory that extends `./.nuxt/tsconfig.json`.' : 'Extend `./.nuxt/tsconfig.json` in the module\'s tsconfig.'
+ const advice = !isInside(cwd, tsconfigs.replaced) ? 'Add a `tsconfig.json` in the module directory that extends `./.nuxt/tsconfig.json`.' : 'Extend `./.nuxt/tsconfig.json` in the module\'s tsconfig.'
consola.info(`\`${path}\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. ${advice} ${guide('module-tsconfig')}`)
}
- const selfPaths = selfReferencePaths(cwd, pkg, outDir)
-
- const config = await loadConfig()
- if (config.unsupported.length) {
- throw new Error(formatUnsupportedOptions(config.unsupported))
- }
- warnDeprecatedBuildConfig(config)
- const directories: DirectoryEntry[] = [{ srcDir: runtimeSrcDir, outDir: join(outDir, 'runtime'), ext: 'js' }, ...config.directories]
- const resolvedSourcemap = sourcemap || config.sourcemap
- const ctx = createBuildContext({ cwd, outDir, pkg, config, directories, sourcemap: resolvedSourcemap })
+ const directories: DirectoryEntry[] = [{ srcDir: resolve(cwd, 'src/runtime'), outDir: join(outDir, 'runtime'), ext: 'js' }, ...config.directories]
const entries = bundledEntries(cwd, config)
+ const selfPaths = selfReferencePaths(cwd, pkg, outDir, entries)
- const moduleTsconfig = tsconfigs.resolve(resolve(cwd, entries.module ?? Object.values(entries)[0]!))
+ const moduleTsconfig = tsconfigs.resolve(resolve(cwd, entries.module))
const nuxtDir = findPackageDir('nuxt', cwd)
return {
@@ -134,8 +115,7 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }:
directories,
entries,
runtimeDirs: directories.map(directory => directory.srcDir),
- sourcemap: resolvedSourcemap,
- ctx,
+ sourcemap: sourcemap || !!config.sourcemap,
neverBundle: [...NUXT_EXTERNALS, ...config.neverBundle],
moduleTsconfig,
rootTsconfig: tsconfigs.root,
@@ -143,8 +123,6 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }:
isolatedDeclarations: hasIsolatedDeclarations(moduleTsconfig),
selfPaths,
declarationTsconfig: moduleTsconfig ? namedCachePath(cwd, `declarations-${createHash('sha256').update(outDir).digest('hex').slice(0, 12)}.json`) : false,
- // `eager` puts every file of the tsconfig in the program, so ambient declarations such
- // as `.nuxt/nuxt.d.ts` apply and inferred types can be named by their package.
declarationPaths: declarationPaths({ ...selfPaths, ...tsconfigPaths(moduleTsconfig) }, cwd).paths,
directoryPaths: { ...selfPaths, ...nuxtDir && { '#app/nuxt': [join(nuxtDir, 'dist/app/nuxt')] } },
generatedTypesHash: await hashGeneratedTypes(cwd),
@@ -155,9 +133,9 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }:
* Runs `build:before` hooks, checks the module's imports, empties the output directory unless
* `keepOutput` is set, and writes what declaration generation reads.
*/
-export async function prepareBuild(plan: BuildPlan, { keepOutput = false }: { keepOutput?: boolean } = {}): Promise {
+export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput: boolean }): Promise {
const { cwd, outDir, entries, runtimeDirs } = plan
- await callBuildHook(plan.config, 'build:before', plan.ctx)
+ await plan.config.callHook?.('build:before', plan)
assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries))
if (!keepOutput) {
await rm(outDir, { recursive: true, force: true })
@@ -168,9 +146,7 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput = false }: { ke
const imports = plan.moduleProject ? await writeDependencyImports(cwd, plan.rootTsconfig) : undefined
await writeDerivedTsconfig(cwd, plan.moduleTsconfig, plan.selfPaths, { file: plan.declarationTsconfig, imports })
}
-
plan.prepared = analyseSources(plan)
- return plan.prepared
}
/**
@@ -179,16 +155,14 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput = false }: { ke
*/
export function analyseSources(plan: BuildPlan): PreparedBuild {
const { cwd, entries } = plan
- const bundledSources = new Map()
- for (const [name, input] of Object.entries(entries)) {
+ const bundledSources = new Map(Object.entries(entries).flatMap(([name, input]) => {
const file = probe(resolve(cwd, input))
- if (file) {
- bundledSources.set(normalize(file), `${name}.mjs`)
- }
- }
+ return file ? [[normalize(file), `${name}.mjs`] as const] : []
+ }))
// Nitro and Node do not transform files in `node_modules`, so JSX that runs there is compiled.
- const runtimeFiles = plan.directories.map(directory => globSync(['**/*'], { cwd: directory.srcDir, ignore: DEFAULT_EXCLUDE, absolute: true, onlyFiles: true }))
- const serverFiles = runtimeFiles.flat().map(file => normalize(file)).filter(file => SCRIPT_RE.test(file) && SERVER_DIR_RE.test(relative(cwd, file)))
+ const serverFiles = plan.directories.flatMap(directory => globSync(['**/*'], { cwd: directory.srcDir, ignore: EXCLUDE, absolute: true, onlyFiles: true }))
+ .map(file => normalize(file))
+ .filter(file => SCRIPT_RE.test(file) && SERVER_DIR_RE.test(relative(cwd, file)))
const compiledJsx = valueImports([...serverFiles, ...bundledSources.keys()])
return { bundledSources, compiledJsx, startedAt: Date.now() }
}
@@ -200,26 +174,19 @@ export function preservesJsx(plan: BuildPlan, file: string): boolean {
/**
* Where a relative import that resolves outside a transpiled directory points. Bundled
- * entries and other directories keep their own output. Any other file is mirrored where
- * the specifier already points, or under `_external/` when that would take the name of a
- * bundled entry or `types`.
+ * entries and other directories keep their own output. Any other file is mirrored.
*/
-export function resolveDirectoryExternal(plan: BuildPlan, directory: DirectoryEntry): ResolveExternal {
- const { cwd, outDir, directories } = plan
- const reserved = new Set([...Object.keys(plan.entries), 'types'])
- return (_specifier, _importer, { file, kind, from, output }) => {
+export function resolveDirectoryExternal(plan: BuildPlan): ResolveExternal {
+ const { outDir, directories } = plan
+ return (_specifier, _importer, { file, kind, from }) => {
const bundled = plan.prepared?.bundledSources.get(file)
if (bundled) {
return relativeSpecifier(from, bundled)
}
- const other = directories.find(directory => !relative(directory.srcDir, file).startsWith('..'))
+ const other = directories.find(directory => isInside(directory.srcDir, file))
if (other) {
return relativeSpecifier(from, join(relative(outDir, other.outDir), relative(other.srcDir, file).replace(SCRIPT_RE, scriptExtension(file, `.${other.ext}`, preservesJsx(plan, file)))))
}
- if (reserved.has(output.replace(SCRIPT_RE, ''))) {
- const segments = relative(cwd, file).replace(SCRIPT_RE, scriptExtension(file, `.${directory.ext}`, preservesJsx(plan, file))).split('/').map(segment => segment === '..' ? '_' : segment)
- return { mirror: kind, output: join('_external', ...segments) }
- }
return { mirror: kind }
}
}
@@ -228,11 +195,11 @@ export interface BuildErrorOptions {
/** Whether the error comes from a transpiled directory rather than the bundled entries. */
directory?: boolean
/** Keeps the previous output, which a watcher goes on serving. */
- keepOutput?: boolean
+ keepOutput: boolean
}
/** Removes a partial output directory and explains declaration failures. */
-export async function onBuildError(plan: BuildPlan, error: unknown, { directory = isDirectoryError(error), keepOutput }: BuildErrorOptions = {}): Promise {
+export async function onBuildError(plan: BuildPlan, error: unknown, { directory = isDirectoryError(error), keepOutput }: BuildErrorOptions): Promise {
if (!keepOutput) {
await rm(plan.outDir, { recursive: true, force: true })
}
@@ -249,46 +216,55 @@ export interface FinishBuildOptions {
outputs: string[]
/** Versions recorded as `builder` in `module.json`, besides this package's. */
builder: Record
+ /** Keeps the output when a step or check fails, as a watcher goes on serving it. */
+ keepOutput?: boolean
}
// Counted per process, as a restarted watcher imports the same files again with a new plan.
let metaImports = 0
/** Writes `module.json` and `types.d.mts`, finalises declarations and runs the checks and remaining hooks. */
-export async function finishBuild(plan: BuildPlan, { outputs, builder }: FinishBuildOptions): Promise {
+export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutput }: FinishBuildOptions): Promise {
const { cwd, outDir, pkg } = plan
const duration = Date.now() - (plan.prepared?.startedAt ?? Date.now())
- const version = metaImports++ || undefined
- await writeModuleMeta({
- cwd,
- outDir,
- pkg,
- builder: { [builderPkg.name]: builderPkg.version, ...builder },
- version,
- }).catch((error) => {
- consola.error(error)
- consola.error('Cannot load module. Please check dist:', resolve(outDir, 'module.mjs'))
- })
- const typesFile = join(outDir, 'types.d.mts')
- plan.writesTypes ??= !existsSync(typesFile)
- if (plan.writesTypes) {
+ try {
+ const types = outputs.find(file => file === 'types.mjs' || file === 'types.d.mts')
+ if (types) {
+ throw new Error(`A directory entry emits \`${types}\` at the root of \`${relative(cwd, outDir)}\`, which would replace the generated \`types.d.mts\`. Rename the file, or give the directory entry another \`outDir\`.`)
+ }
+ const moduleFile = resolve(outDir, 'module.mjs')
+ const meta = await importModule(moduleFile, { cwd, version: metaImports++ || undefined })
+ .then(exports => ((exports.default ?? exports) as NuxtModule>).getMeta?.())
+ .then(meta => meta || {}, (error) => {
+ throw new Error(`Cannot load \`${relative(cwd, moduleFile)}\` to write \`module.json\`: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
+ })
+ meta.name ||= pkg.name
+ meta.version ||= pkg.version
+ meta.builder = { [builderPkg.name]: builderPkg.version, ...builder }
+ await writeIfChanged(resolve(outDir, 'module.json'), JSON.stringify(meta, null, 2))
await writeTypes(outDir)
- }
- await callBuildHook(plan.config, 'rollup:done', plan.ctx)
- await rewriteRuntimeDeclarations(outDir, outputs)
+ await plan.config.callHook?.('rollup:done', plan)
+ await rewriteRuntimeDeclarations(outDir, outputs)
- if (shouldNudge(plan.isolatedDeclarations)) {
- const project = plan.moduleProject && relative(cwd, plan.moduleProject)
- const where = !project ? 'your `tsconfig.json`' : project.startsWith('.nuxt') ? 'a `tsconfig.module.json` that extends `./.nuxt/tsconfig.node.json`' : `\`${project}\``
- consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`)
- }
+ if (shouldNudge(plan.isolatedDeclarations)) {
+ const project = plan.moduleProject && relative(cwd, plan.moduleProject)
+ const where = !project ? 'your `tsconfig.json`' : project.startsWith('.nuxt') ? 'a `tsconfig.module.json` that extends `./.nuxt/tsconfig.node.json`' : `\`${project}\``
+ consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`)
+ }
- await checkDeprecatedPackageFields(cwd)
- const importsError = unpublishableImportsError(cwd, pkg, importedFrom(outDir, Object.keys(publishedPackage(pkg).imports ?? {})))
- if (importsError) {
- throw new Error(importsError)
+ await checkPublishedPaths(cwd)
+ const importsError = unpublishableImportsError(cwd, pkg, importedFrom(outDir, Object.keys(publishedPackage(pkg).imports ?? {})))
+ if (importsError) {
+ throw new Error(importsError)
+ }
+ await plan.config.callHook?.('build:done', plan)
+ }
+ catch (error) {
+ if (!keepOutput) {
+ await rm(outDir, { recursive: true, force: true })
+ }
+ throw error
}
- await callBuildHook(plan.config, 'build:done', plan.ctx)
}
const OUTPUT_TEXT_RE = /\.(?:[cm]?[jt]sx?|vue|css)$/
@@ -306,8 +282,8 @@ function importedFrom(dir: string, keys: string[]): (key: string) => boolean {
}
function valueImports(roots: string[]) {
- const transform = loadOxc()?.transformSync
- const queue = roots.filter(file => SCRIPT_RE.test(file))
+ const { transformSync } = loadOxc()!
+ const queue = roots.filter(isSourceScript)
const found = new Set()
while (queue.length) {
const file = queue.pop()!
@@ -315,13 +291,10 @@ function valueImports(roots: string[]) {
continue
}
found.add(file)
- const source = readFileSync(file, 'utf8')
- const code = transform
- ? (transform(file, source, { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], jsx: 'preserve', typescript: { onlyRemoveTypeImports: false } })).code
- : source
+ const { code } = transformSync(file, readFileSync(file, 'utf8'), { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], jsx: 'preserve', typescript: { onlyRemoveTypeImports: false } })
for (const specifier of valueSpecifiers(code)) {
- const target = probeSource(resolve(dirname(file), specifier))
- if (target && SCRIPT_RE.test(target)) {
+ const target = probe(resolve(dirname(file), specifier))
+ if (target && isSourceScript(target)) {
queue.push(normalize(target))
}
}
@@ -334,19 +307,17 @@ function isDirectoryError(error: unknown) {
return Array.isArray(errors) && errors.some(nested => nested.plugin === 'transpile-dir')
}
-function relativeSpecifier(from: string, to: string) {
- const path = relative(dirname(from), to)
- return path.startsWith('.') ? path : `./${path}`
-}
+const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb']
/**
- * A hash of the types Nuxt generates in `.nuxt/`, which augment what single-file
- * component declarations refer to without being visible to the declaration cache.
+ * A hash of the types Nuxt generates in `.nuxt/` and of the nearest lockfile, which change
+ * what single-file component declarations refer to without being visible to the declaration cache.
*/
-async function hashGeneratedTypes(cwd: string) {
+export async function hashGeneratedTypes(cwd: string): Promise {
const files = await glob(['tsconfig.json', '**/*.d.ts'], { cwd: join(cwd, '.nuxt'), absolute: true, onlyFiles: true })
+ const lockfile = findUp(cwd, dir => LOCKFILES.map(name => join(dir, name)).find(file => existsSync(file)))
const hash = createHash('sha256')
- for (const file of files.sort()) {
+ for (const file of [...files.sort(), ...lockfile ? [lockfile] : []]) {
hash.update(relative(cwd, file)).update(await readFile(file))
}
return hash.digest('hex').slice(0, 12)
diff --git a/src/build/deprecations.ts b/src/build/deprecations.ts
deleted file mode 100644
index 51e1fea6..00000000
--- a/src/build/deprecations.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { existsSync, statSync } from 'node:fs'
-import { relative, resolve } from 'pathe'
-import { consola } from 'consola'
-import { readPackageJSON } from 'pkg-types'
-
-import { guide } from './guide.ts'
-import { collectStrings, publishedPackage } from './package.ts'
-
-/**
- * Warn about `package.json` fields that point at output this builder no longer produces.
- * The paths are read as published, with `publishConfig` applied.
- */
-export async function checkDeprecatedPackageFields(cwd: string): Promise {
- const read = await readPackageJSON(cwd).catch(() => undefined)
- const pkg = read && publishedPackage(read)
- if (!pkg) {
- return
- }
-
- checkLegacyDeclarationPaths(cwd, pkg)
- checkLegacyCJSPaths(cwd, pkg)
- checkStaleTypesField(cwd, pkg)
- checkNode10DeclarationPaths(cwd, pkg)
- checkMissingPaths(cwd, pkg)
-}
-
-type PackageJSON = Awaited>
-
-const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/
-const CJS_MODULE_RE = /module\.cjs$/
-
-export function checkLegacyDeclarationPaths(cwd: string, pkg: PackageJSON): boolean {
- if (!missingPaths(cwd, pkg).some(path => DECLARATION_RE.test(path))) {
- return false
- }
- consola.warn(`\`@nuxt/module-builder\` no longer generates \`.d.ts\` declarations for the module entry. Replace \`.d.ts\` with \`.d.mts\` in these \`package.json\` paths: ${list(missingPaths(cwd, pkg).filter(path => DECLARATION_RE.test(path)))}. ${guide('declaration-paths')}`)
- return true
-}
-
-export function checkLegacyCJSPaths(cwd: string, pkg: PackageJSON): boolean {
- if (!missingPaths(cwd, pkg).some(path => CJS_MODULE_RE.test(path))) {
- return false
- }
- consola.warn(`\`@nuxt/module-builder\` no longer generates \`module.cjs\`, which Nuxt 3 and later do not need. Replace it with \`./dist/module.mjs\` in \`package.json\`. ${guide('modulecjs')}`)
- return true
-}
-
-export function checkStaleTypesField(cwd: string, pkg: PackageJSON): boolean {
- if (!pkg.types || resolvesForTypeScript(cwd, pkg.types)) {
- return false
- }
- consola.warn(`\`types\` in \`package.json\` points at \`${pkg.types}\`, which the build does not produce. Set it to \`./dist/types.d.mts\`, which node10 module resolution reads, or remove it: bundler module resolution reads \`exports\` instead. ${guide('the-types-field')}`)
- return true
-}
-
-/**
- * Warn about `typesVersions` paths that TypeScript's node10 resolution cannot find because
- * they rely on probing for `.d.ts`, where the build now produces `.d.mts`.
- */
-export function checkNode10DeclarationPaths(cwd: string, pkg: PackageJSON): boolean {
- const entries = typesVersionsPaths(pkg).flatMap((path) => {
- const replacement = node10Replacement(cwd, path)
- return replacement ? [`\`${path}\` (use \`${replacement}\`)`] : []
- })
- if (!entries.length) {
- return false
- }
- consola.warn(`These \`typesVersions\` paths in \`package.json\` do not resolve under TypeScript's node10 module resolution, which probes for \`.d.ts\` but not for \`.d.mts\`: ${entries.join(', ')}. Write each path with its extension. ${guide('typesversions-paths')}`)
- return true
-}
-
-/** Warn about paths in `package.json` that the build did not produce, other than those the checks above explain. */
-export function checkMissingPaths(cwd: string, pkg: PackageJSON): boolean {
- const paths = [...new Set(missingPaths(cwd, pkg))]
- .filter(path => !path.includes('*') && !DECLARATION_RE.test(path) && !CJS_MODULE_RE.test(path) && path !== pkg.types && !node10Replacement(cwd, path))
- if (!paths.length) {
- return false
- }
- consola.warn(`These paths in \`package.json\` do not exist after the build, so imports that resolve to them will fail: ${list(paths)}. Add the entry that produces each one, or remove the path. ${guide('paths-the-build-does-not-produce')}`)
- return true
-}
-
-function list(paths: string[]) {
- return [...new Set(paths)].map(path => `\`${path}\``).join(', ')
-}
-
-const TS_PROBES = ['', '.ts', '.tsx', '.d.ts', '/index.ts', '/index.tsx', '/index.d.ts']
-const TS_MODULE_PROBES = ['.d.mts', '.d.cts', '/index.d.mts', '/index.d.cts']
-
-function isFile(path: string) {
- return existsSync(path) && statSync(path).isFile()
-}
-
-/** Whether TypeScript's node10 resolution finds a file for `path`: as written, or with a `.ts`, `.tsx`, `.d.ts` or `/index` suffix. */
-function resolvesForTypeScript(cwd: string, path: string) {
- return TS_PROBES.some(suffix => isFile(resolve(cwd, path + suffix)))
-}
-
-/** The `.d.mts` or `.d.cts` file an unresolvable `path` was meant to reach, as a `./` path. */
-function node10Replacement(cwd: string, path: string) {
- if (resolvesForTypeScript(cwd, path)) {
- return
- }
- const suffix = TS_MODULE_PROBES.find(suffix => isFile(resolve(cwd, path + suffix)))
- return suffix === undefined ? undefined : `./${relative(cwd, resolve(cwd, path + suffix))}`
-}
-
-function typesVersionsPaths(pkg: PackageJSON) {
- return collectStrings(pkg.typesVersions).filter(path => !path.includes('*'))
-}
-
-function missingPaths(cwd: string, pkg: PackageJSON): string[] {
- const typesVersions = new Set(typesVersionsPaths(pkg))
- return referencedPaths(pkg).filter(path => !path.startsWith('/') && !(typesVersions.has(path) ? resolvesForTypeScript(cwd, path) : existsSync(resolve(cwd, path))))
-}
-
-function referencedPaths(pkg: PackageJSON): string[] {
- return [...[pkg.exports, pkg.typesVersions, pkg.types, pkg.main, pkg.module].flatMap(collectStrings), ...collectStrings(pkg.imports).filter(path => path.startsWith('./'))]
-}
diff --git a/src/build/externals.ts b/src/build/externals.ts
deleted file mode 100644
index b8ea2dd0..00000000
--- a/src/build/externals.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export const NUXT_EXTERNALS: (string | RegExp)[] = [
- '@nuxt/schema',
- '@nuxt/schema-nightly',
- '@nuxt/schema-edge',
- '@nuxt/kit',
- '@nuxt/kit-nightly',
- '@nuxt/kit-edge',
- /^#app(\/|$)/,
- /^#build(\/|$)/,
- /^#imports$/,
- /^nuxt(\/|$)/,
- 'nuxt-nightly',
- 'nuxt-edge',
- 'nuxt3',
- 'vue',
- 'vue-demi',
-]
diff --git a/src/build/guide.ts b/src/build/guide.ts
index 2fdfabf4..a6370abb 100644
--- a/src/build/guide.ts
+++ b/src/build/guide.ts
@@ -2,7 +2,6 @@ const GUIDE_URL = 'https://github.com/nuxt/module-builder/blob/main/docs/upgrade
/** The sections of the upgrade guide that build messages link to, by heading anchor. */
export const GUIDE_SECTIONS = [
- 'node-engines',
'install-tsdown',
'build-configuration',
'tsdown-config',
diff --git a/src/build/loader.ts b/src/build/loader.ts
index 336a220d..e04be434 100644
--- a/src/build/loader.ts
+++ b/src/build/loader.ts
@@ -1,26 +1,23 @@
-import { existsSync, readFileSync, statSync } from 'node:fs'
+import { existsSync, readFileSync } from 'node:fs'
import { createRequire, registerHooks } from 'node:module'
import { fileURLToPath, pathToFileURL } from 'node:url'
-import { dirname, isAbsolute, relative, resolve } from 'pathe'
+import { dirname, relative, resolve } from 'pathe'
import { resolvePathSync } from 'mlly'
import { createPathsMatcher, getTsconfig } from 'get-tsconfig'
import type ts from 'typescript'
-import type { Transform } from '../rolldown/transpile-dir.ts'
+import type { Transform } from '../transpile/transpile-dir.ts'
+import { isInside, NODE_MODULES_RE, probe, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts'
import { guide } from './guide.ts'
const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/
-const ALIAS_SHAPED_RE = /^(?:#|~|@\/)/
-const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
+const PATH_ALIAS_RE = /^(?:~|@\/)/
const JSON_RE = /\.json$/
const UNLOADABLE_RE = /\.(?:vue|[jt]sx)$/
-const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx']
export interface ImportModuleOptions {
/** Module root, inside which `version` applies. */
- cwd?: string
- /** The build's output directory, inside which `version` also applies. */
- outDir?: string
+ cwd: string
/** Source code to serve in place of these bare specifiers. */
stubs?: Record
/**
@@ -35,40 +32,33 @@ export interface ImportModuleOptions {
* Import a file as Node does, with `stubs` for bare specifiers. Module code has to load as
* Node loads it (see {@link findModuleCodeIssues}).
*/
-export async function importModule(path: string, options: ImportModuleOptions = {}): Promise> {
- const cwd = options.cwd ?? process.cwd()
- const stubs = options.stubs || {}
-
+export async function importModule(path: string, { cwd, stubs = {}, version }: ImportModuleOptions): Promise> {
+ const versioned = (href: string) => {
+ const url = new URL(href)
+ url.searchParams.set('v', String(version))
+ return url.href
+ }
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
if (Object.hasOwn(stubs, specifier)) {
return { url: `data:text/javascript,${encodeURIComponent(stubs[specifier]!)}`, shortCircuit: true }
}
const resolved = nextResolve(specifier, context)
- if (!options.version || !resolved.url.startsWith('file:') || ![cwd, options.outDir ?? cwd].some(root => isInside(root, fileURLToPath(resolved.url))) || NODE_MODULES_RE.test(resolved.url)) {
+ if (!version || !resolved.url.startsWith('file:') || !isInside(cwd, fileURLToPath(resolved.url)) || NODE_MODULES_RE.test(resolved.url)) {
return resolved
}
- const url = new URL(resolved.url)
- url.searchParams.set('v', String(options.version))
- return { ...resolved, url: url.href }
+ return { ...resolved, url: versioned(resolved.url) }
},
})
-
try {
- const url = pathToFileURL(path)
- if (options.version) {
- url.searchParams.set('v', String(options.version))
- }
- return await import(url.href)
+ const url = pathToFileURL(path).href
+ return await import(version ? versioned(url) : url)
}
finally {
hooks.deregister()
}
}
-const TYPESCRIPT_RE = /\.[cm]?tsx?$/
-const SOURCE_RE = /\.[cm]?[jt]sx?$/
-
interface Oxc {
transform: Transform
transformSync: (...args: Parameters) => Awaited>
@@ -100,15 +90,15 @@ export interface ModuleCodeIssue {
message: string
}
-const NON_ERASABLE_FIXES: Record = {
- '`enum`': 'use an `as const` object and a union type of its values',
- '`namespace`': 'use plain exports or an object',
- 'angle-bracket type assertion': 'write `value as Type`',
- 'parameter property': 'declare the field and assign it in the constructor',
- '`import =`': 'use `import`, or `createRequire` for CommonJS',
- '`export =`': 'use `export default`',
- 'decorator': 'call the decorator as a function',
-}
+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)],
+]
/**
* Everything in `entries` and the sources they import by value, which Node loads with
@@ -127,8 +117,8 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs
checked.add(file)
const importedBy = importer && runtimeDirs.some(dir => isInside(dir, file)) ? `${relative(cwd, importer.file)}:${importer.line}` : undefined
const issue = (location: { line: number, column: number }, message: string) => found.push({ file: relative(cwd, file), ...location, ...importedBy && { importedBy }, message })
- for (const { kind, ...location } of analysis.nonErasable) {
- issue(location, `${kind} (${NON_ERASABLE_FIXES[kind]})`)
+ for (const { message, ...location } of analysis.nonErasable) {
+ issue(location, message)
}
for (const { specifier, typeOnly, json, resolution, ...location } of analysis.imports) {
if (typeOnly) {
@@ -147,7 +137,7 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs
issue(location, `\`${specifier}\` is ${resolution.file.endsWith('.vue') ? 'a single-file component' : 'JSX'}, which Node cannot load (move the value the module needs into a \`.ts\` file, or use \`import type\`)`)
continue
}
- const suggestion = relativeSpecifier(dirname(file), resolution.file)
+ const suggestion = relativeSpecifier(file, resolution.file)
if (resolution.via === 'relative' && resolution.file !== resolve(dirname(file), specifier)) {
issue(location, `\`${specifier}\` (use \`${suggestion}\`)`)
}
@@ -162,7 +152,7 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs
}
for (const { specifier, typeOnly, json: _, resolution, ...location } of analysis.imports) {
if (!typeOnly && resolution?.via === 'relative' && resolution.file !== resolve(dirname(file), specifier)) {
- found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(dirname(file), resolution.file)}\`)` })
+ found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(file, resolution.file)}\`)` })
}
}
})
@@ -194,7 +184,7 @@ interface Resolution {
}
interface SourceAnalysis {
- nonErasable: Array<{ line: number, column: number, kind: string }>
+ nonErasable: Array<{ line: number, column: number, message: string }>
imports: Array<{ specifier: string, typeOnly: boolean, json: boolean, line: number, column: number, resolution?: Resolution }>
}
@@ -209,17 +199,15 @@ function walkSources(cwd: string, entries: string[], visit: (file: string, analy
const queue: Array<{ file: string, importer?: Importer }> = entries.map(entry => ({ file: resolve(cwd, entry) }))
while (queue.length) {
const { file, importer } = queue.shift()!
- if (seen.has(file) || !SOURCE_RE.test(file) || !existsSync(file)) {
+ if (seen.has(file) || !SCRIPT_RE.test(file) || !existsSync(file)) {
continue
}
seen.add(file)
const analysis = analyseSource(file, readFileSync(file, 'utf8'))
for (const entry of analysis.imports) {
entry.resolution = resolveSource(entry.specifier, dirname(file), cwd, matchPath)
- if (entry.resolution && !entry.typeOnly) {
- if (!UNLOADABLE_RE.test(entry.resolution.file)) {
- queue.push({ file: entry.resolution.file, importer: { file, line: entry.line } })
- }
+ if (entry.resolution && !entry.typeOnly && !UNLOADABLE_RE.test(entry.resolution.file)) {
+ queue.push({ file: entry.resolution.file, importer: { file, line: entry.line } })
}
}
visit(file, analysis, importer)
@@ -240,16 +228,6 @@ function resolvesAsPackage(specifier: string, parentDir: string) {
}
}
-function relativeSpecifier(from: string, to: string) {
- const path = relative(from, to)
- return path.startsWith('.') ? path : `./${path}`
-}
-
-function isInside(dir: string, path: string) {
- const subpath = relative(dir, path)
- return !subpath.startsWith('..') && !isAbsolute(subpath)
-}
-
/**
* The module source `specifier` reaches: a relative file, an entry in the `imports` of the
* module's `package.json`, or a tsconfig `paths` alias. Packages and the aliases only a
@@ -263,7 +241,7 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP
const file = probe(resolve(parentDir, specifier))
return file ? { file, via: 'relative' } : undefined
}
- const resolved = (specifier.startsWith('#') || !ALIAS_SHAPED_RE.test(specifier)) ? resolvesAsPackage(specifier, parentDir) : undefined
+ const resolved = PATH_ALIAS_RE.test(specifier) ? undefined : resolvesAsPackage(specifier, parentDir)
if (resolved) {
return specifier.startsWith('#') && isInside(cwd, resolved) && !NODE_MODULES_RE.test(resolved) ? { file: resolved, via: 'imports' } : undefined
}
@@ -301,7 +279,7 @@ function hasRuntimeCode(ts: typeof import('typescript'), node: ts.ModuleDeclarat
function analyseSource(filename: string, source: string): SourceAnalysis {
const ts = typescript ??= createRequire(import.meta.url)('typescript') as typeof import('typescript')
- const { SyntaxKind, NodeFlags } = ts
+ const { SyntaxKind } = ts
const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(ts, filename))
const found: SourceAnalysis = { nonErasable: [], imports: [] }
const position = (node: ts.Node) => {
@@ -344,36 +322,13 @@ function analyseSource(filename: string, source: string): SourceAnalysis {
return { specifier: node.arguments[0], typeOnly: false, json: isJsonOptions(node.arguments[1]) }
}
}
- const kindOf = (node: ts.Node) => {
- if (ts.isEnumDeclaration(node)) {
- return '`enum`'
- }
- if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name) && !(node.flags & (NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation)) && hasRuntimeCode(ts, node)) {
- return '`namespace`'
- }
- if (ts.isTypeAssertionExpression(node)) {
- return 'angle-bracket type assertion'
- }
- if (ts.isParameter(node) && ts.isParameterPropertyDeclaration(node, node.parent)) {
- return 'parameter property'
- }
- if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly) {
- return '`import =`'
- }
- if (ts.isExportAssignment(node) && node.isExportEquals) {
- return '`export =`'
- }
- if (ts.isDecorator(node)) {
- return 'decorator'
- }
- }
const visit = (node: ts.Node) => {
if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) {
return
}
- const kind = kindOf(node)
- if (kind) {
- found.nonErasable.push({ ...position(node), kind })
+ const nonErasable = NON_ERASABLE.find(([, matches]) => matches(ts, node))
+ if (nonErasable) {
+ found.nonErasable.push({ ...position(node), message: nonErasable[0] })
}
const imported = specifierOf(node)
if (imported) {
@@ -396,27 +351,3 @@ function pathsMatcher(cwd: string) {
return undefined
}
}
-
-/**
- * Find the source file a specifier refers to, trying the path as written, its
- * TypeScript counterpart, each source extension, then an `index` file.
- */
-export function probe(path: string): string | undefined {
- if (existsSync(path) && statSync(path).isFile()) {
- return path
- }
- const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2')
- if (source !== path && existsSync(source)) {
- return source
- }
- for (const extension of EXTENSIONS) {
- if (existsSync(path + extension)) {
- return path + extension
- }
- }
- for (const extension of EXTENSIONS) {
- if (existsSync(resolve(path, `index${extension}`))) {
- return resolve(path, `index${extension}`)
- }
- }
-}
diff --git a/src/build/meta.ts b/src/build/meta.ts
deleted file mode 100644
index 8d5c37ad..00000000
--- a/src/build/meta.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { resolve } from 'pathe'
-import type { NuxtModule } from '@nuxt/schema'
-
-import { importModule } from './loader.ts'
-import { writeIfChanged } from './write.ts'
-
-export interface WriteModuleMetaOptions {
- cwd: string
- outDir: string
- pkg: { name?: string, version?: string }
- builder: Record
- /** Set on rebuilds, so the rebuilt module is imported rather than the cached one. */
- version?: number
-}
-
-export async function writeModuleMeta({ cwd, outDir, pkg, builder, version }: WriteModuleMetaOptions): Promise {
- const moduleExports = await importModule(resolve(outDir, 'module.mjs'), { cwd, outDir, version })
- const moduleFn = (moduleExports.default ?? moduleExports) as NuxtModule>
-
- const moduleMeta = await moduleFn.getMeta?.() || {}
- moduleMeta.name ||= pkg.name
- moduleMeta.version ||= pkg.version
- moduleMeta.builder = builder
-
- await writeIfChanged(resolve(outDir, 'module.json'), JSON.stringify(moduleMeta, null, 2))
-}
diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts
index 74af841a..ca43a098 100644
--- a/src/build/module-declarations.ts
+++ b/src/build/module-declarations.ts
@@ -3,11 +3,11 @@ import { consola } from 'consola'
import type { TsConfigResult } from 'get-tsconfig'
import { dirname, join, normalize, relative, resolve } from 'pathe'
-import { createDeclarationProgram, relativeSpecifier } from '../rolldown/declarations.ts'
-import { DECLARATION_RE, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE } from '../rolldown/resolve.ts'
-import { isModuleFile } from '../rolldown/tsconfig.ts'
+import { createDeclarationProgram } from '../transpile/declarations.ts'
+import { 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 { hasIsolatedDeclarations } from './tsconfig.ts'
import { writeSourceTypes } from './types.ts'
const NUXT_DIR_RE = /^\.nuxt(?:\/|$)/
@@ -25,7 +25,7 @@ export function moduleDeclarationPaths(cwd: string, dir: string, name: string, s
const paths: Record = { [name]: [join(dir, 'types.d.mts')] }
for (const [alias, [target]] of Object.entries(selfPaths)) {
const file = target && !alias.includes('*') && alias !== name ? probe(target) : undefined
- if (file && SCRIPT_RE.test(file) && !runtimeDirs.some(runtimeDir => !relative(runtimeDir, file).startsWith('..'))) {
+ if (file && SCRIPT_RE.test(file) && !runtimeDirs.some(runtimeDir => isInside(runtimeDir, file))) {
paths[alias] = [declarationFile(cwd, dir, file)]
}
}
@@ -49,7 +49,7 @@ export interface ModuleDeclarationOptions {
*/
export async function writeModuleDeclarations(cwd: string, dir: string, { tsconfig, entry, roots, paths }: ModuleDeclarationOptions): Promise {
await writeSourceTypes(dir, entry, join(dir, relative(cwd, entry)))
- const isModuleCode = (file: string) => SCRIPT_RE.test(file) && !DECLARATION_RE.test(file) && isModuleFile(file, cwd) && !NUXT_DIR_RE.test(relative(cwd, file))
+ const isModuleCode = (file: string) => isSourceScript(file) && isModuleFile(file, cwd) && !NUXT_DIR_RE.test(relative(cwd, file))
const program = await createDeclarationProgram({ cwd, tsconfig, paths }, roots)
const sources = program.sources().filter(isModuleCode)
const { declarations, errors } = (hasIsolatedDeclarations(tsconfig) && await isolatedDeclarations(sources, cwd))
diff --git a/src/build/options.ts b/src/build/options.ts
new file mode 100644
index 00000000..c34b9812
--- /dev/null
+++ b/src/build/options.ts
@@ -0,0 +1,265 @@
+import { isAbsolute, normalize, relative, resolve } from 'pathe'
+import type { PackageJson } from 'pkg-types'
+
+import { assertNoLegacyBuildConfig } from '../legacy/build-config.ts'
+import { escapeRegExp, isInside, isPlainObject, probe, realpath } from '../utils.ts'
+import type { BuildPlan } from './build.ts'
+import { guide } from './guide.ts'
+
+export const NUXT_EXTERNALS: (string | RegExp)[] = [
+ '@nuxt/schema',
+ '@nuxt/schema-nightly',
+ '@nuxt/schema-edge',
+ '@nuxt/kit',
+ '@nuxt/kit-nightly',
+ '@nuxt/kit-edge',
+ /^#app(\/|$)/,
+ /^#build(\/|$)/,
+ /^#imports$/,
+ /^nuxt(\/|$)/,
+ 'nuxt-nightly',
+ 'nuxt-edge',
+ 'nuxt3',
+ 'vue',
+ 'vue-demi',
+]
+
+const ENTRY_KEYS = new Set(['input', 'name', 'builder', 'outDir', 'ext'])
+const DIRECTORY_EXTENSIONS = ['mjs', 'js'] as const
+
+/** The key `builder()` keeps its options under, so `prepare` can find them in a tsdown config. */
+export const BUILDER_OPTIONS: unique symbol = Symbol.for('@nuxt/module-builder:builder-options')
+
+/** An entry of `builder({ entries })`. */
+export type BuilderEntry
+ = | string
+ | { input: string, name?: string, builder?: 'rollup' }
+ | { input: string, builder?: 'mkdist', outDir?: string, ext?: 'mjs' | 'js' }
+
+export interface ReplaceOptions {
+ values: Record
+ delimiters?: [string, string]
+ preventAssignment?: boolean
+ objectGuards?: boolean
+}
+
+export interface BuilderOptions {
+ /**
+ * Entries built besides `src/module`. A path, or `{ input, name }`, is bundled. An `input`
+ * ending in `/` (or `builder: 'mkdist'`) is a directory transpiled file by file like
+ * `src/runtime`, into `outDir` (inside the build's output directory) with the `ext` scripts
+ * get: `mjs` (the default) or `js`.
+ */
+ entries?: BuilderEntry[]
+ /** Imports that are never bundled. A string matches the package and its subpaths. */
+ externals?: Array
+ /** Compile-time replacements in bundled entries, as `{ search: replacement }` or the options of rolldown's replace plugin. */
+ replace?: Record | ReplaceOptions
+}
+
+export interface DirectoryEntry {
+ srcDir: string
+ outDir: string
+ /** Script extension; declarations use the matching `.d.mts` or `.d.ts`. */
+ ext: typeof DIRECTORY_EXTENSIONS[number]
+}
+
+export type BuildHookName = 'build:before' | 'rollup:done' | 'build:done'
+
+export interface ModuleConfig {
+ /** Bundled entries keyed by output name, as paths relative to the module root. */
+ entries: Record
+ /** Directories built file by file, in the same way as `src/runtime`. */
+ directories: DirectoryEntry[]
+ neverBundle: RegExp[]
+ replace?: ReplaceOptions
+ /** Set when source maps are enabled in `build.config.ts`. */
+ sourcemap?: boolean
+ /** Runs the hooks of a `build.config.ts`. */
+ callHook?: (hook: BuildHookName, plan: BuildPlan) => Promise
+}
+
+type Report = (option: string) => void
+
+export interface OptionsCollector {
+ entries: (entries: unknown, report: Report) => void
+ externals: (externals: unknown, report: Report) => void
+ replaceValues: (values: unknown, path: string, report: Report) => void
+ replaceOptions: (options: Record, path: string, report: Report) => void
+ /** The collected options, with the module's own package name never bundled. */
+ finish: (pkg: PackageJson, options?: { replace?: boolean }) => ModuleConfig
+}
+
+/**
+ * Collects entries, externals and replacements from one or more option sources. Of two
+ * sources that set the same replacement or replace option, the first one wins. Options that
+ * cannot be applied are passed to `report`, by their path.
+ */
+export function createOptionsCollector(cwd: string, outDir: string): OptionsCollector {
+ const config: ModuleConfig = { entries: {}, directories: [], neverBundle: [] }
+ const replace: ReplaceOptions = { values: {} }
+ const runtime = { srcDir: resolve(cwd, 'src/runtime'), outDir: resolve(outDir, 'runtime') }
+
+ function entry(value: unknown, path: string, report: Report) {
+ const normalised = typeof value === 'string' ? { input: value } : value
+ if (!isPlainObject(normalised) || typeof normalised.input !== 'string' || !normalised.input) {
+ report(path)
+ return
+ }
+ const input = normalised.input
+ const builder = normalised.builder ?? (input.endsWith('/') ? 'mkdist' : 'rollup')
+ for (const [key, option] of Object.entries(normalised)) {
+ if (!ENTRY_KEYS.has(key) || (key === 'ext' && !(builder === 'mkdist' && DIRECTORY_EXTENSIONS.includes(option as DirectoryEntry['ext'])))) {
+ report(`${path}.${key}`)
+ }
+ }
+
+ const entryOutDir = typeof normalised.outDir === 'string' ? resolve(cwd, normalised.outDir) : outDir
+ if (builder === 'mkdist') {
+ const directory: DirectoryEntry = { srcDir: resolve(cwd, input), outDir: entryOutDir, ext: normalised.ext === 'js' ? 'js' : 'mjs' }
+ if (!isInside(outDir, directory.outDir)) {
+ report(`${path}.outDir`)
+ }
+ else if (directory.srcDir !== runtime.srcDir || directory.outDir !== runtime.outDir) {
+ config.directories.push(directory)
+ }
+ return
+ }
+ if (builder !== 'rollup') {
+ report(`${path}.builder: '${String(builder)}'`)
+ return
+ }
+ if (entryOutDir !== outDir) {
+ report(`${path}.outDir`)
+ return
+ }
+
+ const name = typeof normalised.name === 'string' ? normalised.name : entryName(input, cwd)
+ if (name.toLowerCase() === 'types') {
+ throw new Error(`A bundled entry is named \`types\`, whose declarations would replace the generated \`types.d.mts\`. Give \`${input}\` another \`name\`.`)
+ }
+ config.entries[name] = entryPath(cwd, input)
+ }
+
+ function replaceValues(values: unknown, path: string, report: Report) {
+ if (!isPlainObject(values)) {
+ report(path)
+ return
+ }
+ for (const [search, replacement] of Object.entries(values)) {
+ if (typeof replacement !== 'string') {
+ report(`${path}['${search}']`)
+ }
+ else if (!Object.hasOwn(replace.values, search)) {
+ replace.values[search] = replacement
+ }
+ }
+ }
+
+ return {
+ entries(entries, report) {
+ for (const [index, value] of (Array.isArray(entries) ? entries : [entries]).entries()) {
+ entry(value, `entries[${index}]`, report)
+ }
+ },
+ externals(externals, report) {
+ for (const [index, external] of (Array.isArray(externals) ? externals : [externals]).entries()) {
+ if (typeof external === 'string') {
+ config.neverBundle.push(new RegExp(`^${escapeRegExp(external)}(?:/|$)`))
+ }
+ else if (external instanceof RegExp) {
+ config.neverBundle.push(external)
+ }
+ else {
+ report(`externals[${index}]`)
+ }
+ }
+ },
+ replaceValues,
+ replaceOptions(options, path, report) {
+ for (const [key, value] of Object.entries(options)) {
+ if (key === 'values') {
+ replaceValues(value, `${path}.values`, report)
+ }
+ else if (key === 'delimiters' && Array.isArray(value) && value.length === 2 && value.every(delimiter => typeof delimiter === 'string')) {
+ replace.delimiters ??= value as [string, string]
+ }
+ else if (key === 'preventAssignment' || key === 'objectGuards') {
+ replace[key] ??= value === true
+ }
+ else {
+ report(`${path}.${key}`)
+ }
+ }
+ },
+ finish(pkg, { replace: replaces = true } = {}) {
+ if (replaces && Object.keys(replace.values).length) {
+ config.replace = { ...replace, preventAssignment: replace.preventAssignment ?? true }
+ }
+ if (pkg.name) {
+ config.neverBundle.push(new RegExp(`^${escapeRegExp(pkg.name)}(?:$|/(?!runtime/))`))
+ }
+ return config
+ },
+ }
+}
+
+/** Resolves the options of `builder()` into bundled entries, transpiled directories and replacements. */
+export function resolveModuleOptions(cwd: string, pkg: PackageJson, outDir: string, options: BuilderOptions): ModuleConfig {
+ assertNoLegacyBuildConfig(cwd, pkg)
+ if ('hooks' in options) {
+ throw new Error(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`)
+ }
+ const unsupported: string[] = []
+ const report = (option: string) => unsupported.push(option)
+ const collector = createOptionsCollector(cwd, outDir)
+ for (const [key, value] of Object.entries(options)) {
+ if (value === undefined) {
+ continue
+ }
+ if (key === 'entries') {
+ collector.entries(value, report)
+ }
+ else if (key === 'externals') {
+ collector.externals(value, report)
+ }
+ else if (key === 'replace' && isPlainObject(value) && isPlainObject(value.values)) {
+ collector.replaceOptions(value, 'replace', report)
+ }
+ else if (key === 'replace') {
+ collector.replaceValues(value, 'replace', report)
+ }
+ else {
+ report(key)
+ }
+ }
+ if (unsupported.length) {
+ throw new Error(['`builder()` does not support these options:', ...unsupported.map(option => ` - ${option}`), guide('tsdown-config')].join('\n'))
+ }
+ return collector.finish(pkg)
+}
+
+/** The output name of an entry without an explicit `name`. */
+export function entryName(input: string, cwd: string): string {
+ return (isAbsolute(input) ? relative(cwd, input) : normalize(input)).replace(/^\.\//, '').replace(/^src\//, '').replace(/\.(?:js|mjs|cjs|ts|mts|cts|json|jsx|tsx)$/, '')
+}
+
+/** `src/module` plus the extra bundled entries, keyed by output name. */
+export function bundledEntries(cwd: string, config: ModuleConfig): { module: string, [name: string]: string } {
+ return { ...config.entries, module: entryPath(cwd, 'src/module') }
+}
+
+function entryPath(cwd: string, input: string) {
+ return `./${relative(cwd, probe(resolve(cwd, input)) ?? resolve(cwd, `${input}.ts`))}`
+}
+
+/** Resolves `outDir` against `cwd`, refusing a directory outside the module, which the build would empty. */
+export function resolveOutDir(cwd: string, outDir: string, label: string = `--outDir ${outDir}`): string {
+ const resolved = resolve(cwd, outDir)
+ const root = realpath(cwd)
+ const real = realpath(resolved)
+ if (real === root || !isInside(root, real)) {
+ throw new Error(`\`${label}\` resolves to \`${real}\`, which is not inside the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`)
+ }
+ return resolved
+}
diff --git a/src/build/package.ts b/src/build/package.ts
index 0ae1469e..3450730c 100644
--- a/src/build/package.ts
+++ b/src/build/package.ts
@@ -1,14 +1,19 @@
-import { basename, relative, resolve } from 'pathe'
+import { existsSync } from 'node:fs'
+import { basename, join, relative, resolve } from 'pathe'
+import { consola } from 'consola'
+import { readPackageJSON } from 'pkg-types'
import type { PackageJson } from 'pkg-types'
+import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts'
+import { DECLARATION_RE, isFile, isInside, TYPESCRIPT_RE } from '../utils.ts'
import { guide } from './guide.ts'
-const PUBLISH_CONFIG_FIELDS = ['bin', 'browser', 'exports', 'imports', 'main', 'module', 'types', 'typings', 'typesVersions'] as const
-
/** The fields of `package.json` whose paths are checked for whether they can be published. */
const PATH_FIELDS = ['exports', 'imports', 'main', 'module', 'types', 'typings', 'typesVersions'] as const
type PathField = typeof PATH_FIELDS[number]
+const PUBLISH_CONFIG_FIELDS: readonly string[] = ['bin', 'browser', ...PATH_FIELDS]
+
/** The path fields that each major version of Yarn replaces from `publishConfig` when it packs. */
const YARN_PUBLISH_CONFIG_FIELDS: Record = {
2: ['main', 'module'],
@@ -18,9 +23,7 @@ const YARN_PUBLISH_CONFIG_FIELDS: Record = {
const PACK_EVENTS = new Set(['prepack', 'prepublishOnly'])
-const TS_SOURCE_RE = /\.[cm]?tsx?$/
const UNPUBLISHABLE = 'TypeScript sources or paths that `files` leaves out'
-const DECLARATION_RE = /\.d\.[cm]?ts$/
/** `pkg` as pnpm publishes it, with the paths in `publishConfig` replacing their top-level fields. */
export function publishedPackage(pkg: PackageJson): PackageJson {
@@ -47,22 +50,23 @@ export interface UnpublishablePath {
* out because `files` does not list them. Without `files`, paths into `.nuxt` count as left out.
* Every pack includes `package.json` and the file that `main` points at.
*/
-export function unpublishablePaths(cwd: string, pkg: PackageJson, files: string[] | undefined = pkg.files): UnpublishablePath[] {
+export function unpublishablePaths(cwd: string, pkg: PackageJson): UnpublishablePath[] {
const alwaysPacked = new Set(['package.json', ...typeof pkg.main === 'string' ? [relative(cwd, resolve(cwd, pkg.main))] : []])
const targets = (field: PathField): Array<{ path: string, key?: string }> => field === 'imports'
? Object.entries((pkg.imports ?? {}) as Record).flatMap(([key, value]) => collectStrings(value).filter(path => path.startsWith('./')).map(path => ({ path, key })))
: collectStrings(pkg[field]).map(path => ({ path }))
return PATH_FIELDS.flatMap(field => targets(field).flatMap(({ path, key }): UnpublishablePath[] => {
- if (TS_SOURCE_RE.test(path) && !DECLARATION_RE.test(path)) {
+ if (TYPESCRIPT_RE.test(path) && !DECLARATION_RE.test(path)) {
return [{ field, path, reason: 'source', key }]
}
- return !packed(cwd, path, files, alwaysPacked) ? [{ field, path, reason: 'files', key }] : []
+ return !packed(cwd, path, pkg.files, alwaysPacked) ? [{ field, path, reason: 'files', key }] : []
}))
}
function packed(cwd: string, path: string, files: string[] | undefined, alwaysPacked: Set): boolean {
- const file = relative(cwd, resolve(cwd, path.split('*')[0]!))
- if (!file || file.startsWith('..')) {
+ const target = resolve(cwd, path.split('*')[0]!)
+ const file = relative(cwd, target)
+ if (!file || !isInside(cwd, target)) {
return !file
}
if (!path.includes('*') && alwaysPacked.has(file)) {
@@ -154,19 +158,18 @@ export function sourcePathsPackError(cwd: string, pkg: PackageJson, env: Record<
if (!PACK_EVENTS.has(env.npm_lifecycle_event ?? '')) {
return
}
- const paths = unpublishablePaths(cwd, pkg)
const client = packingClient(env)
+ const applied = client?.fields ?? []
const publishConfig = (pkg.publishConfig ?? {}) as Record
- const published = paths.filter(({ field }) => !client?.fields.includes(field) || publishConfig[field] === undefined)
+ const replaced = PATH_FIELDS.filter(field => applied.includes(field) && publishConfig[field] !== undefined)
+ const published = unpublishablePaths(cwd, pkg).filter(({ field }) => !replaced.includes(field))
if (!published.length) {
- const replaced = PATH_FIELDS.filter(field => client?.fields.includes(field) && publishConfig[field] !== undefined)
const replacements = unpublishablePaths(cwd, { ...pkg, ...Object.fromEntries(replaced.map(field => [field, publishConfig[field]])) }).filter(({ field }) => replaced.includes(field))
- if (!replacements.length) {
- return
- }
- return `These fields of \`publishConfig\` point at ${UNPUBLISHABLE}, so they would be published that way: ${list(replacements.map(({ field }) => field))} (${list(replacements.map(({ path }) => path))}). Point them at \`dist\`. ${guide('publishing-source-exports')}`
+ return replacements.length
+ ? `These fields of \`publishConfig\` point at ${UNPUBLISHABLE}, so they would be published that way: ${list(replacements.map(({ field }) => field))} (${list(replacements.map(({ path }) => path))}). Point them at \`dist\`. ${guide('publishing-source-exports')}`
+ : undefined
}
- const unsupported = [...new Set(published.filter(({ field }) => !client?.fields.includes(field)).map(({ field }) => field))]
+ const unsupported = [...new Set(published.filter(({ field }) => !applied.includes(field)).map(({ field }) => field))]
const pathList = list(published.filter(({ field }) => !unsupported.length || unsupported.includes(field)).map(({ path }) => path))
if (unsupported.length) {
const name = client ? `\`${client.name}${client.version ? `@${client.version}` : ''}\`` : 'This package manager'
@@ -204,11 +207,11 @@ function publishConfigFields(name: string, version: string | undefined): readonl
return []
}
-function list(values: string[]) {
+export function list(values: string[]): string {
return [...new Set(values)].map(value => `\`${value}\``).join(', ')
}
-export function collectStrings(value: unknown): string[] {
+function collectStrings(value: unknown): string[] {
if (typeof value === 'string') {
return [value]
}
@@ -220,3 +223,116 @@ export function collectStrings(value: unknown): string[] {
}
return []
}
+
+/**
+ * `paths` pointing the package's own name and `exports` subpaths at its sources, so
+ * self-referencing imports type-check before `dist` exists. A subpath that points at a
+ * bundled entry of `entries`, keyed by output name, maps to that entry's input.
+ */
+export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string, entries: Record = {}): Record {
+ if (!pkg.name) {
+ return {}
+ }
+ const paths: Record = { [pkg.name]: [resolve(cwd, 'src/module')] }
+ const { exports } = publishedPackage(pkg)
+ if (!exports || typeof exports !== 'object' || Array.isArray(exports)) {
+ return paths
+ }
+ for (const [subpath, target] of Object.entries(exports)) {
+ const file = exportTarget(target)
+ if (!subpath.startsWith('./') || !file) {
+ continue
+ }
+ if (isInside(outDir, resolve(cwd, file))) {
+ const name = relative(outDir, resolve(cwd, file)).replace(/(?:\.d)?\.[cm]?[jt]s$/, '')
+ const input = Object.hasOwn(entries, name) ? entries[name]!.replace(/\.[cm]?[jt]sx?$/, '') : join('src', name)
+ paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, input)]
+ }
+ }
+ return paths
+}
+
+function exportTarget(target: unknown): string | undefined {
+ if (typeof target === 'string') {
+ return target
+ }
+ if (target && typeof target === 'object' && !Array.isArray(target)) {
+ const conditions = target as Record
+ return exportTarget(conditions.import ?? conditions.default ?? conditions.types)
+ }
+}
+
+/**
+ * Warn about `package.json` fields that point at output this builder no longer produces.
+ * The paths are read as published, with `publishConfig` applied.
+ */
+export async function checkPublishedPaths(cwd: string): Promise {
+ const read = await readPackageJSON(cwd).catch(() => undefined)
+ if (!read) {
+ return
+ }
+ const pkg = publishedPackage(read)
+ checkLegacyDeclarationPaths(cwd, pkg)
+ checkLegacyCJSPaths(cwd, pkg)
+ checkStaleTypesField(cwd, pkg)
+ checkNode10DeclarationPaths(cwd, pkg)
+ checkMissingPaths(cwd, pkg)
+}
+
+/** Warns with `message` when `condition` holds, and returns `condition`. */
+export function warnWhen(condition: boolean, message: string): boolean {
+ if (condition) {
+ consola.warn(message)
+ }
+ return condition
+}
+
+export function checkStaleTypesField(cwd: string, pkg: PackageJson): boolean {
+ return warnWhen(!!pkg.types && !resolvesForTypeScript(cwd, pkg.types), `\`types\` in \`package.json\` points at \`${pkg.types}\`, which the build does not produce. Set it to \`./dist/types.d.mts\`, which node10 module resolution reads, or remove it: bundler module resolution reads \`exports\` instead. ${guide('the-types-field')}`)
+}
+
+/**
+ * Warn about `typesVersions` paths that TypeScript's node10 resolution cannot find because
+ * they rely on probing for `.d.ts`, where the build now produces `.d.mts`.
+ */
+export function checkNode10DeclarationPaths(cwd: string, pkg: PackageJson): boolean {
+ const entries = typesVersionsPaths(pkg).flatMap((path) => {
+ const replacement = node10Replacement(cwd, path)
+ return replacement ? [`\`${path}\` (use \`${replacement}\`)`] : []
+ })
+ return warnWhen(entries.length > 0, `These \`typesVersions\` paths in \`package.json\` do not resolve under TypeScript's node10 module resolution, which probes for \`.d.ts\` but not for \`.d.mts\`: ${entries.join(', ')}. Write each path with its extension. ${guide('typesversions-paths')}`)
+}
+
+/** Warn about paths in `package.json` that the build did not produce, other than those the checks above explain. */
+export function checkMissingPaths(cwd: string, pkg: PackageJson): boolean {
+ const paths = [...new Set(missingPaths(cwd, pkg))]
+ .filter(path => !path.includes('*') && !isLegacyPath(path) && path !== pkg.types && !node10Replacement(cwd, path))
+ return warnWhen(paths.length > 0, `These paths in \`package.json\` do not exist after the build, so imports that resolve to them will fail: ${list(paths)}. Add the entry that produces each one, or remove the path. ${guide('paths-the-build-does-not-produce')}`)
+}
+
+const TS_PROBES = ['', '.ts', '.tsx', '.d.ts', '/index.ts', '/index.tsx', '/index.d.ts']
+const TS_MODULE_PROBES = ['.d.mts', '.d.cts', '/index.d.mts', '/index.d.cts']
+
+/** Whether TypeScript's node10 resolution finds a file for `path`: as written, or with a `.ts`, `.tsx`, `.d.ts` or `/index` suffix. */
+function resolvesForTypeScript(cwd: string, path: string) {
+ return TS_PROBES.some(suffix => isFile(resolve(cwd, path + suffix)))
+}
+
+/** The `.d.mts` or `.d.cts` file an unresolvable `path` was meant to reach, as a `./` path. */
+function node10Replacement(cwd: string, path: string) {
+ if (resolvesForTypeScript(cwd, path)) {
+ return
+ }
+ const suffix = TS_MODULE_PROBES.find(suffix => isFile(resolve(cwd, path + suffix)))
+ return suffix === undefined ? undefined : `./${relative(cwd, resolve(cwd, path + suffix))}`
+}
+
+function typesVersionsPaths(pkg: PackageJson) {
+ return collectStrings(pkg.typesVersions).filter(path => !path.includes('*'))
+}
+
+export function missingPaths(cwd: string, pkg: PackageJson): string[] {
+ const typesVersions = new Set(typesVersionsPaths(pkg))
+ const paths = [...[pkg.exports, pkg.typesVersions, pkg.types, pkg.main, pkg.module].flatMap(collectStrings), ...collectStrings(pkg.imports).filter(path => path.startsWith('./'))]
+ return paths.filter(path => !path.startsWith('/') && !(typesVersions.has(path) ? resolvesForTypeScript(cwd, path) : existsSync(resolve(cwd, path))))
+}
diff --git a/src/build/tsconfig.ts b/src/build/tsconfig.ts
deleted file mode 100644
index 0dcf4597..00000000
--- a/src/build/tsconfig.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { TsConfigResult } from 'get-tsconfig'
-import { relative, resolve } from 'pathe'
-import type { PackageJson } from 'pkg-types'
-
-import { publishedPackage } from './package.ts'
-
-/**
- * `paths` pointing the package's own name and `exports` subpaths at its sources, so
- * self-referencing imports type-check before `dist` exists.
- */
-export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string): Record {
- if (!pkg.name) {
- return {}
- }
- const paths: Record = { [pkg.name]: [resolve(cwd, 'src/module')] }
- const { exports } = publishedPackage(pkg)
- if (!exports || typeof exports !== 'object' || Array.isArray(exports)) {
- return paths
- }
- for (const [subpath, target] of Object.entries(exports)) {
- const file = exportTarget(target)
- if (!subpath.startsWith('./') || !file) {
- continue
- }
- const distPath = relative(outDir, resolve(cwd, file))
- if (!distPath.startsWith('..')) {
- paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, 'src', distPath.replace(/(?:\.d)?\.[cm]?[jt]s$/, ''))]
- }
- }
- return paths
-}
-
-function exportTarget(target: unknown): string | undefined {
- if (typeof target === 'string') {
- return target
- }
- if (target && typeof target === 'object' && !Array.isArray(target)) {
- const conditions = target as Record
- return exportTarget(conditions.import ?? conditions.default ?? conditions.types)
- }
-}
-
-export function hasIsolatedDeclarations(tsconfig: TsConfigResult | undefined): boolean {
- return tsconfig?.config.compilerOptions?.isolatedDeclarations === true
-}
diff --git a/src/build/types.ts b/src/build/types.ts
index 74a12ecc..72f7a03e 100644
--- a/src/build/types.ts
+++ b/src/build/types.ts
@@ -3,8 +3,7 @@ import { dirname, relative, resolve } from 'pathe'
import { findExports, findTypeExports } from 'mlly'
import type { ESMExport } from 'mlly'
-import { probe } from './loader.ts'
-import { writeIfChanged } from './write.ts'
+import { getOrCreate, probe, writeIfChanged } from '../utils.ts'
const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type'])
const DECLARATION_SUFFIXES: Record = {
@@ -44,53 +43,24 @@ export async function writeTypes(distDir: string, source?: { exports: Set()
+ let typeOnlyExports = new Set()
if (!source) {
- // Read generated module types
- const moduleTypesFile = resolve(distDir, 'module.d.mts')
- const moduleTypes = await fsp.readFile(moduleTypesFile, 'utf8').catch(() => '')
+ const moduleTypes = await fsp.readFile(resolve(distDir, 'module.d.mts'), 'utf8').catch(() => '')
const exports = findExports(withoutTypeModifiers(moduleTypes))
const typeExports = findTypeExports(moduleTypes)
moduleReExports.push(...exports, ...typeExports)
-
- const valueExports = new Set()
- for (const e of findExports(moduleTypes)) {
- if (e.type === 'named' || e.type === 'default') {
- for (const name of e.names) {
- valueExports.add(name)
- }
- }
- }
- for (const e of typeExports) {
- const isTypeOnly = e.type === 'named' || (e.type === 'declaration' && e.declarationType !== undefined && TYPE_ONLY_DECLARATIONS.has(e.declarationType))
- const target = isTypeOnly ? typeOnlyExports : valueExports
- for (const name of e.names) {
- target.add(name)
- }
- }
-
- // `findTypeExports` drops a value declaration that shares its name with a type
- // export, so read those names from the generated declarations too.
- for (const match of moduleTypes.matchAll(VALUE_DECLARATION_RE)) {
- valueExports.add(match[1]!)
- }
-
+ const namedExports = (list: ESMExport[]) => list.filter(e => e.type === 'named' || e.type === 'default').flatMap(e => e.names)
+ const isTypeOnly = (e: ESMExport) => e.type === 'named' || (e.type === 'declaration' && TYPE_ONLY_DECLARATIONS.has(e.declarationType!))
+ const valueExports = new Set([
+ ...namedExports(findExports(moduleTypes)),
+ ...typeExports.filter(e => !isTypeOnly(e)).flatMap(e => e.names),
+ // `findTypeExports` drops a value declaration that shares its name with a type
+ // export, so read those names from the generated declarations too.
+ ...[...moduleTypes.matchAll(VALUE_DECLARATION_RE)].map(match => match[1]!),
+ ])
// `findExports` only reports `export { type Foo }` after the `type` keyword is removed,
// so names it finds only in the normalised types are type-only.
- for (const e of exports) {
- if (e.type !== 'named' && e.type !== 'default') {
- continue
- }
- for (const name of e.names) {
- if (!valueExports.has(name)) {
- typeOnlyExports.add(name)
- }
- }
- }
-
- for (const name of valueExports) {
- typeOnlyExports.delete(name)
- }
+ typeOnlyExports = new Set([...typeExports.filter(isTypeOnly).flatMap(e => e.names), ...namedExports(exports)].filter(name => !valueExports.has(name)))
}
const appShims: string[] = []
@@ -109,23 +79,16 @@ export async function writeTypes(distDir: string, source?: { exports: Set ? Partial : Record`)
}
- if (hasTypeExport('ModuleHooks')) {
- moduleImports.push('ModuleHooks')
- schemaShims.push(' interface NuxtHooks extends ModuleHooks {}')
- }
-
- if (hasTypeExport('ModuleRuntimeHooks')) {
- moduleImports.push('ModuleRuntimeHooks')
- appShims.push(` interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}`)
- }
-
- if (hasTypeExport('ModuleRuntimeConfig')) {
- moduleImports.push('ModuleRuntimeConfig')
- schemaShims.push(' interface RuntimeConfig extends ModuleRuntimeConfig {}')
- }
- if (hasTypeExport('ModulePublicRuntimeConfig')) {
- moduleImports.push('ModulePublicRuntimeConfig')
- schemaShims.push(' interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}')
+ for (const [name, shims, augmented] of [
+ ['ModuleHooks', schemaShims, 'NuxtHooks'],
+ ['ModuleRuntimeHooks', appShims, 'RuntimeNuxtHooks'],
+ ['ModuleRuntimeConfig', schemaShims, 'RuntimeConfig'],
+ ['ModulePublicRuntimeConfig', schemaShims, 'PublicRuntimeConfig'],
+ ] as const) {
+ if (hasTypeExport(name)) {
+ moduleImports.push(name)
+ shims.push(` interface ${augmented} extends ${name} {}`)
+ }
}
const dtsContents = `
@@ -185,15 +148,10 @@ function withoutTypeModifiers(code: string) {
function groupNamedReExports(exports: ESMExport[]) {
const groups = new Map>()
for (const e of exports) {
- if (e.type !== 'named' && e.type !== 'default' && e.type !== 'declaration') {
- continue
- }
- const specifier = e.specifier || './module.mjs'
- const names = groups.get(specifier) ?? new Set()
- for (const name of e.names) {
- names.add(name)
+ if (e.type === 'named' || e.type === 'default' || e.type === 'declaration') {
+ const names = getOrCreate(groups, e.specifier || './module.mjs', () => new Set())
+ e.names.forEach(name => names.add(name))
}
- groups.set(specifier, names)
}
return new Map([...groups].map(([specifier, names]) => [
specifier,
diff --git a/src/build/write.ts b/src/build/write.ts
deleted file mode 100644
index d4f5cae0..00000000
--- a/src/build/write.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { readFile, writeFile } from 'node:fs/promises'
-
-/** Writes `contents` to `file` unless it already holds them, so its modification time only changes with its content. */
-export async function writeIfChanged(file: string, contents: string): Promise {
- if (await readFile(file, 'utf8').catch(() => undefined) !== contents) {
- await writeFile(file, contents, 'utf8')
- }
-}
diff --git a/src/cli.ts b/src/cli.ts
index 0a7656c8..1de49893 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,7 +1,6 @@
#!/usr/bin/env node
import { defineCommand, runMain } from 'citty'
import type { CommandDef } from 'citty'
-import { consola } from 'consola'
import pkg from '../package.json' with { type: 'json' }
const { name, description, version } = pkg
@@ -18,14 +17,6 @@ const main = defineCommand({
prepare: () => import('./commands/prepare.ts').then(_rDefault),
build: () => import('./commands/build.ts').then(_rDefault),
},
- setup(context) {
- // TODO: support 'default command' in citty?
- const firstArg = context.rawArgs[0]
- if (context.cmd.subCommands && !(firstArg && firstArg in context.cmd.subCommands)) {
- consola.warn('Please specify the `build` command explicitly. In a future version of `@nuxt/module-builder`, the implicit default build command will be removed.')
- context.rawArgs.unshift('build')
- }
- },
})
runMain(main)
diff --git a/src/commands/_shared.ts b/src/commands/_shared.ts
index 49e65573..02b442be 100644
--- a/src/commands/_shared.ts
+++ b/src/commands/_shared.ts
@@ -1,8 +1,5 @@
-import { resolve } from 'pathe'
-
import { guide } from '../build/guide.ts'
-import { findTsdownConfig, loadBuilderConfig } from './config-file.ts'
-import type { BuilderConfig } from './config-file.ts'
+import { realpath } from '../utils.ts'
export const sharedArgs = {
// cwd falls back to rootDir's default (indirect default)
@@ -20,16 +17,10 @@ export const sharedArgs = {
},
} as const
-export const resolveCwdArg = (args: { cwd?: string, rootDir?: string }): string => resolve(args.cwd || args.rootDir || '.')
+export const resolveCwdArg = (args: { cwd?: string, rootDir?: string }): string => realpath(args.cwd || args.rootDir || '.')
export function assertNoStubArg(command: 'build' | 'prepare', args: Record): void {
if (args.stub) {
throw new Error(`\`nuxt-module-build ${command} --stub\` has been removed. With pnpm or Yarn 4, point \`package.json\` at the module's sources. Otherwise, build \`dist\` with \`tsdown\` and rebuild it with \`tsdown --watch\`. ${guide('stub-builds')}`)
}
}
-
-/** The `builder()` options of the module's tsdown config, when it has one. */
-export async function loadModuleConfig(cwd: string): Promise {
- const file = findTsdownConfig(cwd)
- return file ? loadBuilderConfig(cwd, file) : undefined
-}
diff --git a/src/commands/config-file.ts b/src/commands/config-file.ts
index 690c3926..99142ebe 100644
--- a/src/commands/config-file.ts
+++ b/src/commands/config-file.ts
@@ -2,8 +2,8 @@ import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { basename, dirname, resolve } from 'pathe'
-import { BUILDER_OPTIONS } from '../build/build-config.ts'
-import type { BuilderOptions } from '../build/build-config.ts'
+import { BUILDER_OPTIONS } from '../build/options.ts'
+import type { BuilderOptions } from '../build/options.ts'
import { guide } from '../build/guide.ts'
import { assertLoadableModuleCode, importModule } from '../build/loader.ts'
@@ -40,7 +40,7 @@ export interface BuilderConfig {
* Finds the options of the `builder()` plugin in a tsdown config file, which may export
* a config, an array of configs, or a function returning either.
*/
-export async function loadBuilderConfig(cwd: string, file: string): Promise {
+async function loadBuilderConfig(cwd: string, file: string): Promise {
if (!file.endsWith('.json')) {
assertLoadableModuleCode(cwd, [file], [])
}
@@ -72,6 +72,12 @@ export async function loadBuilderConfig(cwd: string, file: string): Promise {
+ const file = findTsdownConfig(cwd)
+ return file ? loadBuilderConfig(cwd, file) : undefined
+}
+
/** Whether `plugins`, in any of the shapes a tsdown config accepts, contain `builder()`. */
export async function hasBuilder(plugins: unknown): Promise {
return (await flattenPlugins(plugins)).some(plugin => !!plugin && typeof plugin === 'object' && BUILDER_OPTIONS in plugin)
diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts
index 4ec2038d..73399023 100644
--- a/src/commands/prepare.ts
+++ b/src/commands/prepare.ts
@@ -4,32 +4,38 @@ import { defineCommand } from 'citty'
import type { CommandDef } from 'citty'
import { readFile, writeFile } from 'node:fs/promises'
import { parseTsconfig } from 'get-tsconfig'
-import { resolvePathSync } from 'mlly'
+import { resolvePath } from 'mlly'
import { dirname, join, relative, resolve } from 'pathe'
import { readPackageJSON } from 'pkg-types'
+import type { PackageJson } from 'pkg-types'
import { glob } from 'tinyglobby'
-import { assertNoLegacyBuildConfig, bundledEntries, loadBuildConfig, resolveModuleOptions } from '../build/build-config.ts'
-import type { TranslatedBuildConfig } from '../build/build-config.ts'
import { assertLoadableModuleCode, importModule } from '../build/loader.ts'
import { moduleDeclarationPaths, writeModuleDeclarations } from '../build/module-declarations.ts'
-import { selfReferencePaths } from '../build/tsconfig.ts'
+import { bundledEntries, resolveModuleOptions } from '../build/options.ts'
+import type { ModuleConfig } from '../build/options.ts'
+import { selfReferencePaths } from '../build/package.ts'
import { writeSourceTypes } from '../build/types.ts'
-import { probe } from '../rolldown/resolve.ts'
-import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../rolldown/tsconfig.ts'
-import { assertNoStubArg, loadModuleConfig, resolveCwdArg, sharedArgs } from './_shared.ts'
+import { loadBuildConfig } from '../legacy/build-config.ts'
+import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts'
+import { isInside, probe } from '../utils.ts'
+import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts'
+import { loadModuleConfig } from './config-file.ts'
const BUILD_DECLARATION_RE = /^declare module "#build\/(.+)";$/
const PATH_OPTIONS = new Set(['paths', 'baseUrl', 'rootDir', 'rootDirs', 'outDir', 'outFile', 'declarationDir', 'typeRoots', 'tsBuildInfoFile'])
-async function loadPrepareConfig(cwd: string): Promise<{ config: TranslatedBuildConfig, outDir: string }> {
+interface PrepareConfig {
+ config: ModuleConfig
+ outDir: string
+ pkg: PackageJson
+}
+
+async function loadPrepareConfig(cwd: string): Promise {
const pkg = await readPackageJSON(cwd)
const moduleConfig = await loadModuleConfig(cwd)
const outDir = resolve(cwd, moduleConfig?.outDir ?? 'dist')
- if (!moduleConfig) {
- return { config: await loadBuildConfig(cwd, pkg, outDir), outDir }
- }
- assertNoLegacyBuildConfig(cwd, pkg)
- return { config: resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options), outDir }
+ const config = moduleConfig ? resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options) : await loadBuildConfig(cwd, pkg, outDir)
+ return { config, outDir, pkg }
}
/**
@@ -58,23 +64,23 @@ async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude:
return { globals, augmentations }
}
-export async function prepareModule(cwd: string, buildConfig?: { config: TranslatedBuildConfig, outDir: string }): Promise<{ result: unknown }> {
+export async function prepareModule(cwd: string, prepareConfig?: PrepareConfig): Promise<{ result: unknown }> {
const { runCommand } = await import('@nuxt/cli')
- const { config, outDir } = buildConfig ?? await loadPrepareConfig(cwd)
+ const { config, outDir, pkg } = prepareConfig ?? await loadPrepareConfig(cwd)
const runtimeDirs = [resolve(cwd, 'src/runtime'), ...config.directories.map(directory => directory.srcDir)]
const entries = bundledEntries(cwd, config)
assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries))
- const moduleExports = await importModule(resolve(cwd, entries.module), { cwd })
+ const entryPath = resolve(cwd, entries.module)
+ const moduleExports = await importModule(entryPath, { cwd })
const nuxtModule = (moduleExports.default ?? moduleExports) as NuxtModule
- const pkg = await readPackageJSON(cwd)
const { name } = pkg
const useNuxt = name ? await loadUseNuxt(cwd) : undefined
- const entryPath = resolve(cwd, entries.module)
const rootConfig = await rootTsconfig(cwd)
const ambient = await ambientDeclarations(cwd, runtimeDirs, [...rootConfig.exclude ?? [], outDir])
- const selfPaths = selfReferencePaths(cwd, pkg, outDir)
- const declarationsDir = join(sourceTypesDir(cwd), 'declarations')
+ const selfPaths = selfReferencePaths(cwd, pkg, outDir, entries)
+ const sourceTypesDir = resolve(cwd, '.nuxt/module-builder')
+ const declarationsDir = join(sourceTypesDir, 'declarations')
const ownTypes = join(declarationsDir, 'types.d.mts')
const ownPaths = name ? moduleDeclarationPaths(cwd, declarationsDir, name, selfPaths, runtimeDirs) : {}
let perContext = false
@@ -180,11 +186,11 @@ export async function prepareModule(cwd: string, buildConfig?: { config: Transla
list.push(...ambient.augmentations.map(path => ({ path })))
}
// Module code can import types from runtime sources, which rely on the app's aliases, declarations and JSX options.
- const appDeclarations = (tsConfig.include ?? []).filter(pattern => !relative(nuxt.options.buildDir, resolve(nuxt.options.buildDir, pattern)).startsWith('..'))
+ const appDeclarations = (tsConfig.include ?? []).filter(pattern => isInside(nuxt.options.buildDir, resolve(nuxt.options.buildDir, pattern)))
nodeTsConfig.include = [...new Set([...nodeTsConfig.include ?? [], ...appDeclarations])]
// A type reference does not resolve the module's own package name.
const ownReference = nodeReferences.findIndex(isOwnTypes)
- nodeReferences.splice(ownReference === -1 ? nodeReferences.length : ownReference, ownReference === -1 ? 0 : 1, { path: join(sourceTypesDir(cwd), 'types.d.mts') })
+ nodeReferences.splice(ownReference === -1 ? nodeReferences.length : ownReference, ownReference === -1 ? 0 : 1, { path: join(sourceTypesDir, 'types.d.mts') })
const { jsx, jsxImportSource } = tsConfig.compilerOptions ?? {}
nodeTsConfig.compilerOptions = { jsx, jsxImportSource, ...nodeTsConfig.compilerOptions }
nodeTsConfig.compilerOptions.paths = { ...tsConfig.compilerOptions?.paths, ...nodeTsConfig.compilerOptions.paths }
@@ -206,10 +212,10 @@ export async function prepareModule(cwd: string, buildConfig?: { config: Transla
],
} satisfies NuxtConfig,
})
- await writeSourceTypes(sourceTypesDir(cwd), entryPath)
+ await writeSourceTypes(sourceTypesDir, entryPath)
await writeCompatibilityTsconfig(resolve(cwd, '.nuxt/tsconfig.json'), cwd, { ownPaths, ownTypes, entryPath, ambient: ambient.globals })
if (name && perContext) {
- const roots = Object.values(entries).flatMap(input => probe(resolve(cwd, input)) ?? []).filter(file => !runtimeDirs.some(dir => !relative(dir, file).startsWith('..')))
+ const roots = Object.values(entries).flatMap(input => probe(resolve(cwd, input)) ?? []).filter(file => !runtimeDirs.some(dir => isInside(dir, file)))
const tsconfigs = await createTsconfigResolver(cwd)
const project = tsconfigs.resolve(entryPath)
const nodeTsconfig = resolve(cwd, '.nuxt/tsconfig.node.json')
@@ -219,8 +225,6 @@ export async function prepareModule(cwd: string, buildConfig?: { config: Transla
return result
}
-const sourceTypesDir = (cwd: string) => resolve(cwd, '.nuxt/module-builder')
-
interface CompatibilityOptions {
ownPaths: Record
ownTypes: string
@@ -244,7 +248,7 @@ async function writeCompatibilityTsconfig(file: string, cwd: string, { ownPaths,
const entryDir = dirname(entryPath)
const isDerived = (pattern: string) => {
const path = resolve(dirname(file), pattern)
- const inEntryDist = entryDir !== cwd && !relative(join(entryDir, 'dist'), path).startsWith('..')
+ const inEntryDist = entryDir !== cwd && isInside(join(entryDir, 'dist'), path)
return path === ownTypes || path === join(entryDir, 'runtime/server') || inEntryDist
}
config.include = config.include?.filter(pattern => !isDerived(pattern))
@@ -277,22 +281,13 @@ function replaceEntries(modules: unknown[] | undefined, name: string, nuxtModule
/** `useNuxt` from the kit the module in `cwd` resolves, so hooks can read the Nuxt instance they run in. */
async function loadUseNuxt(cwd: string): Promise<(() => Nuxt) | undefined> {
for (const id of ['@nuxt/kit', 'nuxt/kit']) {
- const path = tryResolvePath(id, cwd)
+ const path = await resolvePath(id, { url: pathToFileURL(`${cwd}/`) }).catch(() => undefined)
if (path) {
return (await import(pathToFileURL(path).href) as { useNuxt: () => Nuxt }).useNuxt
}
}
}
-function tryResolvePath(id: string, cwd: string) {
- try {
- return resolvePathSync(id, { url: pathToFileURL(`${cwd}/`) })
- }
- catch {
- return undefined
- }
-}
-
const command: CommandDef = defineCommand({
meta: {
name: 'prepare',
diff --git a/src/index.ts b/src/index.ts
index 91cfbabb..03ce9123 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,4 @@
export { default as build } from './commands/build.ts'
export { default as prepare } from './commands/prepare.ts'
-export { defineBuildConfig } from './build/define.ts'
-export type { BuildConfig, BuildContext, BuildEntry, BuildHook } from './build/define.ts'
+export { defineBuildConfig } from './legacy/define.ts'
+export type { BuildConfig, BuildContext, BuildEntry, BuildHook } from './legacy/define.ts'
diff --git a/src/legacy/build-config.ts b/src/legacy/build-config.ts
new file mode 100644
index 00000000..44253de4
--- /dev/null
+++ b/src/legacy/build-config.ts
@@ -0,0 +1,311 @@
+/**
+ * Reads a v1 module's `build.config.*` and the `unbuild` or `build` field of `package.json`,
+ * translates them into the build's options, and runs their unbuild hooks.
+ */
+import { existsSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import { relative, resolve } from 'pathe'
+import { consola } from 'consola'
+import type { PackageJson } from 'pkg-types'
+
+import type { BuildPlan } from '../build/build.ts'
+import { guide } from '../build/guide.ts'
+import type { GuideSection } from '../build/guide.ts'
+import { findModuleCodeIssues, formatModuleCodeIssues, importModule } from '../build/loader.ts'
+import { bundledEntries, createOptionsCollector, entryName } from '../build/options.ts'
+import type { BuildHookName, ModuleConfig } from '../build/options.ts'
+import { isPlainObject } from '../utils.ts'
+import type { BuildContext, BuildHook } from './define.ts'
+
+const BUILD_CONFIG_FILES = ['build.config.ts', 'build.config.mts', 'build.config.js', 'build.config.mjs']
+
+const DEFINE_BUILD_CONFIG_STUB = [
+ 'export const defineBuildConfig = config => config',
+ 'export const definePreset = preset => preset',
+].join('\n')
+
+const ACCEPTED_KEYS = new Set(['failOnWarn', 'name', 'parallel'])
+const SUPPORTED_HOOKS: readonly string[] = ['build:before', 'rollup:done', 'build:done'] satisfies BuildHookName[]
+const UNBUILD_IMPORT_RE = /\bfrom\s*['"]unbuild['"]/
+
+export interface BuildConfigSource {
+ /** Where the config came from, used in diagnostics. */
+ name: string
+ config: unknown
+}
+
+export interface TranslatedBuildConfig extends ModuleConfig {
+ hooks: Record
+ /** Hooks that are skipped because there is nothing for them to act on, as `: `. */
+ ignoredHooks: string[]
+ /** Options without an equivalent, as `: `. */
+ unsupported: string[]
+}
+
+export interface LoadedBuildConfig extends TranslatedBuildConfig {
+ /** The `build.config.*` file that was read, if any. */
+ file?: string
+ /** Whether that file still imports from `unbuild`. */
+ importsUnbuild?: boolean
+ /** The `package.json` field that was read, if any. */
+ field?: 'unbuild' | 'build'
+}
+
+/**
+ * Translate unbuild configs into the equivalent build options. Sources are given in
+ * unbuild's precedence order: `build.config.*` first, then `package.json`'s `unbuild` or
+ * `build`.
+ */
+export function translateBuildConfig(sources: BuildConfigSource[], options: { cwd: string, outDir: string, pkg?: PackageJson }): TranslatedBuildConfig {
+ const cwd = resolve(options.cwd)
+ const outDir = resolve(options.outDir)
+ const collector = createOptionsCollector(cwd, outDir)
+ const hooks: TranslatedBuildConfig['hooks'] = { 'build:before': [], 'rollup:done': [], 'build:done': [] }
+ const ignoredHooks: string[] = []
+ const rejected: string[] = []
+ let sourcemap = false
+ let declaration: unknown
+ let replaceDisabled = false
+
+ for (const { name: source, config } of sources) {
+ const unsupported = (option: string) => rejected.push(`${source}: ${option}`)
+
+ if (!isPlainObject(config)) {
+ unsupported('(not an object)')
+ continue
+ }
+
+ for (const [key, value] of Object.entries(config)) {
+ switch (key) {
+ case 'entries':
+ collector.entries((Array.isArray(value) ? value : [value]).map(withoutIgnoredEntryKeys), unsupported)
+ break
+ case 'externals':
+ collector.externals(value, unsupported)
+ break
+ case 'replace':
+ collector.replaceValues(value, 'replace', unsupported)
+ break
+ case 'rollup':
+ translateRollup(value)
+ break
+ case 'sourcemap':
+ sourcemap ||= value === true
+ break
+ case 'declaration':
+ declaration ??= value
+ break
+ case 'clean':
+ if (value === false) {
+ unsupported('clean: false')
+ }
+ break
+ case 'rootDir':
+ case 'outDir':
+ if (typeof value !== 'string' || resolve(cwd, value) !== (key === 'rootDir' ? cwd : outDir)) {
+ unsupported(key)
+ }
+ break
+ case 'hooks':
+ if (!isPlainObject(value)) {
+ unsupported('hooks')
+ break
+ }
+ for (const [hook, fn] of Object.entries(value)) {
+ if (typeof fn !== 'function') {
+ unsupported(`hooks['${hook}']`)
+ }
+ else if (SUPPORTED_HOOKS.includes(hook)) {
+ hooks[hook as BuildHookName].push(fn as BuildHook)
+ }
+ else if (hook.startsWith('mkdist:')) {
+ ignoredHooks.push(`${source}: hooks['${hook}']`)
+ }
+ else {
+ unsupported(`hooks['${hook}']`)
+ }
+ }
+ break
+ default:
+ if (!ACCEPTED_KEYS.has(key)) {
+ unsupported(key)
+ }
+ }
+ }
+
+ function translateRollup(value: unknown) {
+ if (!isPlainObject(value)) {
+ unsupported('rollup')
+ return
+ }
+ for (const [key, option] of Object.entries(value)) {
+ if ((key === 'emitCJS' || key === 'cjsBridge') && !option) {
+ continue
+ }
+ if (key === 'replace' && option === false) {
+ replaceDisabled = true
+ }
+ else if (key === 'replace' && isPlainObject(option)) {
+ const { sourcemap: _, sourceMap: __, ...replace } = option
+ collector.replaceOptions(replace, 'rollup.replace', unsupported)
+ }
+ // `output.exports` only affects CommonJS output, which is never emitted.
+ else if (!(key === 'output' && isPlainObject(option) && Object.keys(option).every(name => name === 'exports'))) {
+ unsupported(key === 'emitCJS' || key === 'cjsBridge' ? `rollup.${key}: true` : `rollup.${key}`)
+ }
+ }
+ }
+ }
+
+ let ctx: BuildContext | undefined
+ return {
+ ...collector.finish(options.pkg ?? {}, { replace: !replaceDisabled }),
+ sourcemap,
+ hooks,
+ ignoredHooks,
+ unsupported: rejected,
+ async callHook(hook, plan) {
+ ctx ??= createBuildContext(plan, declaration)
+ for (const fn of hooks[hook]) {
+ await fn(ctx)
+ }
+ },
+ }
+}
+
+/** Declarations are always generated, and relative declaration specifiers always carry their extension. */
+function withoutIgnoredEntryKeys(entry: unknown) {
+ if (!isPlainObject(entry)) {
+ return entry
+ }
+ const { declaration: _, ...rest } = entry
+ if ((rest.builder ?? (String(rest.input).endsWith('/') ? 'mkdist' : 'rollup')) === 'mkdist') {
+ delete rest.addRelativeDeclarationExtensions
+ }
+ return rest
+}
+
+/**
+ * Read `build.config.*` and `package.json`'s `unbuild` (or, failing that, `build`) field
+ * and translate them. Neither `unbuild` nor this package is loaded to evaluate the file:
+ * `defineBuildConfig` is replaced with the identity.
+ */
+export async function loadBuildConfig(cwd: string, pkg: PackageJson, outDir: string): Promise {
+ const field = buildConfigField(pkg)
+ const fieldSource = field ? [{ name: `package.json "${field}"`, config: pkg[field] }] : []
+
+ let importsUnbuild: boolean | undefined
+ let configs: unknown[] = []
+ const file = BUILD_CONFIG_FILES.find(file => existsSync(resolve(cwd, file)))
+ if (file) {
+ importsUnbuild = UNBUILD_IMPORT_RE.test(await readFile(resolve(cwd, file), 'utf8'))
+ const stubs = { 'unbuild': DEFINE_BUILD_CONFIG_STUB, '@nuxt/module-builder': DEFINE_BUILD_CONFIG_STUB }
+ const unresolvable = findModuleCodeIssues(cwd, [file], [])
+ if (unresolvable.length) {
+ const withoutFile = translateBuildConfig(fieldSource, { cwd, outDir })
+ const runtimeDirs = [resolve(cwd, 'src/runtime'), ...withoutFile.directories.map(directory => directory.srcDir)]
+ const entries = bundledEntries(cwd, withoutFile)
+ unresolvable.push(...findModuleCodeIssues(cwd, [entries.module], runtimeDirs, Object.values(entries)))
+ throw new Error(formatModuleCodeIssues(unresolvable))
+ }
+ const { default: config } = await importModule(resolve(cwd, file), { cwd, stubs })
+ if (typeof config === 'function') {
+ throw new TypeError(`\`${file}\` must export a config object, not a function. Replace the function with the object it returns. ${guide('other-options')}`)
+ }
+ configs = (Array.isArray(config) ? config : [config]).filter(Boolean)
+ }
+
+ const translated = translateBuildConfig([...configs.map(config => ({ name: file!, config })), ...fieldSource], { cwd, outDir, pkg })
+ if (configs.length > 1) {
+ translated.unsupported.unshift(`${file}: an array of ${configs.length} configs`)
+ }
+ return Object.assign(translated, { file, importsUnbuild, field })
+}
+
+/** {@link loadBuildConfig}, failing on options without an equivalent and warning about deprecated ones. */
+export async function loadLegacyModuleConfig(cwd: string, pkg: PackageJson, outDir: string): Promise {
+ const config = await loadBuildConfig(cwd, pkg, outDir)
+ if (config.unsupported.length) {
+ throw new Error(formatUnsupportedOptions(config.unsupported))
+ }
+ warnDeprecatedBuildConfig(config)
+ return config
+}
+
+/**
+ * Fails when `build.config.*` or a `build` or `unbuild` field of `package.json` would
+ * configure the build alongside `builder()`.
+ */
+export function assertNoLegacyBuildConfig(cwd: string, pkg: PackageJson): void {
+ const file = BUILD_CONFIG_FILES.find(file => existsSync(resolve(cwd, file)))
+ const field = buildConfigField(pkg)
+ if (file || field) {
+ const source = file ? `\`${file}\`` : `The \`${field}\` field of \`package.json\``
+ const advice = file ? 'delete the file' : 'remove the field'
+ throw new Error(`${source} configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and ${advice}. ${guide('moving-from-buildconfigts')}`)
+ }
+}
+
+export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void {
+ for (const hook of config.ignoredHooks) {
+ consola.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`)
+ }
+ if (config.file) {
+ consola.warn([
+ `\`${config.file}\` is deprecated. Its options are still applied.`,
+ ...config.importsUnbuild ? ['Import `defineBuildConfig` from `@nuxt/module-builder` instead of `unbuild`.'] : [],
+ 'Move them into `builder()` in `tsdown.config.ts`.',
+ guide('moving-from-buildconfigts'),
+ ].join(' '))
+ }
+ if (config.field === 'unbuild') {
+ consola.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`)
+ }
+}
+
+function buildConfigField(pkg: PackageJson): LoadedBuildConfig['field'] {
+ return pkg.unbuild !== undefined ? 'unbuild' : pkg.build !== undefined ? 'build' : undefined
+}
+
+function createBuildContext({ cwd, outDir, pkg, entries, directories, sourcemap }: BuildPlan, declaration: unknown): BuildContext {
+ return {
+ options: {
+ name: (pkg.name || '').split('/').pop() || 'default',
+ rootDir: cwd,
+ outDir,
+ entries: [
+ ...Object.entries(entries).map(([name, input]) => ({ input: resolve(cwd, input), name, builder: 'rollup' as const, outDir })),
+ ...directories.map(({ srcDir, outDir }) => ({ input: `${srcDir}/`, name: entryName(relative(cwd, srcDir), cwd), builder: 'mkdist' as const, outDir })),
+ ],
+ declaration,
+ stub: false,
+ sourcemap,
+ },
+ pkg,
+ }
+}
+
+export function formatUnsupportedOptions(unsupported: string[]): string {
+ return [
+ 'The build config uses options that `@nuxt/module-builder` v2 does not support:',
+ ...unsupported.map(option => ` - ${option} (${guide(unsupportedOptionSection(option))})`),
+ `Remove each of them from the file named. ${guide('unsupported-build-options')}`,
+ ].join('\n')
+}
+
+function unsupportedOptionSection(option: string): GuideSection {
+ const name = option.slice(option.indexOf(': ') + 2)
+ if (name.startsWith('hooks[')) {
+ return 'hooks'
+ }
+ if (name.startsWith('rollup.emitCJS')) {
+ return 'commonjs-output'
+ }
+ if (name.startsWith('rollup')) {
+ return 'rollup-options'
+ }
+ if (/^entries\[\d+\]\.(?!outDir|builder)/.test(name)) {
+ return 'mkdist-options'
+ }
+ return 'other-options'
+}
diff --git a/src/build/define.ts b/src/legacy/define.ts
similarity index 87%
rename from src/build/define.ts
rename to src/legacy/define.ts
index 1fe5171e..4bb9bbf5 100644
--- a/src/build/define.ts
+++ b/src/legacy/define.ts
@@ -1,3 +1,7 @@
+/**
+ * `defineBuildConfig` and the types of a v1 module's `build.config.ts`, which
+ * `@nuxt/module-builder` still exports for modules that have not moved to `builder()`.
+ */
import type { PackageJson } from 'pkg-types'
export interface BuildEntry {
@@ -43,8 +47,8 @@ export interface BuildConfig {
/**
* Type helper for a legacy `build.config.ts`, which `nuxt-module-build` still reads.
- * Supported options are `entries`, `externals`, `replace`, `rollup.replace` and the
- * `build:before`, `rollup:done` and `build:done` hooks.
+ * Supported options are `entries`, `externals`, `replace`, `rollup.replace`, `sourcemap` and
+ * the `build:before`, `rollup:done` and `build:done` hooks.
*
* @deprecated `build.config.ts` will stop being read in a future major. Move `entries`, `externals`
* and `replace` into `builder()` from `@nuxt/module-builder/tsdown`, in `tsdown.config.ts`, and
diff --git a/src/legacy/package-paths.ts b/src/legacy/package-paths.ts
new file mode 100644
index 00000000..4f3be881
--- /dev/null
+++ b/src/legacy/package-paths.ts
@@ -0,0 +1,25 @@
+/**
+ * Advice for `package.json` paths to the `.d.ts` declarations and `module.cjs` that v1
+ * of `@nuxt/module-builder` generated for the module entry.
+ */
+import type { PackageJson } from 'pkg-types'
+
+import { guide } from '../build/guide.ts'
+import { list, missingPaths, warnWhen } from '../build/package.ts'
+
+const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/
+const CJS_MODULE_RE = /(?:^|\/)module\.cjs$/
+
+/** Whether `path` is one that v1 generated and the build no longer does, which the checks below explain. */
+export function isLegacyPath(path: string): boolean {
+ return DECLARATION_RE.test(path) || CJS_MODULE_RE.test(path)
+}
+
+export function checkLegacyDeclarationPaths(cwd: string, pkg: PackageJson): boolean {
+ const paths = missingPaths(cwd, pkg).filter(path => DECLARATION_RE.test(path))
+ return warnWhen(paths.length > 0, `\`@nuxt/module-builder\` no longer generates \`.d.ts\` declarations for the module entry. Replace \`.d.ts\` with \`.d.mts\` in these \`package.json\` paths: ${list(paths)}. ${guide('declaration-paths')}`)
+}
+
+export function checkLegacyCJSPaths(cwd: string, pkg: PackageJson): boolean {
+ return warnWhen(missingPaths(cwd, pkg).some(path => CJS_MODULE_RE.test(path)), `\`@nuxt/module-builder\` no longer generates \`module.cjs\`, which Nuxt 3 and later do not need. Replace it with \`./dist/module.mjs\` in \`package.json\`. ${guide('modulecjs')}`)
+}
diff --git a/src/rolldown/index.ts b/src/rolldown/index.ts
deleted file mode 100644
index 7e5b92cf..00000000
--- a/src/rolldown/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { emptyEntry, transpileDir, TYPE_ERRORS_WARNING } from './transpile-dir.ts'
-export type { ExternalImport, ImportKind, MirrorExternal, ResolveExternal, Transform, TransformOptions, TransformResult, TranspileDirApi, TranspileDirOptions } from './transpile-dir.ts'
-export type { VueOptions } from './vue.ts'
diff --git a/src/rolldown/transpile-dir.ts b/src/rolldown/transpile-dir.ts
deleted file mode 100644
index f1e1426d..00000000
--- a/src/rolldown/transpile-dir.ts
+++ /dev/null
@@ -1,646 +0,0 @@
-import { readFile } from 'node:fs/promises'
-import type { TsConfigResult } from 'get-tsconfig'
-import { basename, dirname, join, normalize, relative, resolve } from 'pathe'
-import { glob } from 'tinyglobby'
-import type { Rolldown } from 'tsdown'
-
-import type { Transform as VueTransform } from 'vue-sfc-transformer/core'
-
-import { createDeclarationProgram, DeclarationError, declarationError, relativeSpecifier } from './declarations.ts'
-import type { DeclarationProgram } from './declarations.ts'
-import { DECLARATION_RE, moduleSpecifiers, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE, scriptExtension, valueSpecifiers } from './resolve.ts'
-import { compileSass, SASS_RE, transformCss } from './stylesheets.ts'
-import { createTsconfigResolver, writeDependencyImports, writeDerivedTsconfig } from './tsconfig.ts'
-import { declarationPath, emitDeclarations, transformVueRuntime } from './vue.ts'
-import type { VueDeclarations, VueOptions } from './vue.ts'
-
-export interface TransformResult {
- code: string
- map?: object
- errors: Array<{ message: string }>
-}
-
-export interface TransformOptions {
- lang?: string
- sourcemap?: boolean
- jsx?: 'preserve' | { runtime?: 'automatic' | 'classic', importSource?: string }
- typescript?: { onlyRemoveTypeImports?: boolean }
- tsconfig?: string
-}
-
-/** The shape of `transform` from `rolldown/utils`. */
-export type Transform = (filename: string, source: string, options?: TransformOptions) => Promise
-
-export type ImportKind = 'value' | 'type'
-
-export interface ExternalImport {
- /** Absolute path of the file the specifier resolves to. */
- file: string
- /** Whether the import remains in the emitted script, or only its types are used. */
- kind: ImportKind
- /** Where the importer is emitted, relative to the output directory. */
- from: string
- /** Where the plugin would emit the file, relative to the output directory. */
- output: string
-}
-
-export interface MirrorExternal {
- /** Emit the file alongside the directory: as a script and declaration, or as a declaration only. */
- mirror: ImportKind
- /** Where to emit it, relative to the output directory. Defaults to the proposed `output`. */
- output?: string
-}
-
-/**
- * Decides what happens to a relative import that resolves outside `srcDir`: a replacement
- * specifier, a mirrored copy of the file, or `undefined` to keep the specifier as written.
- */
-export type ResolveExternal = (specifier: string, importer: string, context: ExternalImport) => string | MirrorExternal | undefined | Promise
-
-export interface TranspileDirOptions {
- /** The directory whose files are transpiled one by one. */
- srcDir: string
- /** Where the outputs go, relative to the build's output directory. Defaults to its root. */
- outBase?: string
- /** The project root: where `srcDir` is resolved, the tsconfig search starts and `node_modules` is read. Defaults to the build's `cwd`. */
- cwd?: string
- /** Globs of files to include, relative to `srcDir`. Defaults to every file. */
- include?: string[]
- /** Globs of files to exclude. Defaults to test and story files. */
- exclude?: string[]
- /** The extension of emitted scripts; declarations follow (`.d.ts` or `.d.mts`). Defaults to `js`. */
- extension?: 'js' | 'mjs'
- /** The tsconfig to compile with, or `false` for none. Defaults to the nearest one above `cwd`. */
- tsconfig?: string | false
- /** `paths` added to the tsconfig's when generating declarations. */
- paths?: Record
- /**
- * JSX compilation for `.tsx` and `.jsx` files, or a function of the source path that returns it.
- * Defaults to `'preserve'`, which emits them as `.jsx` with types stripped, next to a `.d.ts`,
- * for the consumer's JSX plugin (such as `@vitejs/plugin-vue-jsx`) to compile.
- */
- jsx?: TransformOptions['jsx'] | ((file: string) => TransformOptions['jsx'])
- /** The oxc `transform` to use. Defaults to the one of the `rolldown` installed. */
- transform?: Transform
- /** Emit source maps next to scripts. */
- sourcemap?: boolean
- /** Generate declarations. Defaults to `true`. */
- declaration?: boolean
- /** Process `.css` with lightningcss and compile Sass. Defaults to `true`; `false` copies stylesheets as they are. */
- stylesheets?: boolean
- /** Options for `.vue` files, or `false` to leave them out. */
- vue?: VueOptions | false
- /** Relative imports that resolve outside `srcDir`. By default they are kept as written. */
- resolveExternal?: ResolveExternal
-}
-
-export interface TranspileDirApi {
- /** Every discovered or mirrored source of the latest build, mapped to the path it is emitted at, relative to the output directory. */
- readonly outputs: Promise>
-}
-
-const EMPTY_ENTRY_ID = '\0transpile-dir:empty-entry'
-
-/**
- * An entry for a build that has nothing to bundle, only directories to transpile. Pass it
- * as tsdown's `entry` (or rolldown's `input`); `transpileDir` resolves it to an empty module
- * and removes its chunk from the output.
- */
-export const emptyEntry: Record = { 'transpile-dir': EMPTY_ENTRY_ID }
-
-/** `pluginCode` of the warning that lists type errors which do not affect the emitted declarations. */
-export const TYPE_ERRORS_WARNING = 'TYPE_ERRORS'
-
-type Warning = string | { pluginCode: string, message: string }
-
-interface Edge {
- specifier: string
- target: string
- value: boolean
-}
-
-type Resolution = { specifier: string } | { target: string, kind: ImportKind, output?: string } | undefined
-
-interface Emitted {
- fileName: string
- source: string | Uint8Array
- map?: { source: string, map: object }
-}
-
-const EMPTY_IMPORT_RE = /^[ \t]*import\s*\{\s*\}\s*from\s*(['"])[^'"\n]+\1\s*;?/gm
-export const DEFAULT_EXCLUDE: string[] = ['**/*.{stories,spec,test}.{js,jsx,ts,tsx,mjs,cjs,mts,cts}', '**/node_modules/**']
-const STYLESHEET_RE = /\.(?:css|s[ac]ss)$/
-const VUE_DECLARATION_RE = /\.(?:d\.vue\.ts|vue\.d\.ts)$/
-const TYPESCRIPT_RE = /\.(?:[cm]?ts|tsx)$/
-
-interface Emitter {
- /** Rewritten declarations keyed by source path. */
- emitted: Map
- /** The program shared by single-file components and TypeScript sources, when the directory has components. */
- vue?: () => Promise
- emit: (files: string[]) => Promise
-}
-
-/**
- * Transpiles the files of a directory one by one: each script keeps its own imports and
- * exports, `.vue` files go through `vue-sfc-transformer`, stylesheets are processed, other
- * files are copied, and declarations come from one TypeScript program over the directory.
- */
-export function transpileDir(options: TranspileDirOptions): Rolldown.Plugin & { api: TranspileDirApi } {
- let cwd = process.cwd()
- let resolveOutputs: (outputs: Map) => void
- let rejectOutputs: (error: unknown) => void
- const outputs = new Promise>((resolve, reject) => {
- resolveOutputs = resolve
- rejectOutputs = reject
- })
- outputs.catch(() => {})
- let latestOutputs = outputs
- let work: Promise<{ build: DirectoryBuild, files: Emitted[] } | { error: unknown }> | undefined
- let latestBuild: DirectoryBuild | undefined
-
- return {
- name: 'transpile-dir',
- api: {
- get outputs() {
- return latestOutputs
- },
- },
- resolveId: {
- filter: { id: /^\0transpile-dir:empty-entry$/ },
- handler: id => id,
- },
- load: {
- filter: { id: /^\0transpile-dir:empty-entry$/ },
- handler: () => ({ code: 'export {}', moduleSideEffects: false }),
- },
- async buildStart(inputOptions) {
- cwd = resolve(inputOptions.cwd, options.cwd ?? '')
- const srcDir = resolve(cwd, options.srcDir)
- const files = await glob(options.include ?? ['**/*'], { cwd: srcDir, ignore: options.exclude ?? DEFAULT_EXCLUDE, absolute: true, onlyFiles: true })
- for (const file of files) {
- this.addWatchFile(file)
- }
- const build = latestBuild = new DirectoryBuild({ ...options, cwd, srcDir }, files.map(file => normalize(file)).sort())
- work = build.run()
- .then((files) => {
- resolveOutputs(build.outputs)
- return { build, files }
- })
- .catch((error) => {
- rejectOutputs(error)
- return { error }
- })
- latestOutputs = work.then(result => 'error' in result ? Promise.reject(result.error) : result.build.outputs)
- latestOutputs.catch(() => {})
- },
- async buildEnd() {
- await work
- for (const source of latestBuild?.outputs.keys() ?? []) {
- this.addWatchFile(source)
- }
- },
- async generateBundle(outputOptions, bundle) {
- for (const [fileName, output] of Object.entries(bundle)) {
- if (output.type === 'chunk' && output.facadeModuleId === EMPTY_ENTRY_ID) {
- Reflect.deleteProperty(bundle, fileName)
- }
- }
- const result = await work!
- if ('error' in result) {
- this.error(result.error instanceof Error ? result.error : new Error(String(result.error)))
- }
- for (const warning of result.build.warnings) {
- this.warn(warning)
- }
- const outDir = resolve(cwd, outputOptions.dir ?? '')
- for (const { fileName, source, map } of result.files) {
- this.emitFile({ type: 'asset', fileName, source })
- if (map) {
- const sources = [relative(dirname(join(outDir, fileName)), map.source)]
- this.emitFile({ type: 'asset', fileName: `${fileName}.map`, source: JSON.stringify({ ...map.map, sources, file: basename(fileName) }) })
- }
- }
- },
- }
-}
-
-class DirectoryBuild {
- /** Source path to output path, relative to the output directory. */
- outputs = new Map()
- warnings: Warning[] = []
- private typeErrors: string[] = []
- private scripts: string[] = []
- private vue: string[] = []
- private assets: string[] = []
- private outside = new Map()
- private edges = new Map>()
- private resolutions = new Map>()
- private references = new Map>()
- private transform: Promise | undefined
- private resolver: ReturnType | undefined
- private extension: string
- private dtsExtension: string
- private outBase: string
- private options: TranspileDirOptions & { cwd: string, srcDir: string }
-
- constructor(options: TranspileDirOptions & { cwd: string, srcDir: string }, files: string[]) {
- this.options = options
- this.extension = `.${options.extension ?? 'js'}`
- this.dtsExtension = options.extension === 'mjs' ? '.d.mts' : '.d.ts'
- this.outBase = options.outBase ?? ''
- for (const file of files) {
- const path = join(this.outBase, relative(options.srcDir, file))
- if (file.endsWith('.vue')) {
- if (options.vue !== false) {
- this.vue.push(file)
- this.outputs.set(file, path)
- }
- }
- else if (SCRIPT_RE.test(file) && !DECLARATION_RE.test(file)) {
- this.scripts.push(file)
- this.outputs.set(file, path.replace(SCRIPT_RE, this.scriptExtension(file)))
- }
- else if (options.stylesheets === false) {
- this.assets.push(file)
- this.outputs.set(file, path)
- }
- else if (!(SASS_RE.test(file) && basename(file).startsWith('_'))) {
- this.assets.push(file)
- this.outputs.set(file, path.replace(SASS_RE, '.css'))
- }
- }
- }
-
- async run(): Promise {
- await this.plan()
- const valueFiles = [...this.outside].filter(([, kind]) => kind === 'value').map(([file]) => file)
- const emitter = this.options.declaration === false ? undefined : await this.createEmitter()
- const settled = await Promise.allSettled([
- Promise.all([...this.scripts, ...valueFiles].map(file => this.transpile(file))),
- Promise.all(this.assets.map(file => this.asset(file))),
- this.transformVue(emitter),
- emitter?.emit([...this.scripts, ...valueFiles]),
- ])
- const failures = settled.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : [])
- if (failures.length) {
- throw failures.every(failure => failure instanceof DeclarationError)
- ? declarationError([...new Set(failures.flatMap(failure => failure.diagnostics))])
- : failures.find(failure => !(failure instanceof DeclarationError))
- }
- const [scripts, assets, vue] = settled.map(result => (result as PromiseFulfilledResult).value) as [Emitted[], Emitted[], Emitted[]]
- const declarations: Emitted[] = []
- if (emitter) {
- const requested = new Set([...this.scripts, ...valueFiles])
- let referenced = this.referencedOutside([...this.scripts, ...valueFiles, ...this.vue], requested)
- while (referenced.length) {
- await emitter.emit(referenced)
- referenced = this.referencedOutside(referenced, requested)
- }
- for (const [source, text] of emitter.emitted) {
- declarations.push({ fileName: this.declarationOutput(source), source: text })
- }
- }
- if (this.typeErrors.length) {
- this.warnings.push({ pluginCode: TYPE_ERRORS_WARNING, message: typeErrorsWarning([...new Set(this.typeErrors)], relative(this.options.cwd, this.options.srcDir)) })
- }
- return [...scripts, ...assets, ...vue, ...declarations]
- }
-
- private jsx(file: string) {
- const { jsx } = this.options
- return (typeof jsx === 'function' ? jsx(file) : jsx) ?? 'preserve'
- }
-
- private scriptExtension(file: string) {
- return scriptExtension(file, this.extension, this.jsx(file) === 'preserve')
- }
-
- private declarationOutput(source: string) {
- const output = this.outputs.get(source)!
- return output.replace(SCRIPT_RE, output.endsWith('.jsx') ? '.d.ts' : this.dtsExtension)
- }
-
- private async plan() {
- const kinds = new Map([...this.scripts, ...this.vue].map(file => [file, 'value']))
- const queue = [...kinds.keys()]
- const taken = new Set([...this.outputs.values()].map(stem))
- while (queue.length) {
- const importer = queue.shift()!
- const importerKind = kinds.get(importer)!
- for (const edge of await this.edgesOf(importer)) {
- if (this.outputs.has(edge.target) && !this.outside.has(edge.target)) {
- continue
- }
- const kind: ImportKind = importerKind === 'value' && edge.value ? 'value' : 'type'
- const from = this.outputs.get(importer)!
- const proposed = this.proposedOutput(importer, edge.target, taken)
- const result = await this.resolveExternal(edge, importer, { file: edge.target, kind, from, output: proposed })
- if (!result || !('target' in result)) {
- continue
- }
- const existing = this.outside.get(edge.target)
- if (existing === 'value' || existing === result.kind) {
- continue
- }
- if (!existing) {
- const output = result.output ?? proposed
- this.outputs.set(edge.target, output)
- taken.add(stem(output))
- }
- this.outside.set(edge.target, result.kind)
- kinds.set(edge.target, result.kind)
- queue.push(edge.target)
- }
- }
- }
-
- private resolveExternal(edge: Edge, importer: string, context: ExternalImport) {
- const key = `${importer}\0${edge.specifier}\0${context.kind}`
- let pending = this.resolutions.get(key)
- if (!pending) {
- pending = Promise.resolve(this.options.resolveExternal?.(edge.specifier, importer, context)).then((result): Resolution => {
- if (typeof result === 'string') {
- return { specifier: result }
- }
- if (result) {
- return { target: edge.target, kind: result.mirror, output: result.output }
- }
- })
- this.resolutions.set(key, pending)
- }
- return pending
- }
-
- /**
- * Where a file outside the directory goes: where the importer's relative specifier
- * already points, or under `_external/` (with `..` segments as `_`) when that leaves the
- * output directory or takes another output's name.
- */
- private proposedOutput(importer: string, target: string, taken: Set) {
- const mirrored = stem(join(dirname(this.outputs.get(importer)!), relative(dirname(importer), target)))
- if (!mirrored.startsWith('..') && !taken.has(mirrored)) {
- return mirrored + this.scriptExtension(target)
- }
- const segments = stem(relative(this.options.cwd, target)).split('/').map(segment => segment === '..' ? '_' : segment)
- return join('_external', ...segments) + this.scriptExtension(target)
- }
-
- private edgesOf(importer: string) {
- let edges = this.edges.get(importer)
- if (!edges) {
- edges = this.readEdges(importer)
- this.edges.set(importer, edges)
- }
- return edges
- }
-
- private async readEdges(importer: string): Promise {
- const source = await readFile(importer, 'utf8')
- const values = importer.endsWith('.vue') ? valueSpecifiers(source) : valueSpecifiers((await this.transpileSource(importer, source)).code)
- const edges: Edge[] = []
- const seen = new Set()
- for (const { specifier } of moduleSpecifiers(source)) {
- if (!RELATIVE_RE.test(specifier) || seen.has(specifier)) {
- continue
- }
- seen.add(specifier)
- const target = probe(resolve(dirname(importer), specifier))
- if (target && SCRIPT_RE.test(target) && !DECLARATION_RE.test(target)) {
- edges.push({ specifier, target: normalize(target), value: values.has(specifier) })
- }
- }
- return edges
- }
-
- private loadTransform() {
- if (this.options.transform) {
- return this.options.transform
- }
- this.transform ??= import('rolldown/utils').then(utils => utils.transform as Transform, (cause) => {
- throw new Error('`transpileDir` needs `rolldown` to transpile scripts. Install it, or pass its `transform` in the `transform` option.', { cause })
- })
- return this.transform
- }
-
- private async transpileSource(file: string, source: string, sourcemap = false) {
- const transform = await this.loadTransform()
- const resolver = await (this.resolver ??= this.tsconfigs())
- const project = resolver?.resolve(file)
- const result = await transform(file, /\.[cm]?tsx?$/.test(file) ? source.replace(EMPTY_IMPORT_RE, match => ' '.repeat(match.length)) : source, {
- lang: file.match(/\.[cm]?([jt]sx?)$/)![1],
- sourcemap,
- jsx: this.jsx(file),
- typescript: { onlyRemoveTypeImports: false },
- ...project && project !== resolver?.root && { tsconfig: project.path },
- })
- if (result.errors.length) {
- throw new Error(`Failed to transpile ${relative(this.options.cwd, file)}:\n${result.errors.map(error => error.message).join('\n')}`)
- }
- return result
- }
-
- private async transpile(file: string): Promise {
- const fileName = this.outputs.get(file)!
- const result = await this.transpileSource(file, await readFile(file, 'utf8'), this.options.sourcemap)
- const code = await this.rewriteSpecifiers(file, fileName, result.code)
- if (!this.options.sourcemap || !result.map) {
- return { fileName, source: code }
- }
- return { fileName, source: `${code}\n//# sourceMappingURL=${basename(fileName)}.map\n`, map: { source: file, map: result.map } }
- }
-
- /**
- * `code` of `source`, emitted at `output`, with relative specifiers pointing at planned
- * outputs. For declarations, the files referred to are recorded.
- */
- private async rewriteSpecifiers(source: string, output: string, code: string, declaration = false) {
- const replacements = new Map()
- const referenced = new Set()
- for (const { specifier } of moduleSpecifiers(code)) {
- if (!RELATIVE_RE.test(specifier) || replacements.has(specifier)) {
- continue
- }
- replacements.set(specifier, await this.replacement(source, specifier, output, referenced))
- }
- if (declaration) {
- this.references.set(source, referenced)
- }
- return rewriteSpecifiers(code, specifier => replacements.get(specifier))
- }
-
- private async replacement(source: string, specifier: string, output: string, referenced: Set) {
- const target = probe(resolve(dirname(source), specifier))
- if (!target) {
- return
- }
- const file = normalize(target)
- referenced.add(file)
- for (const kind of ['value', 'type'] as const) {
- const resolution = await this.resolutions.get(`${source}\0${specifier}\0${kind}`)
- if (resolution && 'specifier' in resolution) {
- return resolution.specifier
- }
- }
- const planned = this.outputs.get(file)
- if (planned && !DECLARATION_RE.test(file) && (SCRIPT_RE.test(file) || file.endsWith('.vue') || SASS_RE.test(file))) {
- return relativeSpecifier(output, planned)
- }
- }
-
- private async asset(file: string): Promise {
- const fileName = this.outputs.get(file)!
- if (this.options.stylesheets !== false && STYLESHEET_RE.test(file)) {
- const source = SASS_RE.test(file)
- ? await compileSass(file, this.options.cwd)
- : await transformCss(file, this.options.cwd, message => this.warnings.push(message))
- return { fileName, source }
- }
- return { fileName, source: await readFile(file) }
- }
-
- private tsconfigs() {
- return this.options.tsconfig === false ? undefined : createTsconfigResolver(this.options.cwd, this.options.tsconfig)
- }
-
- private async transformVue(emitter: Emitter | undefined): Promise {
- if (!this.vue.length) {
- return []
- }
- const runtime = await transformVueRuntime(this.vue, await this.loadTransform() as VueTransform)
- const results: Promise[] = [...runtime].map(async ([file, source]) => {
- const fileName = this.outputs.get(file)!
- return { fileName, source: await this.rewriteSpecifiers(file, fileName, source) }
- })
- if (!emitter) {
- return Promise.all(results)
- }
- const { declarations, errors, warnings } = await emitter.vue!()
- const selected = new Set(this.vue)
- const errorMessages = errors.filter(({ file }) => file === undefined || selected.has(file)).map(({ message }) => message)
- for (const file of this.vue) {
- if (!declarations.has(declarationPath(file)) && !errors.some(error => error.file === file)) {
- errorMessages.push(`${relative(this.options.cwd, file)}: no declaration was emitted`)
- }
- }
- if (errorMessages.length) {
- throw declarationError([...new Set(errorMessages)])
- }
- this.typeErrors.push(...warnings.filter(({ file }) => file !== undefined && selected.has(file)).map(({ message }) => message))
- for (const [path, source] of declarations) {
- const vueFile = path.replace(VUE_DECLARATION_RE, '.vue')
- if (!selected.has(vueFile)) {
- continue
- }
- const output = this.outputs.get(vueFile)!.replace(/\.vue$/, path.slice(vueFile.length - '.vue'.length))
- results.push(this.rewriteSpecifiers(vueFile, output, source, true).then(source => ({ fileName: output, source })))
- }
- return Promise.all(results)
- }
-
- /**
- * Declarations for the directory's scripts. With single-file components present,
- * TypeScript sources join their program so that types imported from a component
- * resolve; other scripts get one program per tsconfig project.
- */
- private async createEmitter(): Promise {
- const resolver = await this.tsconfigs()
- const imports = await writeDependencyImports(this.options.cwd, resolver?.root)
- const programs = new Map>()
- const programFor = (tsconfig: TsConfigResult | undefined) => {
- let program = programs.get(tsconfig?.path)
- if (!program) {
- program = createDeclarationProgram({ cwd: this.options.cwd, tsconfig, paths: this.options.paths ?? {} }, [...this.scripts, ...this.outside.keys(), ...imports ? [imports] : []])
- programs.set(tsconfig?.path, program)
- }
- return program
- }
- let vue: Promise | undefined
- const vueProgram = this.vue.length
- ? () => vue ??= (async () => {
- const tsconfig = resolver?.root
- return emitDeclarations([...this.vue, ...[...this.scripts, ...this.outside.keys()].filter(file => TYPESCRIPT_RE.test(file))], {
- ...this.options.vue || {},
- cwd: this.options.cwd,
- tsconfig: tsconfig && await writeDerivedTsconfig(this.options.cwd, tsconfig, this.options.paths ?? {}, { vue: true, imports }),
- })
- })()
- : undefined
- const emitted = new Map()
-
- return {
- emitted,
- vue: vueProgram,
- emit: async (files: string[]) => {
- const errors: string[] = []
- const warnings: string[] = []
- const groups = new Map, string[]>()
- const shared: string[] = []
- for (const file of files) {
- if (vueProgram && TYPESCRIPT_RE.test(file)) {
- shared.push(file)
- continue
- }
- const program = programFor(resolver?.resolve(file))
- groups.set(program, [...groups.get(program) ?? [], file])
- }
- if (shared.length) {
- const result = await vueProgram!()
- const selected = new Set(shared)
- errors.push(...result.errors.filter(({ file }) => file !== undefined && selected.has(file)).map(({ message }) => message))
- warnings.push(...result.warnings.filter(({ file }) => file !== undefined && selected.has(file)).map(({ message }) => message))
- for (const file of shared) {
- const text = result.declarations.get(declarationPath(file))
- if (text === undefined) {
- if (!result.errors.some(error => error.file === file)) {
- errors.push(`${relative(this.options.cwd, file)}: no declaration was emitted`)
- }
- continue
- }
- emitted.set(file, await this.rewriteSpecifiers(file, this.declarationOutput(file), text, true))
- }
- }
- for (const [pending, groupFiles] of groups) {
- const result = await (await pending).emit(groupFiles)
- errors.push(...result.errors)
- warnings.push(...result.warnings)
- for (const [source, text] of result.declarations) {
- emitted.set(source, await this.rewriteSpecifiers(source, this.declarationOutput(source), text, true))
- }
- }
- if (errors.length) {
- throw declarationError([...new Set(errors)])
- }
- this.typeErrors.push(...warnings)
- },
- }
- }
-
- private referencedOutside(sources: string[], requested: Set) {
- const referenced = new Set()
- for (const source of sources) {
- for (const target of this.references.get(source) ?? []) {
- if (this.outside.has(target) && !requested.has(target)) {
- referenced.add(target)
- requested.add(target)
- }
- }
- }
- return [...referenced]
- }
-}
-
-function stem(path: string) {
- return path.replace(SCRIPT_RE, '')
-}
-
-const SHOWN_TYPE_ERRORS = 3
-
-function typeErrorsWarning(diagnostics: string[], directory: string) {
- const hidden = diagnostics.length - SHOWN_TYPE_ERRORS
- return [
- `${diagnostics.length} type error${diagnostics.length === 1 ? ' was' : 's were'} reported while generating declarations for \`${directory}\`; the declarations were emitted. If the module's own type check (for example \`nuxt typecheck\` or \`vue-tsc --noEmit\`) passes, these come from build-time aliases typed as \`any\` during declaration generation and can be ignored.`,
- ...diagnostics.slice(0, SHOWN_TYPE_ERRORS),
- ...hidden > 0 ? [`... and ${hidden} more`] : [],
- ].join('\n')
-}
diff --git a/src/rolldown/declarations.ts b/src/transpile/declarations.ts
similarity index 89%
rename from src/rolldown/declarations.ts
rename to src/transpile/declarations.ts
index 719c85f6..26dcac4b 100644
--- a/src/rolldown/declarations.ts
+++ b/src/transpile/declarations.ts
@@ -1,9 +1,8 @@
import type { TsConfigResult } from 'get-tsconfig'
-import { dirname, relative } from 'pathe'
+import { relative } from 'pathe'
import type ts from 'typescript'
-import { declarationPaths, projectFiles, tsconfigPaths, writeAmbientModules, writeServerRoutesStub } from './tsconfig.ts'
-import type { DeclarationPaths } from './tsconfig.ts'
+import { projectFiles, writeDeclarationPaths } from './tsconfig.ts'
export interface DeclarationProgramOptions {
cwd: string
@@ -22,7 +21,6 @@ interface DeclarationEmit {
}
export interface DeclarationProgram {
- paths: DeclarationPaths
emit: (files: string[]) => Promise
/** The program's source files other than declaration files. */
sources: () => string[]
@@ -38,12 +36,8 @@ export async function createDeclarationProgram({ cwd, tsconfig, paths }: Declara
const { default: ts } = await import('typescript')
const classifier = import('vue-sfc-transformer/core')
const parsed = tsconfig ? ts.getParsedCommandLineOfConfigFile(tsconfig.path, {}, configHost(ts)) : undefined
- const declaration = declarationPaths({ ...tsconfigPaths(tsconfig), ...paths }, cwd)
- const rootNames = new Set([...projectFiles(parsed, cwd), ...roots])
- await writeServerRoutesStub(cwd)
- if (declaration.ambient.length) {
- rootNames.add(await writeAmbientModules(cwd, declaration.ambient))
- }
+ const declaration = await writeDeclarationPaths(cwd, tsconfig, paths)
+ const rootNames = new Set([...projectFiles(parsed, cwd), ...roots, ...declaration.ambient ? [declaration.ambient] : []])
const options: ts.CompilerOptions = {
...parsed?.options,
@@ -65,7 +59,6 @@ export async function createDeclarationProgram({ cwd, tsconfig, paths }: Declara
const createProgram = () => program ??= ts.createProgram({ rootNames: [...rootNames], options, projectReferences: parsed?.projectReferences })
return {
- paths: declaration,
sources: () => createProgram().getSourceFiles().filter(source => !source.isDeclarationFile).map(source => source.fileName),
resolve: (specifier, importer) => ts.resolveModuleName(specifier, importer, options, ts.sys).resolvedModule?.resolvedFileName,
async emit(files) {
@@ -166,9 +159,3 @@ export function declarationError(diagnostics: string[]): DeclarationError {
: [],
].join('\n'), diagnostics)
}
-
-/** The relative specifier from the directory of `from` to `to`. */
-export function relativeSpecifier(from: string, to: string): string {
- const path = relative(dirname(from), to)
- return path.startsWith('.') ? path : `./${path}`
-}
diff --git a/src/rolldown/resolve.ts b/src/transpile/specifiers.ts
similarity index 66%
rename from src/rolldown/resolve.ts
rename to src/transpile/specifiers.ts
index 01b4a018..c34681cb 100644
--- a/src/rolldown/resolve.ts
+++ b/src/transpile/specifiers.ts
@@ -1,10 +1,7 @@
-import { existsSync, statSync } from 'node:fs'
import { findDynamicImports, findExports, findStaticImports, findTypeExports } from 'mlly'
-import { resolve } from 'pathe'
-export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/
-export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/
-export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/
+import { RELATIVE_RE } from '../utils.ts'
+
const JSX_RE = /\.[jt]sx$/
/** The extension `file` is emitted with: `.jsx` for a JSX source when JSX is preserved, `extension` otherwise. */
@@ -12,32 +9,6 @@ export function scriptExtension(file: string, extension: string, preserveJsx: bo
return preserveJsx && JSX_RE.test(file) ? '.jsx' : extension
}
-const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx']
-
-/** The file an extensionless or `.js`-suffixed specifier for a TypeScript source resolves to. */
-export function probe(path: string): string | undefined {
- if (existsSync(path) && statSync(path).isFile()) {
- return path
- }
- const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2')
- if (source !== path && existsSync(source)) {
- return source
- }
- if (path.endsWith('.js') && existsSync(`${source}x`)) {
- return `${source}x`
- }
- for (const extension of EXTENSIONS) {
- if (existsSync(path + extension)) {
- return path + extension
- }
- }
- for (const extension of EXTENSIONS) {
- if (existsSync(resolve(path, `index${extension}`))) {
- return resolve(path, `index${extension}`)
- }
- }
-}
-
export interface Specifier {
specifier: string
/** Offset of the opening quote. */
@@ -46,13 +17,21 @@ export interface Specifier {
end: number
}
+const DYNAMIC_IMPORT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*)*(?:(['"])([^'"\n]+)\1|`([^`$]+)`)\s*(?:,[\s\S]*)?$/
+
+/** The specifier of an `import()` whose first argument is a string literal. */
+function dynamicImportSpecifier(expression: string) {
+ const match = expression.match(DYNAMIC_IMPORT_RE)
+ return match ? match[2] ?? match[3] : undefined
+}
+
const TYPE_STAR_EXPORT_RE = /\bexport\s+type\s*\*(?:\s*as\s+[\w$]+)?\s*from\s*(['"])([^'"\n]+)\1/g
/** Every string-literal module specifier in `code`: static imports, re-exports (type-only ones included) and `import()` calls. */
export function moduleSpecifiers(code: string): Specifier[] {
const found = new Map()
const locate = (statement: { code: string, start: number }, specifier: string) => {
- const index = Math.max(statement.code.indexOf(`'${specifier}'`), statement.code.indexOf(`"${specifier}"`))
+ const index = Math.max(...['\'', '"', '`'].map(quote => statement.code.indexOf(`${quote}${specifier}${quote}`)))
if (index !== -1) {
const start = statement.start + index
found.set(start, { specifier, start, end: start + specifier.length + 2 })
@@ -70,9 +49,9 @@ export function moduleSpecifiers(code: string): Specifier[] {
locate({ code: match[0], start: match.index }, match[2]!)
}
for (const statement of findDynamicImports(code)) {
- const literal = statement.expression.match(/^\s*(['"])([^'"]+)\1\s*$/)
- if (literal) {
- locate(statement, literal[2]!)
+ const specifier = dynamicImportSpecifier(statement.expression)
+ if (specifier) {
+ locate(statement, specifier)
}
}
return [...found.values()].sort((a, b) => a.start - b.start)
@@ -104,9 +83,9 @@ export function valueSpecifiers(code: string): Set {
}
}
for (const statement of findDynamicImports(code)) {
- const literal = statement.expression.match(/^\s*(['"])(\.\.?\/[^'"]*)\1\s*$/)
- if (literal) {
- values.add(literal[2]!)
+ const specifier = dynamicImportSpecifier(statement.expression)
+ if (specifier && RELATIVE_RE.test(specifier)) {
+ values.add(specifier)
}
}
return values
diff --git a/src/rolldown/stylesheets.ts b/src/transpile/stylesheets.ts
similarity index 93%
rename from src/rolldown/stylesheets.ts
rename to src/transpile/stylesheets.ts
index 2a29a7b9..6ae1268f 100644
--- a/src/rolldown/stylesheets.ts
+++ b/src/transpile/stylesheets.ts
@@ -3,6 +3,8 @@ import { pathToFileURL } from 'node:url'
import { resolvePath } from 'mlly'
import { join, relative } from 'pathe'
+import { getOrCreate } from '../utils.ts'
+
export const SASS_RE: RegExp = /\.s[ac]ss$/
interface SassCompiler {
@@ -45,13 +47,7 @@ const sassCompilers = new Map>()
/** Compile a Sass stylesheet with the `sass` or `sass-embedded` installed under `cwd`. */
export async function compileSass(file: string, cwd: string): Promise {
- let compiler = sassCompilers.get(cwd)
- if (!compiler) {
- compiler = loadSass(cwd)
- sassCompilers.set(cwd, compiler)
- }
-
- const { compileString } = await compiler
+ const { compileString } = await getOrCreate(sassCompilers, cwd, () => loadSass(cwd))
return compileString(await fsp.readFile(file, 'utf8'), {
loadPaths: [join(cwd, 'node_modules')],
url: pathToFileURL(file),
diff --git a/src/transpile/transpile-dir.ts b/src/transpile/transpile-dir.ts
new file mode 100644
index 00000000..5adeb75a
--- /dev/null
+++ b/src/transpile/transpile-dir.ts
@@ -0,0 +1,474 @@
+import { readFile } from 'node:fs/promises'
+import type { TsConfigResult } from 'get-tsconfig'
+import { basename, dirname, join, normalize, relative, resolve } from 'pathe'
+import { glob } from 'tinyglobby'
+import type { Rolldown } from 'tsdown'
+
+import type { Transform as VueTransform } from 'vue-sfc-transformer/core'
+
+import { getOrCreate, isSourceScript, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts'
+import { createDeclarationProgram, DeclarationError, declarationError } from './declarations.ts'
+import type { DeclarationProgram } from './declarations.ts'
+import { moduleSpecifiers, rewriteSpecifiers, scriptExtension, valueSpecifiers } from './specifiers.ts'
+import { compileSass, SASS_RE, transformCss } from './stylesheets.ts'
+import { createTsconfigResolver, writeDependencyImports, writeDerivedTsconfig } from './tsconfig.ts'
+import type { TsconfigResolver } from './tsconfig.ts'
+import { declarationPath, emitDeclarations, transformVueRuntime } from './vue.ts'
+import type { VueDeclarations } from './vue.ts'
+
+interface TransformResult {
+ code: string
+ map?: object
+ errors: Array<{ message: string }>
+}
+
+interface TransformOptions {
+ lang?: string
+ sourcemap?: boolean
+ jsx?: 'preserve' | { runtime?: 'automatic' | 'classic', importSource?: string }
+ typescript?: { onlyRemoveTypeImports?: boolean }
+ tsconfig?: string
+}
+
+/** The shape of `transform` from `rolldown/utils`. */
+export type Transform = (filename: string, source: string, options?: TransformOptions) => Promise
+
+type ImportKind = 'value' | 'type'
+
+export interface ExternalImport {
+ /** Absolute path of the file the specifier resolves to. */
+ file: string
+ /** Whether the import remains in the emitted script, or only its types are used. */
+ kind: ImportKind
+ /** Where the importer is emitted, relative to the output directory. */
+ from: string
+}
+
+/**
+ * Decides what happens to a relative import that resolves outside `srcDir`: a replacement
+ * specifier, a mirrored copy of the file (as a script and declaration, or as a declaration
+ * only), or `undefined` to keep the specifier as written.
+ */
+export type ResolveExternal = (specifier: string, importer: string, context: ExternalImport) => string | { mirror: ImportKind } | undefined
+
+export interface TranspileDirOptions {
+ /** Absolute path of the directory whose files are transpiled one by one. */
+ srcDir: string
+ /** Where the outputs go, relative to the build's output directory. */
+ outBase: string
+ /** The module root: where the tsconfig search starts and `node_modules` is read. */
+ cwd: string
+ /** The extension of emitted scripts; declarations follow (`.d.ts` or `.d.mts`). */
+ extension: 'js' | 'mjs'
+ /** `paths` added to the tsconfig's when generating declarations. */
+ paths: Record
+ /**
+ * JSX compilation for a `.tsx` or `.jsx` source. `'preserve'` emits it as `.jsx` with types
+ * stripped, next to a `.d.ts`, for the app's JSX plugin to compile.
+ */
+ jsx: (file: string) => NonNullable
+ /** The oxc `transform` of the `rolldown` that tsdown runs. */
+ transform: Transform
+ /** Emit source maps next to scripts. */
+ sourcemap: boolean
+ /** Extra key for the declaration cache of single-file components, for inputs the cache cannot see. */
+ cacheVersion: string
+ /** Relative imports that resolve outside `srcDir`. */
+ resolveExternal: ResolveExternal
+ /** Paths relative to the output directory, without extension, that mirrored files are not emitted at. */
+ reserved: string[]
+}
+
+/** `pluginCode` of the warning that lists type errors which do not affect the emitted declarations. */
+export const TYPE_ERRORS_WARNING = 'TYPE_ERRORS'
+
+type Warning = string | { pluginCode: string, message: string }
+
+interface Edge {
+ specifier: string
+ target: string
+ value: boolean
+}
+
+interface Emitted {
+ fileName: string
+ source: string | Uint8Array
+ map?: { source: string, map: object }
+}
+
+const EMPTY_IMPORT_RE = /^[ \t]*import\s*\{\s*\}\s*from\s*(['"])[^'"\n]+\1\s*;?/gm
+export const EXCLUDE: string[] = ['**/*.{stories,spec,test}.{js,jsx,ts,tsx,mjs,cjs,mts,cts}', '**/node_modules/**']
+const STYLESHEET_RE = /\.(?:css|s[ac]ss)$/
+const VUE_DECLARATION_RE = /\.(?:d\.vue\.ts|vue\.d\.ts)$/
+
+/**
+ * Transpiles the files of a directory one by one: each script keeps its own imports and
+ * exports, `.vue` files go through `vue-sfc-transformer`, stylesheets are processed, other
+ * files are copied, and declarations come from one TypeScript program over the directory.
+ * `api.outputs` maps every discovered or mirrored source of the latest build to the path it
+ * is emitted at, relative to the output directory.
+ */
+export function transpileDir(options: TranspileDirOptions): Rolldown.Plugin & { api: { readonly outputs: Promise> } } {
+ let work: Promise<{ build: DirectoryBuild, files: Emitted[] } | { error: unknown }> | undefined
+ let latestBuild: DirectoryBuild | undefined
+
+ return {
+ name: 'transpile-dir',
+ api: {
+ get outputs() {
+ return work!.then(result => 'error' in result ? Promise.reject(result.error) : result.build.outputs)
+ },
+ },
+ async buildStart() {
+ const files = await glob(['**/*'], { cwd: options.srcDir, ignore: EXCLUDE, absolute: true, onlyFiles: true })
+ for (const file of files) {
+ this.addWatchFile(file)
+ }
+ const build = latestBuild = new DirectoryBuild(options, files.map(file => normalize(file)).sort())
+ work = build.run().then(files => ({ build, files }), (error: unknown) => ({ error }))
+ },
+ async buildEnd() {
+ await work
+ for (const source of latestBuild?.outputs.keys() ?? []) {
+ this.addWatchFile(source)
+ }
+ },
+ async generateBundle(outputOptions) {
+ const result = await work!
+ if ('error' in result) {
+ this.error(result.error instanceof Error ? result.error : new Error(String(result.error)))
+ }
+ for (const warning of result.build.warnings) {
+ this.warn(warning)
+ }
+ const outDir = resolve(options.cwd, outputOptions.dir ?? '')
+ for (const { fileName, source, map } of result.files) {
+ this.emitFile({ type: 'asset', fileName, source })
+ if (map) {
+ const sources = [relative(dirname(join(outDir, fileName)), map.source)]
+ this.emitFile({ type: 'asset', fileName: `${fileName}.map`, source: JSON.stringify({ ...map.map, sources, file: basename(fileName) }) })
+ }
+ }
+ },
+ }
+}
+
+class DirectoryBuild {
+ /** Source path to output path, relative to the output directory. */
+ outputs = new Map()
+ warnings: Warning[] = []
+ private typeErrors: string[] = []
+ private scripts: string[] = []
+ private vue: string[] = []
+ private assets: string[] = []
+ private outside = new Map()
+ private edges = new Map>()
+ private resolutions = new Map>()
+ private references = new Map>()
+ /** Rewritten declarations keyed by source path. */
+ private declarations = new Map()
+ private programs = new Map>()
+ private vueDeclarations: Promise | undefined
+ private resolver!: TsconfigResolver
+ private imports: string | undefined
+ private extension: string
+ private dtsExtension: string
+ private options: TranspileDirOptions
+
+ constructor(options: TranspileDirOptions, files: string[]) {
+ this.options = options
+ this.extension = `.${options.extension}`
+ this.dtsExtension = options.extension === 'mjs' ? '.d.mts' : '.d.ts'
+ for (const file of files) {
+ const path = join(options.outBase, relative(options.srcDir, file))
+ if (file.endsWith('.vue')) {
+ this.vue.push(file)
+ this.outputs.set(file, path)
+ }
+ else if (isSourceScript(file)) {
+ this.scripts.push(file)
+ this.outputs.set(file, path.replace(SCRIPT_RE, this.scriptExtension(file)))
+ }
+ else if (!(SASS_RE.test(file) && basename(file).startsWith('_'))) {
+ this.assets.push(file)
+ this.outputs.set(file, path.replace(SASS_RE, '.css'))
+ }
+ }
+ }
+
+ async run(): Promise {
+ this.resolver = await createTsconfigResolver(this.options.cwd)
+ await this.plan()
+ this.imports = await writeDependencyImports(this.options.cwd, this.resolver.root)
+ const scripts = [...this.scripts, ...[...this.outside].filter(([, kind]) => kind === 'value').map(([file]) => file)]
+ const settled = await Promise.allSettled([
+ Promise.all(scripts.map(file => this.transpile(file))),
+ Promise.all(this.assets.map(file => this.asset(file))),
+ this.transformVue(),
+ this.emitDeclarations(scripts),
+ ])
+ const failures = settled.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : [])
+ if (failures.length) {
+ throw failures.every(failure => failure instanceof DeclarationError)
+ ? declarationError([...new Set(failures.flatMap(failure => failure.diagnostics))])
+ : failures.find(failure => !(failure instanceof DeclarationError))
+ }
+ const [transpiled, assets, vue] = settled.map(result => (result as PromiseFulfilledResult).value) as [Emitted[], Emitted[], Emitted[]]
+ const requested = new Set(scripts)
+ let referenced = this.referencedOutside([...scripts, ...this.vue], requested)
+ while (referenced.length) {
+ await this.emitDeclarations(referenced)
+ referenced = this.referencedOutside(referenced, requested)
+ }
+ const declarations = [...this.declarations].map(([source, text]) => ({ fileName: this.declarationOutput(source), source: text }))
+ if (this.typeErrors.length) {
+ this.warnings.push({ pluginCode: TYPE_ERRORS_WARNING, message: typeErrorsWarning([...new Set(this.typeErrors)], relative(this.options.cwd, this.options.srcDir)) })
+ }
+ return [...transpiled, ...assets, ...vue, ...declarations]
+ }
+
+ private scriptExtension(file: string) {
+ return scriptExtension(file, this.extension, this.options.jsx(file) === 'preserve')
+ }
+
+ private declarationOutput(source: string) {
+ const output = this.outputs.get(source)!
+ return output.replace(SCRIPT_RE, output.endsWith('.jsx') ? '.d.ts' : this.dtsExtension)
+ }
+
+ private async plan() {
+ const queue = [...this.scripts, ...this.vue]
+ const taken = new Set([...[...this.outputs.values()].map(stem), ...this.options.reserved])
+ while (queue.length) {
+ const importer = queue.shift()!
+ const importerKind = this.outside.get(importer) ?? 'value'
+ for (const edge of await getOrCreate(this.edges, importer, () => this.readEdges(importer))) {
+ if (this.outputs.has(edge.target) && !this.outside.has(edge.target)) {
+ continue
+ }
+ const kind: ImportKind = importerKind === 'value' && edge.value ? 'value' : 'type'
+ const context = { file: edge.target, kind, from: this.outputs.get(importer)! }
+ const result = getOrCreate(this.resolutions, `${importer}\0${edge.specifier}\0${kind}`, () => this.options.resolveExternal(edge.specifier, importer, context))
+ const existing = this.outside.get(edge.target)
+ if (!result || typeof result === 'string' || existing === 'value' || existing === result.mirror) {
+ continue
+ }
+ if (!existing) {
+ const output = this.proposedOutput(importer, edge.target, taken)
+ this.outputs.set(edge.target, output)
+ taken.add(stem(output))
+ }
+ this.outside.set(edge.target, result.mirror)
+ queue.push(edge.target)
+ }
+ }
+ }
+
+ /**
+ * Where a file outside the directory goes: where the importer's relative specifier
+ * already points, or under `_external/` (with `..` segments as `_`) when that leaves the
+ * output directory or takes another output's name.
+ */
+ private proposedOutput(importer: string, target: string, taken: Set) {
+ const mirrored = stem(join(dirname(this.outputs.get(importer)!), relative(dirname(importer), target)))
+ if (!mirrored.startsWith('..') && !taken.has(mirrored)) {
+ return mirrored + this.scriptExtension(target)
+ }
+ const segments = stem(relative(this.options.cwd, target)).split('/').map(segment => segment === '..' ? '_' : segment)
+ return join('_external', ...segments) + this.scriptExtension(target)
+ }
+
+ private async readEdges(importer: string): Promise {
+ const source = await readFile(importer, 'utf8')
+ const values = valueSpecifiers(importer.endsWith('.vue') ? source : (await this.transpileSource(importer, source)).code)
+ const specifiers = new Set(moduleSpecifiers(source).map(({ specifier }) => specifier).filter(specifier => RELATIVE_RE.test(specifier)))
+ return [...specifiers].flatMap((specifier) => {
+ const target = probe(resolve(dirname(importer), specifier))
+ return target && isSourceScript(target) ? [{ specifier, target: normalize(target), value: values.has(specifier) }] : []
+ })
+ }
+
+ private async transpileSource(file: string, source: string, sourcemap = false) {
+ const project = this.resolver.resolve(file)
+ const result = await this.options.transform(file, TYPESCRIPT_RE.test(file) ? source.replace(EMPTY_IMPORT_RE, match => ' '.repeat(match.length)) : source, {
+ lang: file.match(/\.[cm]?([jt]sx?)$/)![1],
+ sourcemap,
+ jsx: this.options.jsx(file),
+ typescript: { onlyRemoveTypeImports: false },
+ ...project && project !== this.resolver.root && { tsconfig: project.path },
+ })
+ if (result.errors.length) {
+ throw new Error(`Failed to transpile ${relative(this.options.cwd, file)}:\n${result.errors.map(error => error.message).join('\n')}`)
+ }
+ return result
+ }
+
+ private async transpile(file: string): Promise {
+ const fileName = this.outputs.get(file)!
+ const result = await this.transpileSource(file, await readFile(file, 'utf8'), this.options.sourcemap)
+ const code = this.rewriteSpecifiers(file, fileName, result.code)
+ if (!this.options.sourcemap || !result.map) {
+ return { fileName, source: code }
+ }
+ return { fileName, source: `${code}\n//# sourceMappingURL=${basename(fileName)}.map\n`, map: { source: file, map: result.map } }
+ }
+
+ /**
+ * `code` of `source`, emitted at `output`, with relative specifiers pointing at planned
+ * outputs. For declarations, the files referred to are recorded.
+ */
+ private rewriteSpecifiers(source: string, output: string, code: string, declaration = false) {
+ const referenced = new Set()
+ const rewritten = rewriteSpecifiers(code, specifier => RELATIVE_RE.test(specifier) ? this.replacement(source, specifier, output, referenced) : undefined)
+ if (declaration) {
+ this.references.set(source, referenced)
+ }
+ return rewritten
+ }
+
+ private replacement(source: string, specifier: string, output: string, referenced: Set) {
+ const target = probe(resolve(dirname(source), specifier))
+ if (!target) {
+ return
+ }
+ const file = normalize(target)
+ referenced.add(file)
+ for (const kind of ['value', 'type'] as const) {
+ const resolution = this.resolutions.get(`${source}\0${specifier}\0${kind}`)
+ if (typeof resolution === 'string') {
+ return resolution
+ }
+ }
+ const planned = this.outputs.get(file)
+ if (planned && (isSourceScript(file) || file.endsWith('.vue') || SASS_RE.test(file))) {
+ return relativeSpecifier(output, planned)
+ }
+ }
+
+ private async asset(file: string): Promise {
+ const fileName = this.outputs.get(file)!
+ if (STYLESHEET_RE.test(file)) {
+ const source = SASS_RE.test(file)
+ ? await compileSass(file, this.options.cwd)
+ : await transformCss(file, this.options.cwd, message => this.warnings.push(message))
+ return { fileName, source }
+ }
+ return { fileName, source: await readFile(file) }
+ }
+
+ private async transformVue(): Promise {
+ if (!this.vue.length) {
+ return []
+ }
+ const runtime = await transformVueRuntime(this.vue, this.options.transform as VueTransform)
+ const result = await this.vueProgram()
+ const { errors, warnings } = vueEmit(result, this.vue, this.options.cwd, true)
+ if (errors.length) {
+ throw declarationError([...new Set(errors)])
+ }
+ this.typeErrors.push(...warnings)
+ const selected = new Set(this.vue)
+ const declarations = [...result.declarations].flatMap(([path, source]) => {
+ const vueFile = path.replace(VUE_DECLARATION_RE, '.vue')
+ if (!selected.has(vueFile)) {
+ return []
+ }
+ const fileName = this.outputs.get(vueFile)!.replace(/\.vue$/, path.slice(vueFile.length - '.vue'.length))
+ return [{ fileName, source: this.rewriteSpecifiers(vueFile, fileName, source, true) }]
+ })
+ return [...[...runtime].map(([file, source]) => {
+ const fileName = this.outputs.get(file)!
+ return { fileName, source: this.rewriteSpecifiers(file, fileName, source) }
+ }), ...declarations]
+ }
+
+ private program(tsconfig: TsConfigResult | undefined) {
+ return getOrCreate(this.programs, tsconfig?.path, () => createDeclarationProgram({ cwd: this.options.cwd, tsconfig, paths: this.options.paths }, [...this.scripts, ...this.outside.keys(), ...this.imports ? [this.imports] : []]))
+ }
+
+ /** The program shared by single-file components and TypeScript sources. */
+ private vueProgram() {
+ return this.vueDeclarations ??= (async () => {
+ const tsconfig = this.resolver.root
+ return emitDeclarations([...this.vue, ...[...this.scripts, ...this.outside.keys()].filter(file => TYPESCRIPT_RE.test(file))], {
+ cwd: this.options.cwd,
+ cacheVersion: this.options.cacheVersion,
+ tsconfig: tsconfig && await writeDerivedTsconfig(this.options.cwd, tsconfig, this.options.paths, { vue: true, imports: this.imports }),
+ })
+ })()
+ }
+
+ /**
+ * Declarations for `files`. With single-file components present, TypeScript sources join
+ * their program so that types imported from a component resolve; other scripts get one
+ * program per tsconfig project.
+ */
+ private async emitDeclarations(files: string[]) {
+ const isShared = (file: string) => this.vue.length > 0 && TYPESCRIPT_RE.test(file)
+ const shared = files.filter(isShared)
+ const groups = new Map, string[]>()
+ for (const file of files.filter(file => !isShared(file))) {
+ const program = this.program(this.resolver.resolve(file))
+ groups.set(program, [...groups.get(program) ?? [], file])
+ }
+ const results = shared.length ? [vueEmit(await this.vueProgram(), shared, this.options.cwd, false)] : []
+ for (const [program, groupFiles] of groups) {
+ results.push(await (await program).emit(groupFiles))
+ }
+ for (const [source, text] of results.flatMap(result => [...result.declarations])) {
+ this.declarations.set(source, this.rewriteSpecifiers(source, this.declarationOutput(source), text, true))
+ }
+ const errors = results.flatMap(result => result.errors)
+ if (errors.length) {
+ throw declarationError([...new Set(errors)])
+ }
+ this.typeErrors.push(...results.flatMap(result => result.warnings))
+ }
+
+ private referencedOutside(sources: string[], requested: Set) {
+ const referenced = [...new Set(sources.flatMap(source => [...this.references.get(source) ?? []]))]
+ .filter(target => this.outside.has(target) && !requested.has(target))
+ for (const target of referenced) {
+ requested.add(target)
+ }
+ return referenced
+ }
+}
+
+/**
+ * The declarations of `files` in `result`, keyed by source path, the diagnostics about them,
+ * and an error for each of them without a declaration or an error of its own. With `global`,
+ * errors that name no file are included.
+ */
+function vueEmit(result: VueDeclarations, files: string[], cwd: string, global: boolean) {
+ const { errors, warnings } = result
+ const selected = new Set(files)
+ const about = ({ file }: { file?: string }) => file === undefined ? global : selected.has(file)
+ const declarations = new Map(files.flatMap((file) => {
+ const text = result.declarations.get(declarationPath(file))
+ return text === undefined ? [] : [[file, text] as const]
+ }))
+ return {
+ declarations,
+ errors: [
+ ...errors.filter(about).map(({ message }) => message),
+ ...files.filter(file => !declarations.has(file) && !errors.some(error => error.file === file)).map(file => `${relative(cwd, file)}: no declaration was emitted`),
+ ],
+ warnings: warnings.filter(({ file }) => file !== undefined && selected.has(file)).map(({ message }) => message),
+ }
+}
+
+function stem(path: string) {
+ return path.replace(SCRIPT_RE, '')
+}
+
+const SHOWN_TYPE_ERRORS = 3
+
+function typeErrorsWarning(diagnostics: string[], directory: string) {
+ const hidden = diagnostics.length - SHOWN_TYPE_ERRORS
+ return [
+ `${diagnostics.length} type error${diagnostics.length === 1 ? ' was' : 's were'} reported while generating declarations for \`${directory}\`; the declarations were emitted. If the module's own type check (for example \`nuxt typecheck\` or \`vue-tsc --noEmit\`) passes, these come from build-time aliases typed as \`any\` during declaration generation and can be ignored.`,
+ ...diagnostics.slice(0, SHOWN_TYPE_ERRORS),
+ ...hidden > 0 ? [`... and ${hidden} more`] : [],
+ ].join('\n')
+}
diff --git a/src/rolldown/tsconfig.ts b/src/transpile/tsconfig.ts
similarity index 79%
rename from src/rolldown/tsconfig.ts
rename to src/transpile/tsconfig.ts
index 859749a3..945e5a7d 100644
--- a/src/rolldown/tsconfig.ts
+++ b/src/transpile/tsconfig.ts
@@ -3,10 +3,11 @@ import { existsSync } from 'node:fs'
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { createFilesMatcher, createPathsMatcher, getTsconfig, parseTsconfig } from 'get-tsconfig'
import type { TsConfigResult } from 'get-tsconfig'
-import { dirname, isAbsolute, join, relative, resolve } from 'pathe'
+import { dirname, join, relative, resolve } from 'pathe'
import type ts from 'typescript'
-import { moduleSpecifiers } from './resolve.ts'
+import { findPackageDir, isInside, NODE_MODULES_RE } from '../utils.ts'
+import { moduleSpecifiers } from './specifiers.ts'
export interface TsconfigResolver {
/** The nearest tsconfig, which may delegate files to `references`. */
@@ -18,28 +19,24 @@ export interface TsconfigResolver {
}
/**
- * Finds the nearest tsconfig above `dir`, or reads `file`. When it has `references`, each
+ * Finds the nearest tsconfig above `dir`. When it has `references`, each
* source file is compiled with the referenced project that includes it, falling back to
* the tsconfig itself. A tsconfig whose generated types come from a `.nuxt` other than
* `dir`'s own (a playground's, typically) is rebuilt on `dir/.nuxt/tsconfig.json`, see
* {@link rebaseOnOwnBuildDir}.
*/
-export async function createTsconfigResolver(dir: string, file?: string): Promise {
- const path = file && resolve(dir, file)
- let root = path ? { path, config: parseTsconfig(path) } : getTsconfig(dir) ?? undefined
+export async function createTsconfigResolver(dir: string): Promise {
+ let root = getTsconfig(dir) ?? undefined
let replaced: string | undefined
const own = join(dir, '.nuxt/tsconfig.json')
- if (root && !path && usesForeignBuildDir(root, dir) && existsSync(own)) {
+ if (root && usesForeignBuildDir(root, dir) && existsSync(own)) {
replaced = root.path
root = await rebaseOnOwnBuildDir(root.path, own, dir)
}
const projects = allReferencedProjects(root).map(project => ({ project, matches: createFilesMatcher(project) }))
-
- const scriptPath = (file: string) => file.endsWith('.vue') ? `${file}.ts` : file
-
return {
root,
- resolve: file => projects.find(({ matches }) => matches(scriptPath(file)))?.project ?? root,
+ resolve: file => projects.find(({ matches }) => matches(file.endsWith('.vue') ? `${file}.ts` : file))?.project ?? root,
...replaced && { replaced },
}
}
@@ -47,17 +44,27 @@ export async function createTsconfigResolver(dir: string, file?: string): Promis
function usesForeignBuildDir(tsconfig: TsConfigResult, dir: string) {
const targets = Object.values(tsconfigPaths(tsconfig)).flat()
const projects = allReferencedProjects(tsconfig).map(project => project.path)
- return [...targets, ...projects].some(file => NUXT_BUILD_DIR_RE.test(file) && !isOwnBuildFile(file, dir))
+ return [...targets, ...projects].some(file => isForeignBuildFile(file, dir))
}
function isOwnBuildFile(file: string, dir: string) {
- return !relative(join(dir, '.nuxt'), file).startsWith('..')
+ return isInside(join(dir, '.nuxt'), file)
}
function isForeignBuildFile(file: string, dir: string) {
return NUXT_BUILD_DIR_RE.test(file) && !isOwnBuildFile(file, dir)
}
+/** The package a bare specifier names, or `undefined` for an alias or a specifier with a protocol. */
+function packageName(specifier: string) {
+ return specifier.startsWith('#') || /^[~@]\//.test(specifier) || specifier.includes(':') ? undefined : specifier.match(PACKAGE_NAME_RE)?.[0]
+}
+
+function parseProject(ts: typeof import('typescript'), path: string, vue: boolean) {
+ const extraFileExtensions = vue ? [{ extension: 'vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }] : undefined
+ return ts.getParsedCommandLineOfConfigFile(path, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }, undefined, undefined, extraFileExtensions)
+}
+
const PATH_OPTIONS = ['baseUrl', 'rootDir', 'outDir', 'declarationDir', 'tsBuildInfoFile'] as const
const PATH_LIST_OPTIONS = ['rootDirs', 'typeRoots'] as const
@@ -69,7 +76,6 @@ const PATH_LIST_OPTIONS = ['rootDirs', 'typeRoots'] as const
*/
async function rebaseOnOwnBuildDir(tsconfig: string, own: string, dir: string): Promise {
const { default: ts } = await import('typescript')
- const read = (file: string) => ts.readConfigFile(file, ts.sys.readFile).config as RawTsconfig | undefined
const ownConfig = parseTsconfig(own)
const ownPaths = tsconfigPaths({ path: own, config: ownConfig })
const { paths, types, ...options } = (await inheritedTsconfig(tsconfig, target => isForeignBuildFile(target, dir))).compilerOptions
@@ -82,7 +88,7 @@ async function rebaseOnOwnBuildDir(tsconfig: string, own: string, dir: string):
...(ownTypes || types) ? { types: [...new Set([...ownTypes ?? [], ...(types ?? []) as string[]])] } : {},
},
}
- const references = (read(tsconfig)?.references ?? [])
+ const references = ((ts.readConfigFile(tsconfig, ts.sys.readFile).config as RawTsconfig | undefined)?.references ?? [])
.map(reference => ({ path: resolve(dirname(tsconfig), reference.path) }))
.filter(reference => !isForeignBuildFile(reference.path, dir))
const file = await writeCached(dir, '.json', JSON.stringify({ ...config, ...references.length && { references } }))
@@ -175,11 +181,7 @@ export function projectFiles(parsed: ts.ParsedCommandLine | undefined, dir: stri
/** Whether `file` belongs to the module in `dir`, as {@link projectFiles} decides. */
export function isModuleFile(file: string, dir: string): boolean {
- const path = relative(dir, file)
- if (path.startsWith('..') || isAbsolute(path) || FOREIGN_DIR_RE.test(path.split('/')[0]!) || NODE_MODULES_RE.test(file)) {
- return false
- }
- return !NUXT_BUILD_DIR_RE.test(file) || isOwnBuildFile(file, dir)
+ return isInside(dir, file) && !FOREIGN_DIR_RE.test(relative(dir, file).split('/')[0]!) && !NODE_MODULES_RE.test(file) && !isForeignBuildFile(file, dir)
}
/**
@@ -211,20 +213,20 @@ function allReferencedProjects(tsconfig: TsConfigResult | undefined, seen = new
}).sort((a, b) => projectRank(a.path) - projectRank(b.path))
}
+export function hasIsolatedDeclarations(tsconfig: TsConfigResult | undefined): boolean {
+ return tsconfig?.config.compilerOptions?.isolatedDeclarations === true
+}
+
/** The tsconfig's `paths` made absolute. */
export function tsconfigPaths(tsconfig: TsConfigResult | undefined): Record {
const paths = tsconfig?.config.compilerOptions?.paths
- const matchPath = tsconfig && createPathsMatcher(tsconfig)
- if (!paths || !matchPath) {
- return {}
- }
- return Object.fromEntries(Object.keys(paths).map(alias => [alias, matchPath(alias)]))
+ const matchPath = paths && createPathsMatcher(tsconfig!)
+ return matchPath ? Object.fromEntries(Object.keys(paths).map(alias => [alias, matchPath(alias)])) : {}
}
const BUILD_ALIAS_RE = /^#(?:build|internal)(?:\/|$)/
const SERVER_ROUTES_ALIAS = '#build/server-routes'
const NUXT_BUILD_DIR_RE = /[\\/]\.nuxt(?:[\\/]|$)/
-const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
const PACKAGE_NAME_RE = /^(?:@[\w.-]+\/)?[\w.-]+/
export interface DeclarationPaths {
@@ -251,7 +253,7 @@ export function declarationPaths(paths: Record, cwd: string):
result.ambient.push(alias)
continue
}
- const name = /^[#~@]\//.test(alias) || alias.startsWith('#') ? undefined : alias.match(PACKAGE_NAME_RE)?.[0]
+ const name = packageName(alias)
if (name && targets.every(target => NODE_MODULES_RE.test(target)) && findPackageDir(name, cwd)) {
continue
}
@@ -261,26 +263,9 @@ export function declarationPaths(paths: Record, cwd: string):
}
function serverRoutesTable(paths: Record, cwd: string) {
- const targets = [...paths[SERVER_ROUTES_ALIAS] ?? [], ...(paths['#build/*'] ?? []).map(target => target.replaceAll('*', 'server-routes'))]
- for (const target of targets) {
- const file = target.endsWith('.d.ts') ? target : `${target}.d.ts`
- if (isOwnBuildFile(file, cwd) && existsSync(file)) {
- return file
- }
- }
-}
-
-/** The directory of an installed package, found the way Node looks up `node_modules`. */
-export function findPackageDir(name: string, cwd: string): string | undefined {
- for (let dir = cwd; ; dir = dirname(dir)) {
- const packageDir = join(dir, 'node_modules', name)
- if (existsSync(join(packageDir, 'package.json'))) {
- return packageDir
- }
- if (dirname(dir) === dir) {
- return
- }
- }
+ return [...paths[SERVER_ROUTES_ALIAS] ?? [], ...(paths['#build/*'] ?? []).map(target => target.replaceAll('*', 'server-routes'))]
+ .map(target => target.endsWith('.d.ts') ? target : `${target}.d.ts`)
+ .find(file => isOwnBuildFile(file, cwd) && existsSync(file))
}
const cacheDir = (cwd: string) => join(cwd, 'node_modules/.cache/transpile-dir')
@@ -295,10 +280,7 @@ function cachedPath(cwd: string, extension: string, contents: string) {
*/
async function writeCached(cwd: string, extension: string, contents: string) {
const file = cachedPath(cwd, extension, contents)
- if (existsSync(file)) {
- return file
- }
- return writeAtomic(file, contents)
+ return existsSync(file) ? file : writeAtomic(file, contents)
}
/** A path in the cache directory that keeps its name whatever is written to it. */
@@ -319,9 +301,18 @@ async function writeAtomic(file: string, contents: string) {
return file
}
-/** An ambient declaration file declaring each alias as a module. */
-export function writeAmbientModules(cwd: string, ambient: string[]): Promise {
- return writeCached(cwd, '.d.ts', ambient.map(alias => `declare module '${alias}'\n`).join(''))
+/**
+ * The {@link declarationPaths} of the `paths` of `tsconfig` plus `paths`, once the files they
+ * rely on are written: the server routes stub, and the `ambient` file that declares each alias
+ * left out as a module.
+ */
+export async function writeDeclarationPaths(cwd: string, tsconfig: TsConfigResult | undefined, paths: Record): Promise<{ paths: Record, ambient?: string }> {
+ const declaration = declarationPaths({ ...tsconfigPaths(tsconfig), ...paths }, cwd)
+ await writeServerRoutesStub(cwd)
+ return {
+ paths: declaration.paths,
+ ...declaration.ambient.length && { ambient: await writeCached(cwd, '.d.ts', declaration.ambient.map(alias => `declare module '${alias}'\n`).join('')) },
+ }
}
/**
@@ -375,14 +366,12 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu
return
}
const { default: ts } = await import('typescript')
- const extraFileExtensions = [{ extension: 'vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }]
- const host = { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }
- const files = new Set(projects.flatMap(project => projectFiles(ts.getParsedCommandLineOfConfigFile(project.path, {}, host, undefined, undefined, extraFileExtensions), cwd)))
+ const files = new Set(projects.flatMap(project => projectFiles(parseProject(ts, project.path, true), cwd)))
const sources = await Promise.all([...files].sort().map(file => readFile(file, 'utf8').catch(() => '')))
const specifiers = new Map()
for (const source of sources) {
for (const { specifier } of moduleSpecifiers(source)) {
- const name = /^[#~@]\//.test(specifier) || specifier.startsWith('#') || specifier.includes(':') ? undefined : specifier.match(PACKAGE_NAME_RE)?.[0]
+ const name = packageName(specifier)
if (name && !specifiers.has(name) && findPackageDir(name, cwd)) {
specifiers.set(name, specifier)
}
@@ -401,35 +390,27 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu
* With `vue`, single-file components are listed too. `imports` (see {@link writeDependencyImports})
* is listed in each derived tsconfig that lists files of its own.
*/
-export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult | undefined, paths: Record, { file, vue, imports }: { file?: string, vue?: boolean, imports?: string } = {}): Promise {
- const declaration = declarationPaths({ ...tsconfigPaths(tsconfig), ...paths }, cwd)
- await writeServerRoutesStub(cwd)
+export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult, paths: Record, { file, vue = false, imports }: { file?: string, vue?: boolean, imports?: string } = {}): Promise {
+ const { default: ts } = await import('typescript')
+ const declaration = await writeDeclarationPaths(cwd, tsconfig, paths)
const compilerOptions: Record = { paths: declaration.paths, isolatedDeclarations: false }
- if (declaration.ambient.length) {
+ if (declaration.ambient) {
compilerOptions.types = [
- ...tsconfig?.config.compilerOptions?.types ?? await automaticTypes(tsconfig, cwd),
- await writeAmbientModules(cwd, declaration.ambient),
+ ...tsconfig.config.compilerOptions?.types ?? ts.getAutomaticTypeDirectiveNames({
+ configFilePath: tsconfig.path,
+ typeRoots: tsconfig.config.compilerOptions?.typeRoots?.map(root => resolve(dirname(tsconfig.path), root)),
+ }, ts.sys),
+ declaration.ambient,
]
}
const references = await Promise.all(referencedProjects(tsconfig).map(async project => ({ path: await writeDerivedTsconfig(cwd, project, paths, { vue, imports }) })))
- const { default: ts } = await import('typescript')
- const extraFileExtensions = vue ? [{ extension: 'vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }] : undefined
- const parsed = tsconfig && ts.getParsedCommandLineOfConfigFile(tsconfig.path, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }, undefined, undefined, extraFileExtensions)
- const files = projectFiles(parsed, cwd)
+ const files = projectFiles(parseProject(ts, tsconfig.path, vue), cwd)
const contents = JSON.stringify({
- ...tsconfig && { extends: tsconfig.path },
- ...tsconfig && { files: [...files, ...imports && files.length ? [imports] : []].map(file => relative(cacheDir(cwd), file)), include: [] },
+ extends: tsconfig.path,
+ files: [...files, ...imports && files.length ? [imports] : []].map(file => relative(cacheDir(cwd), file)),
+ include: [],
compilerOptions,
...references.length && { references },
})
return file ? writeAtomic(file, contents) : writeCached(cwd, '.json', contents)
}
-
-async function automaticTypes(tsconfig: TsConfigResult | undefined, cwd: string) {
- const { default: ts } = await import('typescript')
- const base = tsconfig ? dirname(tsconfig.path) : cwd
- return ts.getAutomaticTypeDirectiveNames({
- configFilePath: tsconfig?.path ?? join(cwd, 'tsconfig.json'),
- typeRoots: tsconfig?.config.compilerOptions?.typeRoots?.map(root => resolve(base, root)),
- }, ts.sys)
-}
diff --git a/src/rolldown/vue.ts b/src/transpile/vue.ts
similarity index 80%
rename from src/rolldown/vue.ts
rename to src/transpile/vue.ts
index 214dd3df..1c3dbc69 100644
--- a/src/rolldown/vue.ts
+++ b/src/transpile/vue.ts
@@ -1,20 +1,13 @@
import { readFile } from 'node:fs/promises'
import { relative } from 'pathe'
-import type { DeclarationDiagnostic, DtsCache, Transform } from 'vue-sfc-transformer/core'
+import type { DeclarationDiagnostic, Transform } from 'vue-sfc-transformer/core'
-export interface VueOptions {
- /** Extra key for the declaration cache, for inputs the cache cannot see, such as generated type augmentations. */
- cacheVersion?: string
- /** The declaration cache, or `false` to disable it. Defaults to `node_modules/.cache/vue-sfc-dts`. */
- cache?: DtsCache | false
- /** Also emit each declaration as `.vue.d.ts`, the file name older toolchains resolve. Defaults to `true`. */
- emitLegacyDeclarationAlias?: boolean
-}
-
-export interface VueDeclarationOptions extends VueOptions {
+interface VueDeclarationOptions {
cwd: string
/** The tsconfig to emit declarations from. */
tsconfig?: string
+ /** Extra key for the declaration cache, for inputs the cache cannot see, such as generated type augmentations. */
+ cacheVersion: string
}
interface DeclarationMessage {
@@ -25,7 +18,7 @@ interface DeclarationMessage {
}
export interface VueDeclarations {
- /** Declarations keyed by the path next to their source: `Foo.d.vue.ts` and, by default, `Foo.vue.d.ts`; `foo.d.ts` for a script. */
+ /** Declarations keyed by the path next to their source: `Foo.d.vue.ts` and `Foo.vue.d.ts`; `foo.d.ts` for a script. */
declarations: Map
/** Diagnostics that prevent correct declarations. */
errors: DeclarationMessage[]
@@ -34,7 +27,7 @@ export interface VueDeclarations {
}
/** Transforms `.vue` files into their runtime form with TypeScript stripped, keyed by source path. */
-export async function transformVueRuntime(files: string[], transform?: Transform): Promise> {
+export async function transformVueRuntime(files: string[], transform: Transform): Promise> {
const { transformVueSfc } = await import('vue-sfc-transformer/core')
return new Map(await Promise.all(files.map(async (id) => {
const { code } = await transformVueSfc(await readFile(id, 'utf8'), id, { transform })
@@ -52,9 +45,8 @@ export async function emitDeclarations(files: string[], options: VueDeclarationO
const { files: declarations, diagnostics } = await emitVueDeclarations(sources, {
cwd: options.cwd,
tsconfig: options.tsconfig,
- cache: options.cache,
cacheVersion: options.cacheVersion,
- emitLegacyDeclarationAlias: options.emitLegacyDeclarationAlias ?? true,
+ emitLegacyDeclarationAlias: true,
})
const errors = diagnostics.filter(diagnostic => diagnostic.category === 'error')
const format = (diagnostic: DeclarationDiagnostic): DeclarationMessage => ({ file: diagnostic.file, message: formatDiagnostic(diagnostic, options.cwd) })
diff --git a/src/tsdown/build.ts b/src/tsdown/build.ts
index dbee1481..8cae8c7d 100644
--- a/src/tsdown/build.ts
+++ b/src/tsdown/build.ts
@@ -3,6 +3,7 @@ import type { TsdownPlugin } from 'tsdown'
import { findTsdownConfig, hasBuilder, missingBuilderError } from '../commands/config-file.ts'
import { assertLoadableModuleCode } from '../build/loader.ts'
+import { loadLegacyModuleConfig } from '../legacy/build-config.ts'
import { createBuilder } from './plugin.ts'
export interface BuildOptions {
@@ -24,7 +25,7 @@ export async function build(cwd: string, options: BuildOptions): Promise {
config: file ?? false,
...options.outDir !== undefined && { outDir: options.outDir },
...options.sourcemap !== undefined && { sourcemap: options.sourcemap },
- plugins: file ? [requireBuilder(file)] : [createBuilder({}, { legacy: true })],
+ plugins: file ? [requireBuilder(file)] : [createBuilder({}, { loadConfig: loadLegacyModuleConfig })],
})
}
diff --git a/src/tsdown/externals.ts b/src/tsdown/externals.ts
index 0b72b920..82fa5978 100644
--- a/src/tsdown/externals.ts
+++ b/src/tsdown/externals.ts
@@ -1,12 +1,14 @@
-import { isAbsolute } from 'pathe'
+import { isAbsolute, join, normalize, relative } from 'pathe'
import type { Rolldown } from 'tsdown'
-const DECLARATION_RE = /\.d\.[cm]?ts$/
-const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
+import { rewriteAppAliases } from '../build/aliases.ts'
+import { scriptExtension } from '../transpile/specifiers.ts'
+import { DECLARATION_RE, isInside, NODE_MODULES_RE, probe, relativeSpecifier, SCRIPT_RE } from '../utils.ts'
/**
* Keeps declaration imports of installed packages external, whether or not the package
- * is a dependency. Aliases that resolve into the module's own source are bundled.
+ * is a dependency. Aliases that resolve into the module's own source are bundled, and
+ * `#app` aliases are written as `nuxt/app`.
*/
export function externalDependencyDeclarations(): Rolldown.Plugin {
return {
@@ -26,5 +28,87 @@ export function externalDependencyDeclarations(): Rolldown.Plugin {
}
},
},
+ renderChunk(code, chunk) {
+ if (DECLARATION_RE.test(chunk.fileName)) {
+ const rewritten = rewriteAppAliases(code)
+ return rewritten === code ? undefined : { code: rewritten, map: null }
+ }
+ },
+ }
+}
+
+export interface RuntimeExternalsOptions {
+ /** Absolute path of the build's output directory. */
+ outDir: string
+ /** The directories transpiled file by file, with their absolute source and output paths. */
+ directories: Array<{ srcDir: string, outDir: string, ext: 'js' | 'mjs' }>
+ /** The module's own package name, so self-referencing imports are caught. */
+ packageName?: string
+ /** Whether a JSX source is emitted with its JSX preserved, as `.jsx`. Defaults to always. */
+ preserveJsx?: (file: string) => boolean
+}
+
+/**
+ * Rewrites imports of the module's runtime tree to the absolute paths they will occupy
+ * in `dist/`, and marks them external so the runtime tree is never inlined into the
+ * bundled module entry. The build has to set `makeAbsoluteExternalsRelative: false`:
+ * the specifiers are made relative to each chunk's own location when it is rendered.
+ *
+ * `this.resolve()` is used rather than pattern-matching the specifier so that
+ * tsconfig path aliases resolving into `src/runtime/` are handled too.
+ */
+export function runtimeExternals({ outDir, directories, packageName, preserveJsx = () => true }: RuntimeExternalsOptions): Rolldown.Plugin {
+ const selfPrefix = packageName ? `${packageName}/` : undefined
+ const distSubpath = (subpath: string, { srcDir, ext }: { srcDir: string, ext: string }) => {
+ const source = probe(join(srcDir, subpath))
+ if (source && SCRIPT_RE.test(source)) {
+ return relative(srcDir, source).replace(SCRIPT_RE, scriptExtension(source, `.${ext}`, preserveJsx(source)))
+ }
+ if (source || subpath.endsWith('.vue')) {
+ return subpath
+ }
+ return `${subpath.replace(SCRIPT_RE, '')}.${ext}`
+ }
+
+ return {
+ name: 'nuxt-module-builder:runtime-externals',
+ async resolveId(id, importer) {
+ if (selfPrefix && id.startsWith(selfPrefix)) {
+ const target = join(outDir, id.slice(selfPrefix.length))
+ const directory = directories.find(directory => target !== directory.outDir && isInside(directory.outDir, target))
+ if (directory) {
+ return { id: join(directory.outDir, distSubpath(relative(directory.outDir, target), directory)), external: true }
+ }
+ }
+
+ if (!importer) {
+ return
+ }
+
+ const resolved = await this.resolve(id, importer, { skipSelf: true })
+ if (!resolved || resolved.external) {
+ return
+ }
+
+ const file = normalize(resolved.id)
+ const directory = directories.find(directory => file !== directory.srcDir && isInside(directory.srcDir, file))
+ if (directory) {
+ return { id: join(directory.outDir, distSubpath(relative(directory.srcDir, file), directory)), external: true }
+ }
+ },
+ renderChunk(code, chunk, { dir }) {
+ if (!dir) {
+ return
+ }
+ const chunkFile = join(dir, chunk.fileName)
+ let result = code
+ for (const id of new Set([...chunk.imports, ...chunk.dynamicImports])) {
+ if (!directories.some(directory => id.startsWith(`${directory.outDir}/`))) {
+ continue
+ }
+ result = result.replaceAll(JSON.stringify(id), JSON.stringify(relativeSpecifier(chunkFile, id)))
+ }
+ return result === code ? undefined : { code: result, map: null }
+ },
}
}
diff --git a/src/tsdown/index.ts b/src/tsdown/index.ts
index cedb3ab3..59510c28 100644
--- a/src/tsdown/index.ts
+++ b/src/tsdown/index.ts
@@ -1,3 +1,3 @@
export { builder } from './plugin.ts'
export type { BuilderPlugin } from './plugin.ts'
-export type { BuilderEntry, BuilderOptions, ReplaceOptions } from '../build/build-config.ts'
+export type { BuilderEntry, BuilderOptions, ReplaceOptions } from '../build/options.ts'
diff --git a/src/tsdown/plugin.ts b/src/tsdown/plugin.ts
index 9c4e052e..de564d8d 100644
--- a/src/tsdown/plugin.ts
+++ b/src/tsdown/plugin.ts
@@ -1,7 +1,7 @@
import type { TsdownPlugin } from 'tsdown'
-import { BUILDER_OPTIONS } from '../build/build-config.ts'
-import type { BuilderOptions } from '../build/build-config.ts'
+import { BUILDER_OPTIONS } from '../build/options.ts'
+import type { BuilderOptions } from '../build/options.ts'
import type { BuilderSession, SetupOptions } from './setup.ts'
export interface BuilderPlugin extends TsdownPlugin {
@@ -27,7 +27,7 @@ export interface BuilderPlugin extends TsdownPlugin {
* them out apart from additional `deps.neverBundle` entries.
*/
export function builder(options: BuilderOptions = {}): BuilderPlugin {
- return createBuilder(options, { legacy: false })
+ return createBuilder(options, {})
}
export function createBuilder(options: BuilderOptions, setupOptions: SetupOptions): BuilderPlugin {
diff --git a/src/tsdown/replace.ts b/src/tsdown/replace.ts
deleted file mode 100644
index ea0f93d0..00000000
--- a/src/tsdown/replace.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { pathToFileURL } from 'node:url'
-import { resolvePath } from 'mlly'
-import type { Rolldown } from 'tsdown'
-
-import type { ReplaceOptions } from '../build/build-config.ts'
-
-/**
- * rolldown's built-in replace plugin. It is loaded from the copy of rolldown that
- * tsdown runs, because built-in plugins only work with the binding that created them.
- */
-export async function replacePlugin({ values, ...options }: ReplaceOptions): Promise {
- const tsdown = await resolvePath('tsdown', { url: import.meta.url })
- const plugins = await resolvePath('rolldown/plugins', { url: tsdown })
- const { replacePlugin } = await import(pathToFileURL(plugins).href) as { replacePlugin: (values: Record, options: Omit) => Rolldown.RolldownPluginOption }
- return replacePlugin(values, options)
-}
diff --git a/src/tsdown/report.ts b/src/tsdown/report.ts
index 4265ea61..62fb1340 100644
--- a/src/tsdown/report.ts
+++ b/src/tsdown/report.ts
@@ -1,9 +1,8 @@
import { relative } from 'pathe'
import type { Rolldown, UserConfig } from 'tsdown'
-import type { DirectoryEntry } from '../build/build-config.ts'
-
-const DECLARATION_RE = /\.d\.(?:[^/]+\.)?[cm]?ts$/
+import type { DirectoryEntry } from '../build/options.ts'
+import { ANY_DECLARATION_RE } from '../utils.ts'
/**
* tsdown's size report, unless the config sets `report`: a summary when the build has
@@ -47,7 +46,7 @@ export function sizeBreakdown(bundle: Rolldown.OutputBundle, { cwd, outDir, entr
for (const prefix of prefixes) {
const files = sizes.filter(output => output.asset && !entryFiles.has(output.fileName) && owner(output.fileName) === prefix)
if (files.length) {
- const total = (declarations: boolean) => files.filter(output => DECLARATION_RE.test(output.fileName) === declarations).reduce((sum, output) => sum + output.size, 0)
+ const total = (declarations: boolean) => files.filter(output => ANY_DECLARATION_RE.test(output.fileName) === declarations).reduce((sum, output) => sum + output.size, 0)
rows.push([`${base}/${prefix}`, `${formatSize(total(false))} · types ${formatSize(total(true))} · ${files.length} files`])
}
}
diff --git a/src/tsdown/runtime-externals.ts b/src/tsdown/runtime-externals.ts
deleted file mode 100644
index f1d79049..00000000
--- a/src/tsdown/runtime-externals.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { dirname, isAbsolute, join, normalize, relative } from 'pathe'
-import type { Rolldown } from 'tsdown'
-
-import { probe, SCRIPT_RE, scriptExtension } from '../rolldown/resolve.ts'
-
-export interface RuntimeExternalsOptions {
- /** Absolute path of the build's output directory. */
- outDir: string
- /** The directories transpiled file by file, with their absolute source and output paths. */
- directories: Array<{ srcDir: string, outDir: string, ext: 'js' | 'mjs' }>
- /** The module's own package name, so self-referencing imports are caught. */
- packageName?: string
- /** Whether a JSX source is emitted with its JSX preserved, as `.jsx`. Defaults to always. */
- preserveJsx?: (file: string) => boolean
-}
-
-/**
- * Rewrites imports of the module's runtime tree to the absolute paths they will occupy
- * in `dist/`, and marks them external so the runtime tree is never inlined into the
- * bundled module entry. The build has to set `makeAbsoluteExternalsRelative: false`:
- * the specifiers are made relative to each chunk's own location when it is rendered.
- *
- * `this.resolve()` is used rather than pattern-matching the specifier so that
- * tsconfig path aliases resolving into `src/runtime/` are handled too.
- */
-export function runtimeExternals({ outDir, directories, packageName, preserveJsx = () => true }: RuntimeExternalsOptions): Rolldown.Plugin {
- const selfPrefix = packageName ? `${packageName}/` : undefined
- const distSubpath = (subpath: string, { srcDir, ext }: { srcDir: string, ext: string }) => {
- const source = probe(join(srcDir, subpath))
- if (source && SCRIPT_RE.test(source)) {
- return relative(srcDir, source).replace(SCRIPT_RE, scriptExtension(source, `.${ext}`, preserveJsx(source)))
- }
- if (source || subpath.endsWith('.vue')) {
- return subpath
- }
- return `${subpath.replace(SCRIPT_RE, '')}.${ext}`
- }
-
- return {
- name: 'nuxt-module-builder:runtime-externals',
- async resolveId(id, importer) {
- if (selfPrefix && id.startsWith(selfPrefix)) {
- const target = join(outDir, id.slice(selfPrefix.length))
- for (const directory of directories) {
- const subpath = relative(directory.outDir, target)
- if (subpath && !subpath.startsWith('..') && !isAbsolute(subpath)) {
- return { id: join(directory.outDir, distSubpath(subpath, directory)), external: true }
- }
- }
- }
-
- if (!importer) {
- return
- }
-
- const resolved = await this.resolve(id, importer, { skipSelf: true })
- if (!resolved || resolved.external) {
- return
- }
-
- for (const directory of directories) {
- const subpath = relative(directory.srcDir, normalize(resolved.id))
- if (subpath && !subpath.startsWith('..') && !isAbsolute(subpath)) {
- return { id: join(directory.outDir, distSubpath(subpath, directory)), external: true }
- }
- }
- },
- renderChunk(code, chunk, { dir }) {
- if (!dir) {
- return
- }
- const chunkDir = dirname(join(dir, chunk.fileName))
- let result = code
- for (const id of new Set([...chunk.imports, ...chunk.dynamicImports])) {
- if (!directories.some(directory => id.startsWith(`${directory.outDir}/`))) {
- continue
- }
- const specifier = relative(chunkDir, id)
- result = result.replaceAll(JSON.stringify(id), JSON.stringify(specifier.startsWith('.') ? specifier : `./${specifier}`))
- }
- return result === code ? undefined : { code: result, map: null }
- },
- }
-}
diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts
index 06155524..fe6db252 100644
--- a/src/tsdown/setup.ts
+++ b/src/tsdown/setup.ts
@@ -1,32 +1,32 @@
import { existsSync, readdirSync } from 'node:fs'
import { rm } from 'node:fs/promises'
-import { dirname, relative, resolve } from 'pathe'
+import { pathToFileURL } from 'node:url'
+import { relative, resolve } from 'pathe'
import { consola } from 'consola'
+import { resolvePath } from 'mlly'
import { readPackageJSON } from 'pkg-types'
+import type { PackageJson } from 'pkg-types'
import type { InlineConfig, ResolvedConfig, Rolldown, UserConfig } from 'tsdown'
import { analyseSources, finishBuild, onBuildError, prepareBuild, preservesJsx, resolveBuild, resolveDirectoryExternal } from '../build/build.ts'
-import type { BuildPlan } from '../build/build.ts'
-import { assertNoLegacyBuildConfig, loadBuildConfig, resolveModuleOptions, resolveOutDir } from '../build/build-config.ts'
-import type { BuilderOptions } from '../build/build-config.ts'
import { guide } from '../build/guide.ts'
import { loadOxc } from '../build/loader.ts'
+import { resolveModuleOptions, resolveOutDir } from '../build/options.ts'
+import type { BuilderOptions, ModuleConfig, ReplaceOptions } from '../build/options.ts'
import { sourcePathsPackError, unpublishablePathsError } from '../build/package.ts'
import { prepareModule } from '../commands/prepare.ts'
-import { transpileDir, TYPE_ERRORS_WARNING } from '../rolldown/transpile-dir.ts'
-import { externalDependencyDeclarations } from './externals.ts'
-import { replacePlugin } from './replace.ts'
+import { transpileDir, TYPE_ERRORS_WARNING } from '../transpile/transpile-dir.ts'
+import { findUp, realpath } from '../utils.ts'
+import { externalDependencyDeclarations, runtimeExternals } from './externals.ts'
import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts'
-import { runtimeExternals } from './runtime-externals.ts'
import { unchangedOutputs } from './unchanged.ts'
export interface SetupOptions {
- /** Read `build.config.*` and `package.json`'s `build` or `unbuild` field. */
- legacy: boolean
+ /** Loads the module's options from elsewhere than `builder()`. */
+ loadConfig?: (cwd: string, pkg: PackageJson, outDir: string) => Promise
}
export interface BuilderSession {
- plan: BuildPlan
/** Whether a build has started with this session. */
started: boolean
/** Directories a watcher watches as a whole, so new files in them trigger a rebuild. */
@@ -66,7 +66,7 @@ const FORBIDDEN: Array<[option: string, isSet: (config: UserConfig) => boolean,
* Resolves the module build for `config`, fills in the tsdown options it depends on and
* adds the plugins and hooks that build the module.
*/
-export async function setupBuilder(config: UserConfig, inline: InlineConfig, options: BuilderOptions, { legacy }: SetupOptions): Promise {
+export async function setupBuilder(config: UserConfig, inline: InlineConfig, options: BuilderOptions, { loadConfig }: SetupOptions): Promise {
const forbidden = FORBIDDEN.filter(([, isSet]) => isSet(config))
if (forbidden.length) {
throw new Error([
@@ -76,7 +76,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt
].join('\n'))
}
- const cwd = resolve(config.cwd ?? process.cwd())
+ const cwd = realpath(config.cwd ?? process.cwd())
const pkg = await readPackageJSON(cwd)
const packageError = sourcePathsPackError(cwd, pkg) ?? unpublishablePathsError(cwd, pkg)
if (packageError) {
@@ -84,28 +84,26 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt
}
const outDirOption = config.outDir ?? 'dist'
const outDir = resolveOutDir(cwd, outDirOption, inline.outDir === undefined && config.outDir !== undefined ? `outDir: '${outDirOption}'` : `--outDir ${outDirOption}`)
- if (!legacy) {
- assertNoLegacyBuildConfig(cwd, pkg)
- }
- const buildConfig = legacy ? await loadBuildConfig(cwd, pkg, outDir) : resolveModuleOptions(cwd, pkg, outDir, options)
+ const buildConfig = loadConfig ? await loadConfig(cwd, pkg, outDir) : resolveModuleOptions(cwd, pkg, outDir, options)
if (!existsSync(resolve(cwd, '.nuxt/tsconfig.json'))) {
consola.info(`\`.nuxt\` not found, running \`nuxt-module-build prepare\` first. Add it to the module's \`dev:prepare\` script to skip this step. ${guide('preparing-nuxt')}`)
- await prepareModule(cwd, { config: buildConfig, outDir })
+ await prepareModule(cwd, { config: buildConfig, outDir, pkg })
}
- const plan = await resolveBuild({ cwd, pkg, outDir, sourcemap: !!config.sourcemap, loadConfig: async () => buildConfig })
+ const plan = await resolveBuild({ cwd, pkg, outDir, sourcemap: !!config.sourcemap, config: buildConfig })
const directoryPlugins = plan.directories.map(directory => transpileDir({
cwd,
srcDir: directory.srcDir,
outBase: relative(outDir, directory.outDir),
extension: directory.ext,
paths: plan.directoryPaths,
- transform: loadOxc()?.transform,
+ transform: loadOxc()!.transform,
sourcemap: plan.sourcemap,
- vue: { cacheVersion: plan.generatedTypesHash },
+ cacheVersion: plan.generatedTypesHash,
jsx: file => preservesJsx(plan, file) ? 'preserve' : { runtime: 'automatic', importSource: 'vue' },
- resolveExternal: resolveDirectoryExternal(plan, directory),
+ resolveExternal: resolveDirectoryExternal(plan),
+ reserved: [...Object.keys(plan.entries), 'types'],
}))
let watch = false
@@ -140,6 +138,8 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt
const dts = {
tsconfig: plan.declarationTsconfig,
generator: plan.isolatedDeclarations ? 'oxc' : 'tsc',
+ // `eager` puts every file of the tsconfig in the program, so ambient declarations such
+ // as `.nuxt/nuxt.d.ts` apply and inferred types can be named by their package.
// TODO: allow the parallel worker while watching once https://github.com/sxzz/rolldown-plugin-dts/pull/365 is released.
// The worker inherits stdin, which tsdown reads while watching, and on Windows it then blocks at startup.
tsc: { eager: true, parallel: !config.watch },
@@ -193,7 +193,6 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt
} satisfies UserConfig)
const session: BuilderSession = {
- plan,
started: false,
watchDirs: [...new Set(plan.runtimeDirs.map(dir => existingAncestor(dir, cwd)))],
checkResolved(resolved) {
@@ -253,18 +252,27 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt
}
}
const outputs = await Promise.all(directoryPlugins.map(plugin => plugin.api.outputs))
- if (keptOutput) {
- plan.writesTypes ??= !Object.hasOwn(bundle, 'types.d.mts')
- }
await finishBuild(plan, {
outputs: outputs.flatMap(map => [...map.values()]),
builder: { tsdown: await readPackageJSON('tsdown', { from: import.meta.url }).then(r => r.version || 'unknown').catch(() => 'unknown') },
+ keepOutput: watch,
})
},
}
return session
}
+/**
+ * rolldown's built-in replace plugin. It is loaded from the copy of rolldown that
+ * tsdown runs, because built-in plugins only work with the binding that created them.
+ */
+async function replacePlugin({ values, ...options }: ReplaceOptions): Promise {
+ const tsdown = await resolvePath('tsdown', { url: import.meta.url })
+ const plugins = await resolvePath('rolldown/plugins', { url: tsdown })
+ const { replacePlugin } = await import(pathToFileURL(plugins).href) as { replacePlugin: (values: Record, options: Omit) => Rolldown.RolldownPluginOption }
+ return replacePlugin(values, options)
+}
+
/** The files that `finishBuild` writes after the bundle. */
const FINISHED_FILES = new Set(['module.json', 'types.d.mts'])
@@ -274,8 +282,5 @@ function filesIn(dir: string) {
/** `dir`, or the closest directory above it that exists, so a watcher sees `dir` being created. */
function existingAncestor(dir: string, root: string) {
- while (!existsSync(dir) && dir !== root && dirname(dir) !== dir) {
- dir = dirname(dir)
- }
- return dir
+ return findUp(dir, ancestor => existsSync(ancestor) || ancestor === root ? ancestor : undefined)!
}
diff --git a/src/tsdown/unchanged.ts b/src/tsdown/unchanged.ts
index 848a210d..4a3346a1 100644
--- a/src/tsdown/unchanged.ts
+++ b/src/tsdown/unchanged.ts
@@ -4,8 +4,7 @@ import { join } from 'pathe'
import type { Rolldown } from 'tsdown'
import { declarationTargets } from '../build/aliases.ts'
-
-const DECLARATION_RE = /\.d\.(?:[^/]+\.)?[cm]?ts$/
+import { ANY_DECLARATION_RE } from '../utils.ts'
export interface UnchangedOutputs {
/**
@@ -73,7 +72,7 @@ function contentHash(output: Rolldown.OutputChunk | Rolldown.OutputAsset, bundle
if (output.type === 'chunk' && output.map) {
hash.update(output.map.toString())
}
- if (DECLARATION_RE.test(output.fileName)) {
+ if (ANY_DECLARATION_RE.test(output.fileName)) {
const text = typeof code === 'string' ? code : Buffer.from(code).toString('utf8')
hash.update('\0').update(declarationTargets(output.fileName, text).filter(target => Object.hasOwn(bundle, target)).join('\0'))
}
diff --git a/src/utils.ts b/src/utils.ts
new file mode 100644
index 00000000..5067e5bc
--- /dev/null
+++ b/src/utils.ts
@@ -0,0 +1,109 @@
+import { existsSync, realpathSync, statSync } from 'node:fs'
+import { readFile, writeFile } from 'node:fs/promises'
+import { basename, dirname, isAbsolute, join, relative, resolve } from 'pathe'
+
+export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/
+export const TYPESCRIPT_RE: RegExp = /\.[cm]?tsx?$/
+export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/
+/** Declarations of scripts and of single-file components, such as `Foo.d.vue.ts`. */
+export const ANY_DECLARATION_RE: RegExp = /\.d\.(?:[^/]+\.)?[cm]?ts$/
+export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/
+export const NODE_MODULES_RE: RegExp = /[\\/]node_modules[\\/]/
+
+const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx']
+
+/** Whether `file` is a script other than a declaration. */
+export function isSourceScript(file: string): boolean {
+ return SCRIPT_RE.test(file) && !DECLARATION_RE.test(file)
+}
+
+/**
+ * The source file a specifier refers to: the path as written, its TypeScript counterpart for
+ * a `.js`-suffixed path, the path with each source extension, then an `index` file.
+ */
+export function probe(path: string): string | undefined {
+ if (isFile(path)) {
+ return path
+ }
+ const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2')
+ if (source !== path && existsSync(source)) {
+ return source
+ }
+ if (path.endsWith('.js') && existsSync(`${source}x`)) {
+ return `${source}x`
+ }
+ for (const extension of EXTENSIONS) {
+ if (existsSync(path + extension)) {
+ return path + extension
+ }
+ }
+ for (const extension of EXTENSIONS) {
+ if (existsSync(resolve(path, `index${extension}`))) {
+ return resolve(path, `index${extension}`)
+ }
+ }
+}
+
+export function isFile(path: string): boolean {
+ return existsSync(path) && statSync(path).isFile()
+}
+
+/** `path` resolved, with symlinks in it and its existing ancestors followed, as module ids are. */
+export function realpath(path: string): string {
+ const resolved = resolve(path)
+ if (existsSync(resolved)) {
+ return resolve(realpathSync(resolved))
+ }
+ const parent = dirname(resolved)
+ return parent === resolved ? resolved : join(realpath(parent), basename(resolved))
+}
+
+/** Whether `path` is `dir` or inside it. */
+export function isInside(dir: string, path: string): boolean {
+ const subpath = relative(dir, path)
+ return subpath !== '..' && !subpath.startsWith('../') && !isAbsolute(subpath)
+}
+
+/** The relative specifier from the directory of `from` to `to`. */
+export function relativeSpecifier(from: string, to: string): string {
+ const path = relative(dirname(from), to)
+ return RELATIVE_RE.test(path) ? path : `./${path}`
+}
+
+/** The directory of an installed package, found the way Node looks up `node_modules`. */
+export function findPackageDir(name: string, cwd: string): string | undefined {
+ return findUp(cwd, dir => existsSync(join(dir, 'node_modules', name, 'package.json')) ? join(dir, 'node_modules', name) : undefined)
+}
+
+/** The first result of `find` for `dir` or the closest directory above it. */
+export function findUp(dir: string, find: (dir: string) => T | undefined): T | undefined {
+ for (; ; dir = dirname(dir)) {
+ const found = find(dir)
+ if (found !== undefined || dirname(dir) === dir) {
+ return found
+ }
+ }
+}
+
+/** Writes `contents` to `file` unless it already holds them, so its modification time only changes with its content. */
+export async function writeIfChanged(file: string, contents: string): Promise {
+ if (await readFile(file, 'utf8').catch(() => undefined) !== contents) {
+ await writeFile(file, contents, 'utf8')
+ }
+}
+
+/** The value of `key` in `map`, created with `create` the first time. */
+export function getOrCreate(map: Map, key: K, create: () => V): V {
+ if (!map.has(key)) {
+ map.set(key, create())
+ }
+ return map.get(key)!
+}
+
+export function isPlainObject(value: unknown): value is Record {
+ return !!value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof RegExp)
+}
+
+export function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
diff --git a/test/build.spec.ts b/test/build.spec.ts
deleted file mode 100644
index 626c89b7..00000000
--- a/test/build.spec.ts
+++ /dev/null
@@ -1,1760 +0,0 @@
-import { createHash } from 'node:crypto'
-import { existsSync } from 'node:fs'
-import { availableParallelism } from 'node:os'
-import process from 'node:process'
-import { fileURLToPath } from 'node:url'
-import { cp, mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'
-import { beforeAll, describe, it, expect } from 'vitest'
-import { exec as spawn } from 'tinyexec'
-import { readPackageJSON } from 'pkg-types'
-import { dirname, join, relative, resolve } from 'pathe'
-import { findStaticImports } from 'mlly'
-import { version as nuxtVersion } from 'nuxt/package.json'
-import { satisfies } from 'verkit'
-import { version } from '../package.json'
-import { guide } from '../src/build/guide.ts'
-import { publishedPackage } from '../src/build/package.ts'
-import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts'
-import { builderImport, repoRoot, tsdownBin } from './utils.ts'
-
-let running = 0
-const waiting: Array<() => void> = []
-async function exec(...args: Parameters) {
- if (running < availableParallelism()) {
- running++
- }
- else {
- await new Promise(resolve => waiting.push(resolve))
- }
- try {
- return await spawn(...args)
- }
- finally {
- const next = waiting.shift()
- if (next) {
- next()
- }
- else {
- running--
- }
- }
-}
-
-const listFiles = async (dir: string) => (await readdir(dir, { recursive: true })).map(file => file.replaceAll('\\', '/'))
-
-const unresolvedSpecifiers = async (dir: string) => {
- const failures: string[] = []
- for (const entry of await listFiles(dir)) {
- if (!/\.d\.[^/]*ts$/.test(entry)) {
- continue
- }
- const file = join(dir, entry)
- for (const [, specifier] of (await readFile(file, 'utf-8')).matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"](\.\.?\/[^'"]*)['"]/g)) {
- const target = join(dirname(file), specifier!)
- const candidates = specifier!.endsWith('.js')
- ? [target.replace(/\.js$/, '.d.ts')]
- : specifier!.endsWith('.mjs')
- ? [target.replace(/\.mjs$/, '.d.mts')]
- : specifier!.endsWith('.vue')
- ? [`${target}.d.ts`, target.replace(/\.vue$/, '.d.vue.ts')]
- : specifier!.endsWith('.css') ? [target] : []
- if (!candidates.some(candidate => existsSync(candidate))) {
- failures.push(`${entry}: ${specifier}`)
- }
- }
- }
- return failures
-}
-
-const RUNTIME_IMPORTS = `
-import { name } from './runtime/utils/name.ts'
-import { aliased } from '#runtime/utils/aliased'
-import { useShape } from './runtime/composables/useShape.ts'
-import type TestMe from './runtime/components/TestMe.vue'
-import type JsxComponent from './runtime/components/JsxComponent.tsx'
-export const runtimeRefs = [name, aliased, useShape]
-export type TestMeType = typeof TestMe
-export type JsxComponentType = typeof JsxComponent
-export type { NuxtApp } from '#app'
-`
-
-const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '../src'] }
-
-describe('module builder', () => {
- const rootDir = fileURLToPath(new URL('../example', import.meta.url))
- const secondRootDir = rootDir.replace('example', '.temp-example-without-options')
- const thirdRootDir = rootDir.replace('example', '.temp-example-with-runtime-imports')
- const fourthRootDir = rootDir.replace('example', '.temp-example-single-runtime-dir')
- const wildcardRootDir = rootDir.replace('example', '.temp-example-wildcard-paths')
- const noRuntimeRootDir = rootDir.replace('example', '.temp-example-without-runtime')
- const vueOnlyRootDir = rootDir.replace('example', '.temp-example-vue-only-runtime')
- const packageImportsRootDir = rootDir.replace('example', '.temp-example-package-imports')
- const prepareLoaderRootDir = rootDir.replace('example', '.temp-example-prepare-loader')
- const extensionlessRootDir = rootDir.replace('example', '.temp-example-extensionless-imports')
- const buildConfigRootDir = rootDir.replace('example', '.temp-example-build-config')
- const replaceRootDir = rootDir.replace('example', '.temp-example-build-config-replace')
- const unsupportedRootDir = rootDir.replace('example', '.temp-example-build-config-unsupported')
- const stylesheetsRootDir = rootDir.replace('example', '.temp-example-stylesheets')
- const transpileRootDir = rootDir.replace('example', '.temp-example-transpile-only')
- const solutionRootDir = rootDir.replace('example', '.temp-example-solution-tsconfig')
- const parentTsconfigRootDir = rootDir.replace('example', '.temp-example-parent-tsconfig')
- const portableRootDir = rootDir.replace('example', '.temp-example-portable-types')
- const valueExportsRootDir = rootDir.replace('example', '.temp-example-value-exports')
- const valueExportsIsolatedRootDir = rootDir.replace('example', '.temp-example-value-exports-isolated')
- const isolatedRootDir = rootDir.replace('example', '.temp-example-isolated-declarations')
- const typeErrorRootDir = rootDir.replace('example', '.temp-example-type-error')
- const semanticErrorRootDir = rootDir.replace('example', '.temp-example-semantic-error')
- const vueErrorRootDir = rootDir.replace('example', '.temp-example-vue-error')
- const nonErasableRootDir = rootDir.replace('example', '.temp-example-non-erasable-syntax')
- const autoPrepareRootDir = rootDir.replace('example', '.temp-example-auto-prepare')
- const annotatedRootDir = rootDir.replace('example', '.temp-example-isolated-annotated')
- const runtimeShapeRootDir = rootDir.replace('example', '.temp-example-runtime-shape')
- const routesRootDir = rootDir.replace('example', '.temp-example-routes/mod')
- let routesBuild = ''
- let buildConfigBuild = ''
- const encodedRootDir = rootDir.replace('example', '.temp-example with spaces ü')
- const sourceFlowRootDir = rootDir.replace('example', '.temp-example-source-flow')
- const distFlowRootDir = rootDir.replace('example', '.temp-example-dist-flow')
- const packDir = rootDir.replace('example', '.temp-packs')
- const secondDistDir = join(secondRootDir, 'dist')
- const thirdDistDir = join(thirdRootDir, 'dist')
- const fourthDistDir = join(fourthRootDir, 'dist')
-
- const flows = [
- {
- name: 'source exports',
- rootDir: sourceFlowRootDir,
- pack: ['pnpm', 'pack', '--pack-destination', join(packDir, 'source-exports')],
- nodeTypeErrors: [expect.stringContaining(`src/runtime/plugins/plugin.ts(1,34): error TS2307: Cannot find module '#app'`)],
- },
- {
- name: 'dist',
- rootDir: distFlowRootDir,
- pack: ['npm', 'pack', '--pack-destination', join(packDir, 'dist')],
- nodeTypeErrors: [],
- },
- ]
- const flowOutput = new Map()
-
- beforeAll(async () => {
- const legacyRootDir = rootDir.replace('example', '.temp-example-legacy-tsconfig')
- await rm(legacyRootDir, { force: true, recursive: true })
- await cp(rootDir, legacyRootDir, { recursive: true })
- await writeFile(join(legacyRootDir, 'tsconfig.json'), JSON.stringify(LEGACY_TSCONFIG, null, 2))
- await exec('pnpm', ['nuxt-module-build', 'prepare', legacyRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true })
-
- const copyExample = async (target: string, transform: (contents: string) => string) => {
- await mkdir(dirname(target), { recursive: true })
- await rm(target, { force: true, recursive: true })
- await cp(legacyRootDir, target, { recursive: true })
- const pkgPath = join(target, 'package.json')
- const { publishConfig: _, ...pkg } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8')))
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2))
- const moduleSrc = join(target, 'src/module.ts')
- await writeFile(moduleSrc, transform(await readFile(moduleSrc, 'utf-8')))
- }
-
- const enableIsolatedDeclarations = async (target: string) => {
- const tsconfig = join(target, 'tsconfig.json')
- await writeFile(tsconfig, JSON.stringify({ ...JSON.parse(await readFile(tsconfig, 'utf-8')), compilerOptions: { isolatedDeclarations: true } }))
- }
-
- // Builds the module declarations with oxc, for fixtures that do not test them
- const isolate = async (target: string) => {
- const moduleSrc = join(target, 'src/module.ts')
- const contents = await readFile(moduleSrc, 'utf-8')
- await writeFile(moduleSrc, [
- `import type { NuxtModule } from '@nuxt/schema'`,
- contents.replace(/export default defineNuxtModule()?\(\{/, (_, options = '') => `const module: NuxtModule${options} = defineNuxtModule${options}({`),
- 'export default module',
- ].join('\n'))
- await writeFile(join(target, 'src/utils.ts'), 'export const myModuleUtils = (): void => {}\n')
- await enableIsolatedDeclarations(target)
- }
-
- // Prepare second root directory without type export
- await copyExample(secondRootDir, contents => contents.replace('export interface ModuleOptions', 'interface ModuleOptions'))
-
- // Prepare a root directory whose path is percent-encoded in file URLs
- await copyExample(encodedRootDir, contents => contents + RUNTIME_IMPORTS)
-
- // Prepare third root directory whose module entry pulls in runtime code, through a
- // relative specifier, a tsconfig alias and a `.vue` import
- await copyExample(thirdRootDir, contents => contents + RUNTIME_IMPORTS)
-
- // Prepare a fourth root directory whose entire runtime tree lives in one
- // subdirectory, and which contains no single-file components
- await copyExample(fourthRootDir, contents => contents)
- for (const directory of ['components', 'composables', 'assets']) {
- await rm(join(fourthRootDir, 'src/runtime', directory), { force: true, recursive: true })
- }
- await isolate(fourthRootDir)
-
- const minimalModule = (name: string) => () => `import { defineNuxtModule } from '@nuxt/kit'
-
-export default defineNuxtModule({
- meta: { name: '${name}', configKey: '${name}' },
- setup() {},
-})
-`
-
- await copyExample(prepareLoaderRootDir, contents => `import { deps } from './deps.ts'\nimport { deep } from './deep/a.ts'\n${contents}\nexport const loaded = [deps, deep]\n`)
- await rm(join(prepareLoaderRootDir, '.nuxt'), { force: true, recursive: true })
-
- await copyExample(extensionlessRootDir, contents => `${contents}\nexport { myModuleUtils } from './utils.js'\nexport { helper } from './helpers'\nexport { kit } from './kit'\nexport type { Kit } from './kit'\n`)
-
- await copyExample(packageImportsRootDir, () => `${minimalModule('package-imports')()}\nexport { nativeValue } from './native-helper.ts'\nexport { internal } from '#internal/value'\n`)
- const packageImportsPkg = join(packageImportsRootDir, 'package.json')
- await writeFile(packageImportsPkg, JSON.stringify({ ...JSON.parse(await readFile(packageImportsPkg, 'utf-8')), imports: { '#internal/*': './src/internal/*.ts' } }, null, 2))
-
- await copyExample(noRuntimeRootDir, minimalModule('no-runtime'))
- await rm(join(noRuntimeRootDir, 'src/runtime'), { force: true, recursive: true })
- await isolate(noRuntimeRootDir)
-
- await copyExample(vueOnlyRootDir, minimalModule('vue-only'))
- for (const file of ['assets', 'composables', 'plugins', 'components/JsxComponent.tsx']) {
- await rm(join(vueOnlyRootDir, 'src/runtime', file), { force: true, recursive: true })
- }
- await isolate(vueOnlyRootDir)
-
- await copyExample(isolatedRootDir, contents => contents)
- await enableIsolatedDeclarations(isolatedRootDir)
-
- const valueExports = `export function defineMyModuleConfig(): void {}
-export const myModuleVersion = '1.0.0'
-export const Mode = { Light: 0, Dark: 1 } as const
-export type Mode = typeof Mode[keyof typeof Mode]`
- const valueExportsConsumer = `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module'
-import type { ModuleOptions } from 'my-module'
-
-defineMyModuleConfig()
-const options: ModuleOptions = { apiKey: myModuleVersion }
-const light: number = Mode.Light
-const dark: Mode = Mode.Dark
-void [light, dark, options]
-`
- const valueExportsConsumerConfig = JSON.stringify({
- compilerOptions: {
- moduleResolution: 'bundler',
- module: 'ESNext',
- target: 'ESNext',
- lib: ['ESNext'],
- strict: true,
- noEmit: true,
- skipLibCheck: true,
- },
- include: ['consumer.ts'],
- }, null, 2)
- const prepareValueExportsConsumer = async (target: string) => {
- await rm(join(target, 'playground/node_modules/my-module'), { force: true })
- await symlink(target, join(target, 'playground/node_modules/my-module'))
- await writeFile(join(target, 'playground/consumer.ts'), valueExportsConsumer)
- await writeFile(join(target, 'playground/consumer.tsconfig.json'), valueExportsConsumerConfig)
- }
-
- await copyExample(valueExportsRootDir, contents => `${contents}\n${valueExports}\n`)
- await prepareValueExportsConsumer(valueExportsRootDir)
-
- await copyExample(valueExportsIsolatedRootDir, contents => `${contents}\n${valueExports}\n`)
- await prepareValueExportsConsumer(valueExportsIsolatedRootDir)
- await isolate(valueExportsIsolatedRootDir)
-
- await copyExample(nonErasableRootDir, contents => `import { name as packageName } from '../package.json'
-import { Level } from './levels.ts'
-
-enum Mode { Stub = 'stub' }
-class Holder { constructor(public value: string) {} }
-${contents.replace(`name: 'my-module'`, 'name: new Holder(`${packageName}-${Mode.Stub}-${Level.High}`).value')}`)
- const nonErasablePkg = JSON.parse(await readFile(join(nonErasableRootDir, 'package.json'), 'utf-8'))
- nonErasablePkg.exports['./plugin'] = './dist/runtime/plugins/plugin.js'
- await writeFile(join(nonErasableRootDir, 'package.json'), JSON.stringify(nonErasablePkg, null, 2))
- await writeFile(join(nonErasableRootDir, 'src/levels.ts'), `export enum Level { High = 'high' }\n`)
-
- await copyExample(autoPrepareRootDir, contents => contents)
- await rm(join(autoPrepareRootDir, '.nuxt'), { recursive: true, force: true })
- await isolate(autoPrepareRootDir)
-
- await copyExample(typeErrorRootDir, contents => contents)
- await rm(join(typeErrorRootDir, 'src/runtime/components'), { recursive: true, force: true })
- await writeFile(join(typeErrorRootDir, 'src/runtime/utils.ts'), `export const Anonymous = class { private secret = 1 }\n`)
- await copyExample(semanticErrorRootDir, minimalModule('semantic-error'))
- await rm(join(semanticErrorRootDir, 'src/runtime'), { recursive: true, force: true })
- await mkdir(join(semanticErrorRootDir, 'src/runtime/utils'), { recursive: true })
- await writeFile(join(semanticErrorRootDir, 'src/runtime/utils/typo.ts'), `export const count: number = 'one'\nexport const double = (value: number): number => value * 2\n`)
- await mkdir(join(semanticErrorRootDir, 'src/runtime/components'), { recursive: true })
- await writeFile(join(semanticErrorRootDir, 'src/runtime/components/Typo.vue'), `\n\n\n {{ props.label }} {{ count }} \n \n`)
- await writeFile(join(semanticErrorRootDir, 'src/runtime/components/Sized.vue'), `\n\n\n\n\n \n \n`)
- await mkdir(join(semanticErrorRootDir, 'src/runtime/composables'), { recursive: true })
- await writeFile(join(semanticErrorRootDir, 'src/runtime/composables/useSize.ts'), `import { computed } from 'vue'\nimport type { Props } from '../components/Sized.vue'\n\nexport function useSize(props: Props) {\n return computed(() => props.size)\n}\n`)
- await copyExample(vueErrorRootDir, minimalModule('vue-error'))
- await rm(join(vueErrorRootDir, 'src/runtime'), { recursive: true, force: true })
- await copyExample(annotatedRootDir, contents => contents)
- await isolate(annotatedRootDir)
-
- // Prepare a root directory whose tsconfig maps every bare specifier into `src/`,
- // with a file that shadows a real package
- await copyExample(wildcardRootDir, () => `import { defineNuxtModule } from '@nuxt/kit'
-
-export default defineNuxtModule({
- meta: { name: 'wildcard-module', configKey: 'wildcardModule' },
- setup() {},
-})
-`)
- await writeFile(join(wildcardRootDir, 'tsconfig.json'), JSON.stringify({ compilerOptions: { paths: { '*': ['./src/*'] } } }, null, 2))
- await mkdir(join(wildcardRootDir, 'src/@nuxt'), { recursive: true })
- await writeFile(join(wildcardRootDir, 'src/@nuxt/kit.ts'), 'export const defineNuxtModule = (_: unknown) => ({ SHADOWED: true })\n')
-
- const writeFiles = async (target: string, files: Record) => {
- for (const [file, contents] of Object.entries(files)) {
- await mkdir(dirname(join(target, file)), { recursive: true })
- await writeFile(join(target, file), contents)
- }
- }
-
- const fakeCache = {
- 'node_modules/fake-cache/package.json': JSON.stringify({ name: 'fake-cache', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
- 'node_modules/fake-cache/index.js': `export const defineCached = handler => handler\n`,
- 'node_modules/fake-cache/index.d.ts': `import type { Handler } from 'fake-h3'\nexport declare const defineCached: (handler: () => string) => Handler\n`,
- 'node_modules/fake-cache/node_modules/fake-h3/package.json': JSON.stringify({ name: 'fake-h3', type: 'module', exports: { '.': { types: './index.d.ts' } } }),
- 'node_modules/fake-cache/node_modules/fake-h3/index.d.ts': `export interface Handler { (): string, __h3: 2 }\n`,
- }
- await writeFiles(packageImportsRootDir, {
- 'src/native-helper.ts': `import { inner } from './nested/inner.ts'\n\nexport const nativeValue: string = inner\n`,
- 'src/nested/inner.ts': `export const inner: string = 'loaded helper'\n`,
- 'src/internal/value.ts': `export const internal: string = 'through imports'\n`,
- })
-
- await writeFiles(prepareLoaderRootDir, {
- 'node_modules/fake-cjs-marker/package.json': JSON.stringify({ name: 'fake-cjs-marker', version: '1.0.0', main: 'index.js' }),
- 'node_modules/fake-cjs-marker/index.js': `const marker = 'mentions import.meta in a string'\nmodule.exports = { value: marker.length }\n`,
- 'node_modules/fake-esm-split/package.json': JSON.stringify({ name: 'fake-esm-split', version: '1.0.0', type: 'module', exports: { '.': { import: './index.js', require: './index.cjs' } } }),
- 'node_modules/fake-esm-split/index.js': `export { value } from './inner.js'\nexport { other } from './other.js'\n`,
- 'node_modules/fake-esm-split/inner.js': `import cjs from 'fake-cjs-marker'\nexport const value = cjs.value\n`,
- 'node_modules/fake-esm-split/other.js': `import cjs from 'fake-cjs-marker'\nexport const other = cjs.value + 1\n`,
- 'node_modules/fake-esm-split/index.cjs': `module.exports = { value: 0, other: 1 }\n`,
- 'src/deps.ts': `// @ts-ignore untyped\nimport cjs from 'fake-cjs-marker'\n// @ts-ignore untyped\nimport { value, other } from 'fake-esm-split'\n\nexport const deps: unknown[] = [cjs, value, other]\n`,
- 'src/deep/a.ts': `export { deep } from './b.ts'\n`,
- 'src/deep/b.ts': `import pkg from '../../package.json' with { type: 'json' }\n\nexport const deep: string = pkg.name\n`,
- })
-
- for (const dir of [thirdRootDir, encodedRootDir]) {
- const pkgPath = join(dir, 'package.json')
- await writeFile(pkgPath, JSON.stringify({ ...JSON.parse(await readFile(pkgPath, 'utf-8')), imports: { '#runtime/*': './src/runtime/*.ts' } }, null, 2))
- await writeFiles(dir, {
- 'src/runtime/composables/useShape.ts': `import { shape } from '../utils/shape.ts'\n\nexport const useShape = (): string => shape\n`,
- 'src/runtime/utils/name.ts': `export const name: string = 'name'\n`,
- 'src/runtime/utils/aliased.ts': `export const aliased: string = 'aliased'\n`,
- 'src/runtime/utils/shape.ts': `export const shape: string = 'shape'\n`,
- 'src/runtime/components/JsxCard.vue': `\n\n\n \n \n`,
- 'src/runtime/components/JsxSlot.tsx': `import { defineComponent } from 'vue'\nimport { useNuxtApp } from '#app'\nimport JsxComponent from './JsxComponent'\n\nexport const useSlotApp = () => useNuxtApp()\n\nexport default defineComponent((_, { slots }) => () => )\n`,
- 'src/runtime/server/render.tsx': `import { useSlotApp } from '../components/JsxSlot'\nimport { strong } from '../utils/strong'\n\nexport type SlotApp = ReturnType\n\nexport const render = (label: string) => {strong(label)}
\n`,
- 'src/runtime/server/render.stories.ts': `import JsxSlot from '../components/JsxSlot'\n\nexport const tested = JsxSlot\n`,
- 'src/runtime/utils/strong.tsx': `import { bold } from './bold'\n\nexport const strong = (label: string) => {bold(label)} \n`,
- 'src/runtime/utils/bold.tsx': `export const bold = (label: string) => {label} \n`,
- 'src/runtime/utils/label.tsx': `export const label = label \n`,
- })
- }
-
- await writeFiles(extensionlessRootDir, {
- 'src/helpers.ts': `export const helper = (): string => 'helper'\n`,
- 'src/kit/index.ts': `export const kit = (): string => 'kit'\nexport type Kit = ReturnType\n`,
- })
- await rm(join(extensionlessRootDir, 'dist'), { force: true, recursive: true })
-
- await writeFiles(typeErrorRootDir, {
- ...fakeCache,
- 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`,
- })
- await writeFiles(vueErrorRootDir, {
- ...fakeCache,
- 'src/runtime/components/Cached.vue': `\n\n\n cached \n \n`,
- 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`,
- })
-
- await copyExample(buildConfigRootDir, contents => contents)
- await writeFiles(buildConfigRootDir, {
- 'build.config.ts': `import { appendFileSync, existsSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { defineBuildConfig } from '@nuxt/module-builder'
-import { externals } from './build/externals.ts'
-
-const record = hook => ctx => appendFileSync(join(ctx.options.rootDir, 'hooks.log'), JSON.stringify({
- hook,
- stub: ctx.options.stub,
- meta: existsSync(join(ctx.options.outDir, 'module.json')),
- entries: ctx.options.entries.map(entry => entry.name).sort(),
-}) + '\\n')
-
-export default defineBuildConfig({
- hooks: {
- 'build:before'(ctx) {
- record('build:before')(ctx)
- writeFileSync(join(ctx.options.rootDir, 'src/generated.ts'), 'export const generated = "from build:before"\\n')
- },
- 'rollup:done': record('rollup:done'),
- 'build:done': record('build:done'),
- },
- declaration: true,
- entries: [
- 'src/utils',
- './src/vite.ts',
- { input: 'src/content', name: 'content' },
- 'src/nested/helper',
- { input: 'src/shared/', outDir: 'dist/shared' },
- ],
- externals,
- replace: {
- __MODULE_VERSION__: JSON.stringify('1.2.3'),
- },
- rollup: {
- emitCJS: false,
- },
-})
-`,
- 'build/externals.ts': `export const externals = ['fake-pkg', '#content-alias', /^regex-pkg$/]\n`,
- 'node_modules/fake-pkg/package.json': JSON.stringify({ name: 'fake-pkg', type: 'module', exports: { './sub': './sub.js' } }),
- 'node_modules/fake-pkg/sub.js': `export const plugin = 'bundled-fake-pkg'\n`,
- 'node_modules/regex-pkg/package.json': JSON.stringify({ name: 'regex-pkg', type: 'module', exports: './index.js' }),
- 'node_modules/regex-pkg/index.js': `export default 'bundled-regex-pkg'\n`,
- 'src/alias/config.ts': `export default 'bundled-alias'\n`,
- 'src/vite.ts': `// @ts-ignore untyped
-import { plugin } from 'fake-pkg/sub'
-// @ts-ignore untyped
-import virtual from 'regex-pkg'
-
-import { generated } from './generated.ts'
-
-declare const __MODULE_VERSION__: string
-
-export const version: string = __MODULE_VERSION__
-export const refs: unknown[] = [plugin, virtual, generated]
-`,
- 'src/content.ts': `// @ts-ignore build-time alias
-import config from '#content-alias/config'
-
-export const content: unknown = config
-`,
- 'src/nested/helper.ts': `import plugin from '../runtime/plugins/plugin.ts'\n\nexport const helper = (): unknown => plugin\nexport const lazy = (): Promise => import('../runtime/composables/useWrappedFetch.ts')\n`,
- 'src/shared/format.ts': `export const format = (value: string): string => value.trim()\n`,
- 'src/features/flag.ts': `export const flag: boolean = true\n`,
- })
-
- const buildConfigPkg = join(buildConfigRootDir, 'package.json')
- await writeFile(buildConfigPkg, JSON.stringify({
- ...JSON.parse(await readFile(buildConfigPkg, 'utf-8')),
- imports: { '#content-alias/*': './src/alias/*.ts' },
- publishConfig: { imports: { '#content-alias/*': './dist/alias/*.mjs' } },
- build: { entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'js' }] },
- }))
-
- await copyExample(replaceRootDir, contents => contents)
- await isolate(replaceRootDir)
- await writeFiles(replaceRootDir, {
- 'build.config.ts': `import { defineBuildConfig } from 'unbuild'
-
-export default defineBuildConfig({
- entries: ['./src/unplugin'],
- externals: ['#build/ui'],
- hooks: {
- 'mkdist:entry:options'(ctx, entry, options) {
- options.addRelativeDeclarationExtensions = false
- },
- },
- rollup: {
- replace: {
- delimiters: ['', ''],
- values: {
- "process.argv.includes('--uiDev')": 'false',
- },
- },
- },
-})
-`,
- 'src/unplugin.ts': `// @ts-ignore untyped
-import ext from 'ext-pkg'
-
-declare const process: { argv: string[] }
-
-export const isDev: boolean = process.argv.includes('--uiDev')
-export const extRef: unknown = ext
-`,
- 'node_modules/ext-pkg/package.json': JSON.stringify({ name: 'ext-pkg', type: 'module', exports: './index.js' }),
- 'node_modules/ext-pkg/index.js': `export default 'bundled-ext-pkg'\n`,
- })
- const replacePkg = join(replaceRootDir, 'package.json')
- await writeFile(replacePkg, JSON.stringify({ ...JSON.parse(await readFile(replacePkg, 'utf-8')), unbuild: { externals: ['ext-pkg'] } }))
-
- await copyExample(unsupportedRootDir, contents => contents)
- await writeFiles(unsupportedRootDir, {
- 'build.config.ts': `import { defineBuildConfig } from 'unbuild'
-
-export default defineBuildConfig({
- entries: [
- { input: 'src/runtime/', ext: 'cjs' },
- { input: 'src/schema', builder: 'untyped' },
- ],
- hooks: {
- 'build:prepare'() {},
- 'rollup:options'() {},
- 'mkdist:entry:options'() {},
- },
- rollup: {
- emitCJS: true,
- alias: {},
- },
- stub: true,
- unknownOption: 1,
-})
-`,
- })
-
- await copyExample(transpileRootDir, contents => `import type { DeepPartial } from 'fake-types'
-import type FakeCjs from 'fake-cjs-types'
-${contents}
-export interface ExtraOptions { deep?: DeepPartial<{ a: string }>, cjs?: FakeCjs.Options }
-`)
- await writeFiles(transpileRootDir, {
- 'node_modules/fake-cjs-types/package.json': JSON.stringify({ name: 'fake-cjs-types', types: './index.d.ts' }),
- 'node_modules/fake-cjs-types/index.d.ts': `declare namespace FakeCjs { interface Options { level: number } }\nexport = FakeCjs\n`,
- 'src/runtime/server/routes/[...slug].ts': `export default (slug: string) => slug\n`,
- 'src/runtime/utils/self.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const getApiKey = (options: ModuleOptions) => options.apiKey\n`,
- 'node_modules/fake-dep/package.json': JSON.stringify({ name: 'fake-dep', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
- 'node_modules/fake-dep/index.js': `export const helper = () => 'bundled-fake-dep'\n`,
- 'node_modules/fake-dep/index.d.ts': `export declare const helper: () => string\n`,
- 'node_modules/fake-types/package.json': JSON.stringify({ name: 'fake-types', types: './index.d.ts' }),
- 'node_modules/fake-types/index.d.ts': `export type DeepPartial = { [K in keyof T]?: DeepPartial }\n`,
- 'src/runtime/cache/lru.ts': `export const lru: string = 'lru'\n`,
- 'src/runtime/server/handler.ts': `// @ts-ignore build-time virtual
-import options from '#internal/nuxt.config.mjs'
-// @ts-ignore app alias
-import app from '~/app.config'
-// @ts-ignore app alias
-import root from '@/root'
-import { useNuxtApp } from '#app'
-import { helper } from 'fake-dep'
-import { lru } from '#fixture-cache'
-import { local } from '../utils/local'
-
-export default (): unknown[] => [options, app, root, useNuxtApp, helper(), lru, local]
-`,
- 'src/runtime/utils/local.ts': `export const local: string = 'local'\n`,
- 'src/runtime/utils/options.ts': `import type { DeepPartial } from 'fake-types'
-import { helper } from 'fake-dep'
-
-export type Options = DeepPartial<{ a: { b: string } }>
-export const defineOptions = (options: Options) => ({ options, helper })
-`,
- })
- const transpileNuxtTsconfig = join(transpileRootDir, '.nuxt/tsconfig.json')
- const transpileNuxtConfig = JSON.parse(await readFile(transpileNuxtTsconfig, 'utf-8'))
- transpileNuxtConfig.compilerOptions.paths['#fixture-cache'] = ['../src/runtime/cache/lru']
- await writeFile(transpileNuxtTsconfig, JSON.stringify(transpileNuxtConfig))
-
- await copyExample(solutionRootDir, contents => contents)
- await writeFiles(solutionRootDir, {
- 'tsconfig.json': JSON.stringify({ files: [], references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.server.json' }] }),
- 'tsconfig.app.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', include: ['.nuxt/nuxt.d.ts', 'src/**/*'], exclude: ['src/runtime/server/**'] }),
- 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { paths: { '#server-only': ['./src/runtime/server/only.ts'] } }, include: ['src/runtime/server/**/*'] }),
- 'src/runtime/server/only.ts': `export interface ServerOnly { id: string }\n`,
- 'src/runtime/server/api/[id].get.ts': `import type { ServerOnly } from '#server-only'\n\nexport default (value: ServerOnly) => value.id\n`,
- })
-
- await copyExample(parentTsconfigRootDir, contents => contents)
- await mkdir(join(parentTsconfigRootDir, 'packages/mod'), { recursive: true })
- for (const file of ['src', 'package.json']) {
- await cp(join(parentTsconfigRootDir, file), join(parentTsconfigRootDir, 'packages/mod', file), { recursive: true })
- await rm(join(parentTsconfigRootDir, file), { recursive: true, force: true })
- }
- const loggerStore = 'node_modules/.pnpm/fake-logger@1.0.0/node_modules/fake-logger'
- await writeFiles(parentTsconfigRootDir, {
- [`${loggerStore}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.mts', default: './dist/index.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } } }),
- [`${loggerStore}/dist/utils.d.mts`]: `export declare const noop: () => void\n`,
- [`${loggerStore}/dist/utils.mjs`]: `export const noop = () => {}\n`,
- [`${loggerStore}/dist/core.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\n`,
- [`${loggerStore}/dist/core.d.mts`]: `export interface LoggerInstance { log: (message: string) => void }\n`,
- [`${loggerStore}/dist/index.d.ts`]: `import type { LoggerInstance } from './core'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`,
- [`${loggerStore}/dist/index.d.mts`]: `import type { LoggerInstance } from './core.mjs'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`,
- [`${loggerStore}/dist/index.mjs`]: `export const createLogger = () => ({ log: console.log })\n`,
- 'packages/mod/src/runtime/logger.ts': `import { createLogger } from 'fake-logger'\nimport { noop } from 'fake-logger/utils'\n\nexport const logger = createLogger()\nexport const silence = noop\n`,
- })
- await mkdir(join(parentTsconfigRootDir, 'packages/mod/node_modules'), { recursive: true })
- await symlink(join(parentTsconfigRootDir, loggerStore), join(parentTsconfigRootDir, 'packages/mod/node_modules/fake-logger'))
- const parentNuxtTsconfig = join(parentTsconfigRootDir, '.nuxt/tsconfig.json')
- const parentNuxtConfig = JSON.parse(await readFile(parentNuxtTsconfig, 'utf-8'))
- parentNuxtConfig.compilerOptions.paths['fake-logger'] = [`../${loggerStore}`]
- await writeFile(parentNuxtTsconfig, JSON.stringify(parentNuxtConfig))
-
- await copyExample(portableRootDir, contents => `import { defineThing } from 'fake-kit'\n${contents}\nexport const thing = defineThing({ name: 'portable' })\n`)
- const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}`
- await writeFiles(portableRootDir, {
- [`${store('fake-schema')}/package.json`]: JSON.stringify({ name: 'fake-schema', types: './index.d.ts' }),
- [`${store('fake-schema')}/index.d.ts`]: `export interface Thing { options: T }\n`,
- [`${store('fake-kit')}/package.json`]: JSON.stringify({ name: 'fake-kit', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
- [`${store('fake-kit')}/index.d.ts`]: `import type { Thing } from 'fake-schema'\nexport declare function defineThing(options: T): Thing\n`,
- [`${store('fake-kit')}/index.js`]: `export const defineThing = options => ({ options })\n`,
- })
- await symlink(join(portableRootDir, store('fake-schema')), join(portableRootDir, 'node_modules/.pnpm/fake-kit@1.0.0/node_modules/fake-schema'))
- await symlink(join(portableRootDir, store('fake-schema')), join(portableRootDir, 'node_modules/fake-schema'))
- await symlink(join(portableRootDir, store('fake-kit')), join(portableRootDir, 'node_modules/fake-kit'))
- const portableNuxtTsconfig = join(portableRootDir, '.nuxt/tsconfig.json')
- const portableNuxtConfig = JSON.parse(await readFile(portableNuxtTsconfig, 'utf-8'))
- portableNuxtConfig.compilerOptions.paths['fake-schema'] = [`../${store('fake-schema')}`]
- await writeFile(portableNuxtTsconfig, JSON.stringify(portableNuxtConfig))
- const portableNuxtTypes = join(portableRootDir, '.nuxt/nuxt.d.ts')
- await writeFile(portableNuxtTypes, `/// \n${await readFile(portableNuxtTypes, 'utf-8')}`)
-
- await copyExample(stylesheetsRootDir, contents => contents)
- await isolate(stylesheetsRootDir)
- await writeFiles(join(stylesheetsRootDir, 'src/runtime'), {
- 'styles/card.css': `@import "./base.css";\n\n.card {\n user-select: none;\n & .title { font-weight: bold; }\n &:hover { color: rebeccapurple; }\n}\n`,
- 'styles/base.css': `.base { margin: 0px 0px; }\n`,
- 'styles/_variables.scss': `$primary: #00dc82;\n`,
- 'styles/theme.scss': `@use "variables" as v;\n.theme { color: v.$primary; .nested { padding: 1px; } }\n`,
- 'styles/indented.sass': `.indented\n color: blue\n`,
- 'styles/legacy.less': `@c: red;\n.less { color: @c; }\n`,
- 'types/ambient.d.ts': `declare global { interface Window { __fixture: true } }\nexport {}\n`,
- 'types/app.d.ts': `import type { NuxtApp } from '#app'\nexport type App = NuxtApp\n`,
- 'plugins/styled.ts': `import '../styles/card.css'\nimport '../styles/theme.scss'\n\nexport const styled = true\n`,
- })
-
- await copyExample(runtimeShapeRootDir, contents => contents)
- const runtimeShapePkg = JSON.parse(await readFile(join(runtimeShapeRootDir, 'package.json'), 'utf-8'))
- await writeFile(join(runtimeShapeRootDir, 'package.json'), JSON.stringify({ ...runtimeShapePkg, build: { entries: ['./src/utils', './src/utils/merge.ts', './src/data.json'] } }, null, 2))
- await writeFile(join(runtimeShapeRootDir, '.nuxt/app.config.ts'), `export default { theme: { buildMachineOnly: 'must-not-be-published' as const } }\n`)
- await writeFile(join(runtimeShapeRootDir, 'external.ts'), `export const answer = 42\n`)
- for (const name of ['fake-polyfill', 'fake-register']) {
- await writeFiles(join(runtimeShapeRootDir, 'node_modules', name), {
- 'package.json': JSON.stringify({ name, type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
- 'index.js': `globalThis.__order = [...globalThis.__order ?? [], '${name}']\n`,
- 'index.d.ts': `export {}\n`,
- })
- }
- await writeFiles(join(runtimeShapeRootDir, 'src'), {
- 'data.json': `{ "answer": 42 }\n`,
- 'utils/merge.ts': `export const merge = (a: T, b: T): T => ({ ...a, ...b })\n`,
- 'shared/constants.ts': `import { LIMIT } from './limits'\n\nexport const CONSTANT = LIMIT\n`,
- 'shared/limits.ts': `export const LIMIT = 10\n`,
- 'types.ts': `export interface RootType { root: string }\n`,
- 'types/middlewares.ts': `export type RequestSizeLimiter = { maxRequestSizeInBytes: number }\n`,
- 'runtime/server/limiter.ts': `import { type RequestSizeLimiter } from '../../types/middlewares'\nimport {} from 'nuxt/app'\nimport '../disabled/side'\n\nexport const limit = (options: RequestSizeLimiter) => options.maxRequestSizeInBytes\n`,
- 'routing.ts': `import { readFileSync } from 'node:fs'\nimport { generate } from './kit/gen'\nimport type { RootType } from './types'\n\nexport interface RouteInfo { path: string, root: RootType }\nexport const localizeRoutes = (file: string): string => generate(readFileSync(file, 'utf8'))\n`,
- 'kit/gen.ts': `import { createHash } from 'node:crypto'\n\nexport const generate = (input: string) => createHash('sha1').update(input).digest('hex')\n`,
- 'runtime/composables/useLocaleRoute.ts': `import { RouteInfo } from '../../routing'\n\nexport const useLocaleRoute = (route: RouteInfo) => route\n`,
- 'runtime/types.ts': `export interface RuntimeType { runtime: string }\n`,
- 'runtime/server/uses.ts': [
- `import { merge } from '../../utils/merge'`,
- `import { CONSTANT } from '../../shared/constants'`,
- `import type { RootType } from '../../types'`,
- `import type { RuntimeType } from '../types'`,
- ``,
- `export const combine = (a: RootType & RuntimeType, b: RootType & RuntimeType) => [merge(a, b), CONSTANT] as const`,
- ``,
- ].join('\n'),
- 'runtime/escaping.ts': `export const load = () => import('../../external')\n`,
- 'runtime/composables/mock.ts': `export const defineThing = () => 'mock'\n`,
- 'runtime/disabled/composables/defineThing.ts': `export { defineThing } from '../../composables/mock'\n`,
- 'runtime/disabled/index.ts': `import './side'\nexport { defineThing } from './composables/defineThing'\n`,
- 'runtime/disabled/side.ts': `globalThis.__side = true\n`,
- 'runtime/order/first.ts': `import 'fake-polyfill'\nimport 'vue'\nimport './order.css'\nimport './effect'\nimport 'fake-register'\nexport { level } from './levels'\n`,
- 'runtime/order/interleaved.ts': [
- `import 'fake-register'`,
- `import { level } from './levels'`,
- `export * from './reexported'`,
- `import './order.css'`,
- `export { useState } from '#imports'`,
- `import 'fake-polyfill'`,
- `import './effect'`,
- `import { ref } from 'vue'`,
- ``,
- `export const value = ref(level)`,
- ``,
- ].join('\n'),
- 'runtime/order/levels.ts': `export const level = 1\n`,
- 'runtime/order/reexported.ts': `export const reexported = 1\n`,
- 'runtime/order/effect.ts': `globalThis.__effect = true\n`,
- 'runtime/order/order.css': `.order { color: red }\n`,
- 'runtime/content/index.ts': `export * from '../components/TestMe.vue'\nexport * from '../components/TestMeSetup.vue'\nexport * from './prose'\n`,
- 'runtime/content/prose.ts': `export * from './levels'\nexport interface ProseThing { title: string }\n`,
- 'runtime/content/levels.ts': `export const proseLevel = 1\n`,
- 'runtime/utils/provider.ts': `import type { ModuleOptions } from '../../module'\n\nexport const defineProvider = (options: ModuleOptions) => options\n`,
- 'runtime/utils/props.ts': `export interface BaseProps { size?: number }\n`,
- 'runtime/composables/useThemeConfig.ts': `import appConfig from '#build/app.config'\n\nexport const useThemeConfig = () => appConfig.theme\n`,
- 'runtime/composables/useButton.ts': `import theme, { variants } from '#build/ui/button'\nimport * as config from '#build/app.config'\n\nexport const useButton = () => ({ slots: theme.slots, size: variants.size, ui: config.default.ui })\n`,
- 'runtime/components/Button.vue': `\n\n\n \n \n`,
- 'runtime/components/Sized.vue': `\n\n\n {{ theme }}
\n \n`,
- })
-
- await copyExample(routesRootDir, contents => contents
- .replace('import { defineNuxtModule, addPlugin, createResolver }', 'import { defineNuxtModule, addPlugin, addServerHandler, createResolver }')
- .replace(`addPlugin(resolver.resolve('./runtime/plugins/plugin'))`, `addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addServerHandler({ route: '/api/own', handler: resolver.resolve('./runtime/server/api/own') })`))
- await writeFiles(routesRootDir, {
- '.nuxtrc': `${(await readFile(join(rootDir, '.nuxtrc'), 'utf-8')).trimEnd()}\nworkspaceDir=..\n`,
- '../tsconfig.json': JSON.stringify({ extends: './mod/playground/.nuxt/tsconfig.json', compilerOptions: { types: ['fake-global-types'] }, exclude: ['**/dist', '**/node_modules'] }),
- 'node_modules/fake-global-types/package.json': JSON.stringify({ name: 'fake-global-types', types: 'index.d.ts' }),
- 'node_modules/fake-global-types/index.d.ts': `declare namespace Fake {\n interface Thing { id: number }\n function current(): Thing\n}\n`,
- 'src/runtime/composables/useGlobal.ts': `export const useGlobal = () => Fake.current()\n`,
- 'src/runtime/server/api/own.ts': `export default () => ({ own: 'module-owned' as const })\n`,
- 'src/runtime/composables/useOwn.ts': `import { useFetch } from '#app'\n\nexport const useOwn = () => useFetch('/api/own')\n`,
- 'src/runtime/composables/useSecret.ts': `import { useFetch } from '#app'\n\nexport const useSecret = () => useFetch('/api/secret')\n`,
- 'src/runtime/composables/useSibling.ts': `import { useFetch } from '#app'\n\nexport const useSibling = () => useFetch('/api/sibling')\n`,
- 'src/runtime/composables/useDocs.ts': `import { useFetch } from '#app'\n\nexport const useDocs = () => useFetch('/api/docs')\n`,
- 'src/runtime/components/Routes.vue': `\n\n\n
\n \n`,
- 'playground/server/api/secret.ts': `export default () => ({ localRoute: 'must-not-be-published' as const })\n`,
- 'playground/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/secret': { default: 'must-not-be-published' }\n }\n}\n`,
- 'docs/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/docs': { default: 'must-not-be-published' }\n }\n}\n`,
- '../sibling/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/sibling': { default: 'must-not-be-published' }\n }\n}\n`,
- })
- await rm(join(routesRootDir, 'tsconfig.json'))
- await cp(join(rootDir, 'package.json'), join(routesRootDir, 'package.json'))
- await rm(join(routesRootDir, 'playground/node_modules/my-module'), { force: true })
- await symlink(routesRootDir, join(routesRootDir, 'playground/node_modules/my-module'))
-
- await rm(sourceFlowRootDir, { recursive: true, force: true })
- await cp(rootDir, sourceFlowRootDir, { recursive: true })
- for (const dir of ['dist', '.nuxt', 'playground/.nuxt', 'playground/.output']) {
- await rm(join(sourceFlowRootDir, dir), { recursive: true, force: true })
- }
- await rm(join(sourceFlowRootDir, 'playground/node_modules/my-module'), { force: true })
- await symlink(sourceFlowRootDir, join(sourceFlowRootDir, 'playground/node_modules/my-module'))
-
- await copyExample(distFlowRootDir, contents => contents)
- const { build: distFlowBuild, ...distFlowPkg } = JSON.parse(await readFile(join(distFlowRootDir, 'package.json'), 'utf-8'))
- await writeFile(join(distFlowRootDir, 'package.json'), JSON.stringify({
- ...distFlowPkg,
- scripts: {
- ...distFlowPkg.scripts,
- 'prepack': `node ${tsdownBin}`,
- 'dev:prepare': `node ../src/cli.ts prepare && node ${tsdownBin} && nuxt prepare playground`,
- },
- }, null, 2))
- await writeFile(join(distFlowRootDir, 'tsdown.config.ts'), `${builderImport}\n\nexport default {\n plugins: [builder(${JSON.stringify(distFlowBuild)})],\n}\n`)
- for (const dir of ['dist', '.nuxt', 'playground/.nuxt']) {
- await rm(join(distFlowRootDir, dir), { recursive: true, force: true })
- }
- await rm(join(distFlowRootDir, 'playground/node_modules/my-module'), { force: true })
- await symlink(distFlowRootDir, join(distFlowRootDir, 'playground/node_modules/my-module'))
- await rm(packDir, { recursive: true, force: true })
- await Promise.all(['source-exports', 'dist'].map(flow => mkdir(join(packDir, flow), { recursive: true })))
-
- const nuxtEnv = { ...process.env, NUXT_TELEMETRY_DISABLED: '1' }
- const runFlow = async ({ name, rootDir: dir, pack: [packCommand, ...packArgs] }: typeof flows[number]) => {
- const playgroundDir = join(dir, 'playground')
- await exec('pnpm', ['dev:prepare'], { nodeOptions: { cwd: dir, env: nuxtEnv }, throwOnError: true })
- const typecheck = (context: string) => exec('pnpm', ['exec', 'vue-tsc', '--noEmit', '-p', join(playgroundDir, `.nuxt/tsconfig.${context}.json`)], { nodeOptions: { cwd: repoRoot } })
- const [appTypes, nodeTypes] = await Promise.all([typecheck('app'), typecheck('node')])
- await exec('pnpm', ['exec', 'nuxt', 'generate', playgroundDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true })
- const pack = await exec(packCommand!, packArgs, { nodeOptions: { cwd: dir }, throwOnError: true })
- flowOutput.set(name, {
- appTypes: appTypes.stdout + appTypes.stderr,
- nodeTypes: nodeTypes.stdout + nodeTypes.stderr,
- pack: pack.stdout + pack.stderr,
- })
- }
-
- await Promise.all([
- exec('pnpm', ['nuxt-module-build', 'prepare', routesRootDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true })
- .then(() => exec('pnpm', ['exec', 'nuxt', 'prepare', join(routesRootDir, 'playground')], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true }))
- .then(() => exec('pnpm', ['nuxt-module-build', 'build', routesRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NODE_ENV: '', TEST: '' } }, throwOnError: true }))
- .then(({ stdout, stderr }) => { routesBuild = stdout + stderr }),
- exec('pnpm', ['nuxt-module-build', 'build', stylesheetsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', runtimeShapeRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- ...flows.map(runFlow),
- exec('pnpm', ['nuxt-module-build', 'prepare', secondRootDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true })
- .then(() => exec('pnpm', ['nuxt-module-build', 'build', secondRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true })),
- exec('pnpm', ['nuxt-module-build', 'build', encodedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', thirdRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', fourthRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', noRuntimeRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', annotatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', vueOnlyRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', wildcardRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', buildConfigRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, CI: '' } }, throwOnError: true })
- .then(({ stdout, stderr }) => { buildConfigBuild = stdout + stderr }),
- exec('pnpm', ['nuxt-module-build', 'build', replaceRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', transpileRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', solutionRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', join(parentTsconfigRootDir, 'packages/mod')], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', portableRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', valueExportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- exec('pnpm', ['nuxt-module-build', 'build', valueExportsIsolatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
- ])
- }, 300 * 1000)
-
- it('should build `build.config.ts` entries under the names unbuild gave them', async () => {
- const files = await listFiles(join(buildConfigRootDir, 'dist'))
- expect(files.filter(file => !file.startsWith('runtime')).sort()).toMatchInlineSnapshot(`
- [
- "content.d.mts",
- "content.mjs",
- "features",
- "features/flag.d.ts",
- "features/flag.js",
- "module.d.mts",
- "module.json",
- "module.mjs",
- "nested",
- "nested/helper.d.mts",
- "nested/helper.mjs",
- "shared",
- "shared/format.d.mts",
- "shared/format.mjs",
- "types.d.mts",
- "utils.d.mts",
- "utils.mjs",
- "vite.d.mts",
- "vite.mjs",
- ]
- `)
- })
-
- it('should import runtime code relative to nested entries', async () => {
- const helper = await readFile(join(buildConfigRootDir, 'dist/nested/helper.mjs'), 'utf-8')
- expect(findStaticImports(helper).map(i => i.specifier)).toEqual(['../runtime/plugins/plugin.js'])
- expect(helper).toContain('import("../runtime/composables/useWrappedFetch.js")')
- expect(helper).not.toContain(buildConfigRootDir)
- })
-
- it('should run `build.config.ts` hooks in order with the build context', async () => {
- const log = (await readFile(join(buildConfigRootDir, 'hooks.log'), 'utf-8')).trim().split('\n').map(line => JSON.parse(line))
- expect(log.slice(0, 3)).toEqual([
- expect.objectContaining({ hook: 'build:before', stub: false }),
- expect.objectContaining({ hook: 'rollup:done', stub: false, meta: true }),
- expect.objectContaining({ hook: 'build:done', stub: false, meta: true }),
- ])
- expect(log[0].entries).toEqual(['content', 'features', 'module', 'nested/helper', 'runtime', 'shared', 'utils', 'vite'])
- expect(await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8')).toContain('from build:before')
- })
-
- it('should read the `unbuild` field of `package.json` in preference to `build`', async () => {
- const unplugin = await readFile(join(replaceRootDir, 'dist/unplugin.mjs'), 'utf-8')
- expect(unplugin).toContain('from "ext-pkg"')
- expect(unplugin).not.toContain('bundled-ext-pkg')
- expect(existsSync(join(replaceRootDir, 'dist/utils.mjs'))).toBe(false)
- })
-
- it('should keep `build.config.ts` externals external', async () => {
- const vite = await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8')
- expect(vite).toContain('from "fake-pkg/sub"')
- expect(vite).toContain('from "regex-pkg"')
- const content = await readFile(join(buildConfigRootDir, 'dist/content.mjs'), 'utf-8')
- expect(content).toContain('from "#content-alias/config"')
- expect(vite + content).not.toContain('bundled-')
- })
-
- it('should apply `build.config.ts` replacements', async () => {
- const vite = await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8')
- expect(vite).toContain('"1.2.3"')
- expect(vite).not.toContain('__MODULE_VERSION__')
-
- const unplugin = await readFile(join(replaceRootDir, 'dist/unplugin.mjs'), 'utf-8')
- expect(unplugin).not.toContain('--uiDev')
- expect(unplugin).toMatch(/isDev = false/)
- })
-
- it('should fail on TypeScript syntax that Node cannot strip, with how to rewrite it', async () => {
- for (const args of [['build'], ['prepare']]) {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', ...args, nonErasableRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode, args.join(' ')).not.toBe(0)
- expect(stdout + stderr, args.join(' ')).toContain([
- 'Module code has to load with Node, which strips types and resolves imports as written:',
- ' - src/levels.ts:1:1: `enum` (use an `as const` object and a union type of its values)',
- ' - src/module.ts:1:37: `../package.json` is JSON (use `import pkg from \'../package.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)',
- ' - src/module.ts:4:1: `enum` (use an `as const` object and a union type of its values)',
- ' - src/module.ts:5:28: parameter property (declare the field and assign it in the constructor)',
- ].join('\n'))
- expect(stdout + stderr, args.join(' ')).toMatch(/src\/module\.ts:\d+:\d+: angle-bracket type assertion \(write `value as Type`\)/)
- expect(stdout + stderr, args.join(' ')).toContain(guide('module-code-loads-with-node'))
- }
- })
-
- it('should refuse an `outDir` that contains the module root', async () => {
- for (const outDir of ['.', '..']) {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', '--outDir', outDir, noRuntimeRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- expect(stdout + stderr).toContain(`\`--outDir ${outDir}\` resolves to \`${resolve(noRuntimeRootDir, outDir)}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`)
- }
- expect(existsSync(join(noRuntimeRootDir, 'package.json'))).toBe(true)
- expect(existsSync(join(repoRoot, 'package.json'))).toBe(true)
- })
-
- it('should warn that `build.config.ts` is deprecated', () => {
- expect(buildConfigBuild).toMatch(new RegExp(`\`build\\.config\\.ts\` is deprecated\\..*${guide('moving-from-buildconfigts')}`))
- expect(buildConfigBuild).not.toContain('instead of')
- expect(buildConfigBuild).not.toContain('`unbuild` field')
- })
-
- it('should fail on every `build.config.ts` option without an equivalent', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', unsupportedRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- for (const option of ['entries[0].ext', 'entries[1].builder: \'untyped\'', 'hooks[\'build:prepare\']', 'hooks[\'rollup:options\']', 'rollup.emitCJS: true', 'rollup.alias', 'stub', 'unknownOption']) {
- expect(stdout + stderr).toContain(`build.config.ts: ${option}`)
- }
- expect(stdout + stderr).not.toContain('build.config.ts: hooks[\'mkdist:entry:options\']')
- expect(stdout + stderr).toContain(`build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`)
- expect(stdout + stderr).toContain(guide('unsupported-build-options'))
- })
-
- it('should surface isolated declaration diagnostics when the tsconfig opts in', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', isolatedRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- expect(stdout + stderr).toMatch(/Declaration generation failed under `?isolatedDeclarations/)
- expect(stdout + stderr).toMatch(/TS90\d\d/)
- expect(stdout + stderr).toContain(guide('isolated-declarations'))
- expect(stdout + stderr).not.toMatch(/Type declarations could not be generated/)
- })
-
- it('should prepare a module without `.nuxt` before building it', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', autoPrepareRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NODE_ENV: '', TEST: '' } } })
- expect(exitCode).toBe(0)
- expect(stdout + stderr).toMatch(new RegExp(`\\.nuxt\`? not found, running \`?nuxt-module-build prepare\`? first\\..*${guide('preparing-nuxt')}`))
- const declaration = await readFile(join(autoPrepareRootDir, 'dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8')
- expect(declaration).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
- })
-
- it('should prepare a module whose entry Node cannot import natively without handing it to jiti', async () => {
- const { stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'prepare', prepareLoaderRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } })
- expect(stderr).not.toContain('ERR_INTERNAL_ASSERTION')
- expect(exitCode).toBe(0)
- expect(await readFile(join(prepareLoaderRootDir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).toContain('/// ')
- const modulesDts = await readFile(join(prepareLoaderRootDir, '.nuxt/types/modules.d.ts'), 'utf-8')
- expect(modulesDts).toContain(`typeof import(${JSON.stringify(join(prepareLoaderRootDir, 'src/module'))}).default`)
- })
-
- it('should explain type errors that prevent declaration generation', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', typeErrorRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- expect(stdout + stderr).toMatch(/TS4094/)
- expect(stdout + stderr).toMatch(/Type declarations could not be generated/)
- expect(stdout + stderr).toMatch(/cannot reference by name.*explicit type annotation, such as `ReturnType` for a value produced by an imported `fn`:\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/)
- expect(stdout + stderr).toContain(guide('portability-errors'))
- expect(existsSync(join(typeErrorRootDir, 'dist'))).toBe(false)
- })
-
- it('should fail on portability errors in a single-file component and in a script sharing its program', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', vueErrorRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- expect(stdout + stderr).toMatch(/components\/Cached\.vue\(4,14\): error TS(?:2742|2883)/)
- expect(stdout + stderr).toMatch(/server\/cached\.ts\(3,14\): error TS(?:2742|2883)/)
- expect(stdout + stderr).toMatch(/cannot reference by name.*:\n(?:- `\w+` in \S+\n)*- `cachedHandler` in \S*src\/runtime\/components\/Cached\.vue:4\n/)
- expect(stdout + stderr).toMatch(/\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/)
- expect(stdout + stderr).toContain(guide('portability-errors'))
- expect(existsSync(join(vueErrorRootDir, 'dist'))).toBe(false)
- })
-
- it('should warn about type errors that do not affect runtime declarations and build anyway', async () => {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', semanticErrorRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).toBe(0)
- expect(stdout + stderr).toMatch(/2 type errors were reported while generating declarations for `?src\/runtime`?; the declarations were emitted\. If the module's own type check \(for example `?nuxt typecheck`? or `?vue-tsc --noEmit`?\) passes/)
- expect(stdout + stderr).toContain('src/runtime/utils/typo.ts(1,14): error TS2322')
- expect(stdout + stderr).toContain('src/runtime/components/Typo.vue(3,7): error TS2322')
- expect((stdout + stderr).match(/type errors? (?:was|were) reported/g)).toHaveLength(1)
- expect(stdout + stderr).toContain(guide('other-type-errors'))
- expect(await readFile(join(semanticErrorRootDir, 'dist/runtime/utils/typo.d.ts'), 'utf-8')).toBe('export declare const count: number;\nexport declare const double: (value: number) => number;\n')
- const component = await readFile(join(semanticErrorRootDir, 'dist/runtime/components/Typo.vue.d.ts'), 'utf-8')
- expect(component).toContain('label: string')
- expect(component).toBe(await readFile(join(semanticErrorRootDir, 'dist/runtime/components/Typo.d.vue.ts'), 'utf-8'))
- expect(stdout + stderr).not.toContain('TS2307')
- const composable = await readFile(join(semanticErrorRootDir, 'dist/runtime/composables/useSize.d.ts'), 'utf-8')
- expect(composable).toContain(`import type { Props } from '../components/Sized.vue';`)
- expect(composable).toMatch(/export declare function useSize\(props: Props\): import\("vue"\)\.ComputedRef<"xs" \| "sm" \| "md" \| undefined>;/)
- })
-
- it('should build an annotated module under `isolatedDeclarations` while still inferring runtime types', async () => {
- const annotatedDistDir = join(annotatedRootDir, 'dist')
- const moduleTypes = await readFile(join(annotatedDistDir, 'module.d.mts'), 'utf-8')
- expect(moduleTypes).toContain('NuxtModule')
- expect(moduleTypes).toMatch(/apiKey: string/)
- const pluginTypes = await readFile(join(annotatedDistDir, 'runtime/plugins/plugin.d.ts'), 'utf-8')
- expect(pluginTypes).toContain('import("nuxt/app").Plugin<')
- expect(JSON.parse(await readFile(join(annotatedDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module', configKey: 'myModule' })
- })
-
- it('should not let a wildcard `paths` entry shadow real packages when loading meta', async () => {
- const meta = JSON.parse(await readFile(join(wildcardRootDir, 'dist/module.json'), 'utf-8'))
- expect(meta).toMatchObject({ name: 'wildcard-module', configKey: 'wildcardModule' })
- })
-
- it('should mirror the runtime source tree even when it has a single subdirectory', async () => {
- const files = await readdir(join(fourthDistDir, 'runtime'), { recursive: true, withFileTypes: true })
- const names = files.filter(file => file.isFile()).map(file => join(file.parentPath, file.name).replace(join(fourthDistDir, 'runtime') + '/', ''))
- expect(names.sort()).toMatchInlineSnapshot(`
- [
- "plugins/plugin.d.ts",
- "plugins/plugin.js",
- ]
- `)
- })
-
- it('should bundle the `imports` of `package.json` and the files they point at', async () => {
- await exec('pnpm', ['nuxt-module-build', 'build', packageImportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true })
- const built = await readFile(join(packageImportsRootDir, 'dist/module.mjs'), 'utf-8')
- expect(built).toContain('loaded helper')
- expect(built).toContain('through imports')
- expect(built).not.toContain('#internal')
- })
-
- it('should re-export the module\'s default export from the types that `prepare` writes', async () => {
- await exec('pnpm', ['nuxt-module-build', 'prepare', packageImportsRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } }, throwOnError: true })
- const probe = join(packageImportsRootDir, 'probe.ts')
- await writeFile(probe, `import type Module from './.nuxt/module-builder/types.mjs'\n\nexport const meta: Promise<{ configKey?: string }> = ({} as typeof Module).getMeta!()\n`)
- const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--ignoreConfig', '--noEmit', '--strict', '--skipLibCheck', '--allowImportingTsExtensions', '--module', 'nodenext', '--moduleResolution', 'nodenext', probe], { nodeOptions: { cwd: repoRoot } })
- expect(stdout + stderr).toBe('')
- expect(exitCode).toBe(0)
- })
-
- it('should fail when module code imports relative files without their extension', async () => {
- const sourceLine = (await readFile(join(extensionlessRootDir, 'src/module.ts'), 'utf-8')).split('\n').findIndex(line => line.includes('./utils.js')) + 1
- for (const args of [['build'], ['prepare']]) {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', ...args, extensionlessRootDir], { nodeOptions: { cwd: repoRoot } })
- expect(exitCode).not.toBe(0)
- expect(stdout + stderr).toContain([
- 'Module code has to load with Node, which strips types and resolves imports as written:',
- ` - src/module.ts:${sourceLine}:31: \`./utils.js\` (use \`./utils.ts\`)`,
- ` - src/module.ts:${sourceLine + 1}:24: \`./helpers\` (use \`./helpers.ts\`)`,
- ` - src/module.ts:${sourceLine + 2}:21: \`./kit\` (use \`./kit/index.ts\`)`,
- `Change each one as suggested. ${guide('module-code-loads-with-node')}`,
- ].join('\n'))
- expect(stdout + stderr).not.toContain(`:${sourceLine + 3}:`)
- }
- expect(existsSync(join(extensionlessRootDir, 'dist'))).toBe(false)
- })
-
- it('should build a module without a runtime directory', async () => {
- const files = await readdir(join(noRuntimeRootDir, 'dist'))
- expect(files.sort()).toEqual(['module.d.mts', 'module.json', 'module.mjs', 'types.d.mts', 'utils.d.mts', 'utils.mjs'])
- })
-
- it('should build a runtime directory that contains only single-file components', async () => {
- const files = await listFiles(join(vueOnlyRootDir, 'dist/runtime'))
- expect(files.sort()).toMatchInlineSnapshot(`
- [
- "components",
- "components/TestMe.css",
- "components/TestMe.d.vue.ts",
- "components/TestMe.vue",
- "components/TestMe.vue.d.ts",
- "components/TestMeSetup.d.vue.ts",
- "components/TestMeSetup.vue",
- "components/TestMeSetup.vue.d.ts",
- ]
- `)
- })
-
- it('should flatten, prefix and minify runtime CSS', async () => {
- const card = await readFile(join(stylesheetsRootDir, 'dist/runtime/styles/card.css'), 'utf-8')
- expect(card).toMatch(/^@import "\.\/base\.css";/)
- expect(card).toContain('.card .title{font-weight:700}')
- expect(card).toContain('.card:hover{color:#639}')
- expect(card).toContain('-webkit-user-select:none')
- expect(card).not.toMatch(/&|\n/)
- })
-
- it('should compile runtime Sass to CSS and skip partials', async () => {
- const styles = join(stylesheetsRootDir, 'dist/runtime/styles')
- expect((await readdir(styles)).sort()).toEqual(['base.css', 'card.css', 'indented.css', 'legacy.less', 'theme.css'])
- expect(await readFile(join(styles, 'theme.css'), 'utf-8')).toMatch(/^\.theme \.nested \{\s*padding: 1px;\s*\}$/m)
- expect(await readFile(join(styles, 'theme.css'), 'utf-8')).toContain('color: #00dc82;')
- expect(await readFile(join(styles, 'indented.css'), 'utf-8')).toContain('color: blue;')
- })
-
- it('should copy runtime declaration files verbatim', async () => {
- const file = 'types/ambient.d.ts'
- expect(await readFile(join(stylesheetsRootDir, 'dist/runtime', file), 'utf-8')).toBe(await readFile(join(stylesheetsRootDir, 'src/runtime', file), 'utf-8'))
- })
-
- it('should rewrite `#app` in copied runtime declaration files', async () => {
- expect(await readFile(join(stylesheetsRootDir, 'dist/runtime/types/app.d.ts'), 'utf-8')).toBe(`import type { NuxtApp } from 'nuxt/app'\nexport type App = NuxtApp\n`)
- })
-
- it('should point stylesheet imports in runtime scripts at the emitted files', async () => {
- const styled = await readFile(join(stylesheetsRootDir, 'dist/runtime/plugins/styled.js'), 'utf-8')
- expect(styled).toContain('import "../styles/card.css";')
- expect(styled).toContain('import "../styles/theme.css";')
- expect(styled).not.toContain('theme.scss')
- })
-
- it('should keep every non-relative runtime import as written', async () => {
- const handler = await readFile(join(transpileRootDir, 'dist/runtime/server/handler.js'), 'utf-8')
- expect(findStaticImports(handler).map(i => i.specifier)).toEqual([
- '#internal/nuxt.config.mjs',
- '~/app.config',
- '@/root',
- '#app',
- 'fake-dep',
- '#fixture-cache',
- '../utils/local.js',
- ])
- const options = await readFile(join(transpileRootDir, 'dist/runtime/utils/options.d.ts'), 'utf-8')
- expect(findStaticImports(options).map(i => i.specifier)).toEqual(['fake-types'])
- })
-
- it('should not emit dependencies or bundler helpers into the runtime directory', async () => {
- const files = await listFiles(join(transpileRootDir, 'dist/runtime'))
- expect(files.filter(file => /node_modules|_virtual/.test(file))).toEqual([])
- for (const file of files.filter(file => /\.m?[jt]s$/.test(file))) {
- expect(await readFile(join(transpileRootDir, 'dist/runtime', file), 'utf-8'), file).not.toMatch(/bundled-fake-dep|DeepPartial/)
- }
- })
-
- it('should keep types of packages that are not dependencies external in module declarations', async () => {
- const types = await readFile(join(transpileRootDir, 'dist/module.d.mts'), 'utf-8')
- expect(types).toMatch(/from "fake-types"/)
- expect(types).toMatch(/from "fake-cjs-types"/)
- expect(types).not.toMatch(/DeepPartial/)
- })
-
- it('should keep bracketed file names in runtime output', async () => {
- expect(existsSync(join(transpileRootDir, 'dist/runtime/server/routes/[...slug].js'))).toBe(true)
- expect(existsSync(join(transpileRootDir, 'dist/runtime/server/routes/[...slug].d.ts'))).toBe(true)
- })
-
- it('should resolve imports of the package itself to its source in declarations', async () => {
- const types = await readFile(join(transpileRootDir, 'dist/runtime/utils/self.d.ts'), 'utf-8')
- expect(types).toMatch(/=> string;/)
- })
-
- it('should generate declarations for each project of a solution-style tsconfig', async () => {
- const route = await readFile(join(solutionRootDir, 'dist/runtime/server/api/[id].get.d.ts'), 'utf-8')
- expect(route).toMatch(/=> string;/)
- const app = await readFile(join(solutionRootDir, 'dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8')
- expect(app).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
- expect(existsSync(join(solutionRootDir, 'dist/runtime/components/TestMe.vue.d.ts'))).toBe(true)
- })
-
- it('should use a tsconfig from a parent directory', async () => {
- const app = await readFile(join(parentTsconfigRootDir, 'packages/mod/dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8')
- expect(app).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
- })
-
- it('should name runtime types by package when the generated tsconfig maps the package into the store', async () => {
- const logger = await readFile(join(parentTsconfigRootDir, 'packages/mod/dist/runtime/logger.d.ts'), 'utf-8')
- expect(logger).toMatch(/import\("fake-logger"\)\.LoggerInstance/)
- })
-
- it('should keep the imports and re-exports of each runtime file as written', async () => {
- const dist = join(runtimeShapeRootDir, 'dist/runtime')
- const read = (file: string) => readFile(join(dist, file), 'utf-8')
- expect(await read('disabled/index.js')).toMatchInlineSnapshot(`
- "import "./side.js";
- export { defineThing } from "./composables/defineThing.js";
- "
- `)
- expect(await read('disabled/composables/defineThing.js')).toMatchInlineSnapshot(`
- "export { defineThing } from "../../composables/mock.js";
- "
- `)
- expect(await read('content/index.js')).toMatchInlineSnapshot(`
- "export * from "../components/TestMe.vue";
- export * from "../components/TestMeSetup.vue";
- export * from "./prose.js";
- "
- `)
- expect(await read('content/index.d.ts')).toMatchInlineSnapshot(`
- "export * from '../components/TestMe.vue';
- export * from '../components/TestMeSetup.vue';
- export * from './prose.js';
- "
- `)
- expect(await read('content/prose.js')).toMatchInlineSnapshot(`
- "export * from "./levels.js";
- "
- `)
- expect(await read('content/prose.d.ts')).toMatchInlineSnapshot(`
- "export * from './levels.js';
- export interface ProseThing {
- title: string;
- }
- "
- `)
- })
-
- it('should keep the source order of imports and re-exports in each runtime file', async () => {
- const dist = join(runtimeShapeRootDir, 'dist/runtime/order')
- expect(await readFile(join(dist, 'interleaved.js'), 'utf-8')).toMatchInlineSnapshot(`
- "import "fake-register";
- import { level } from "./levels.js";
- export * from "./reexported.js";
- import "./order.css";
- export { useState } from "#imports";
- import "fake-polyfill";
- import "./effect.js";
- import { ref } from "vue";
- export const value = ref(level);
- "
- `)
- })
-
- it('should point runtime imports outside the runtime directory at the files emitted for them', async () => {
- const dist = join(runtimeShapeRootDir, 'dist')
- expect(await readFile(join(dist, 'runtime/server/uses.js'), 'utf-8')).toMatchInlineSnapshot(`
- "import { merge } from "../../utils/merge.mjs";
- import { CONSTANT } from "../../shared/constants.js";
- export const combine = (a, b) => [merge(a, b), CONSTANT];
- "
- `)
- expect(await readFile(join(dist, 'runtime/server/uses.d.ts'), 'utf-8')).toMatchInlineSnapshot(`
- "import type { RootType } from '../../_external/src/types.js';
- import type { RuntimeType } from '../types.js';
- export declare const combine: (a: RootType & RuntimeType, b: RootType & RuntimeType) => readonly [RootType & RuntimeType, 10];
- "
- `)
- expect(await readFile(join(dist, 'runtime/escaping.js'), 'utf-8')).toContain(`import("../_external/external.js")`)
- expect(await readFile(join(dist, 'shared/constants.js'), 'utf-8')).toMatchInlineSnapshot(`
- "import { LIMIT } from "./limits.js";
- export const CONSTANT = LIMIT;
- "
- `)
- const files = await listFiles(dist)
- expect(files.filter(file => !file.startsWith('runtime')).sort()).toMatchInlineSnapshot(`
- [
- "_external",
- "_external/external.d.ts",
- "_external/external.js",
- "_external/src",
- "_external/src/types.d.ts",
- "data.d.mts",
- "data.mjs",
- "module.d.mts",
- "module.json",
- "module.mjs",
- "routing.d.ts",
- "shared",
- "shared/constants.d.ts",
- "shared/constants.js",
- "shared/limits.d.ts",
- "shared/limits.js",
- "types",
- "types.d.mts",
- "types/middlewares.d.ts",
- "utils",
- "utils.d.mts",
- "utils.mjs",
- "utils/merge.d.mts",
- "utils/merge.mjs",
- ]
- `)
- expect(files.filter(file => /^runtime\/(?:types|server|utils)/.test(file)).sort()).toMatchInlineSnapshot(`
- [
- "runtime/server",
- "runtime/server/limiter.d.ts",
- "runtime/server/limiter.js",
- "runtime/server/uses.d.ts",
- "runtime/server/uses.js",
- "runtime/types.d.ts",
- "runtime/types.js",
- "runtime/utils",
- "runtime/utils/props.d.ts",
- "runtime/utils/props.js",
- "runtime/utils/provider.d.ts",
- "runtime/utils/provider.js",
- ]
- `)
- })
-
- it('should emit only declarations for files outside the runtime directory that runtime files use as types', async () => {
- const dist = join(runtimeShapeRootDir, 'dist')
- expect(await readFile(join(dist, 'runtime/server/limiter.js'), 'utf-8')).toMatchInlineSnapshot(`
- "import "../disabled/side.js";
- export const limit = (options) => options.maxRequestSizeInBytes;
- "
- `)
- expect(await readFile(join(dist, 'runtime/composables/useLocaleRoute.js'), 'utf-8')).toMatchInlineSnapshot(`
- "export const useLocaleRoute = (route) => route;
- "
- `)
- expect(await readFile(join(dist, 'routing.d.ts'), 'utf-8')).toMatchInlineSnapshot(`
- "import type { RootType } from './_external/src/types.js';
- export interface RouteInfo {
- path: string;
- root: RootType;
- }
- export declare const localizeRoutes: (file: string) => string;
- "
- `)
- for (const file of ['routing.js', 'kit', 'types/middlewares.js', 'types.d.ts', 'types.js', '_external/src/types.js']) {
- expect(existsSync(join(dist, file)), file).toBe(false)
- }
- })
-
- it('should type imports of build-time aliases as `any` in declarations', async () => {
- const dist = join(runtimeShapeRootDir, 'dist/runtime')
- expect(await readFile(join(dist, 'composables/useThemeConfig.d.ts'), 'utf-8')).toContain('useThemeConfig: () => any;')
- expect(await readFile(join(dist, 'composables/useButton.d.ts'), 'utf-8')).toMatchInlineSnapshot(`
- "export declare const useButton: () => {
- slots: any;
- size: any;
- ui: any;
- };
- "
- `)
- expect(await readFile(join(dist, 'components/Button.d.vue.ts'), 'utf-8')).toMatchInlineSnapshot(`
- "type __VLS_Props = {
- size?: string;
- };
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {
- classes: any[];
- }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
- declare const _default: typeof __VLS_export;
- export default _default;
- "
- `)
- expect(existsSync(join(dist, 'components/Sized.vue.d.ts'))).toBe(true)
- })
-
- it('should generate declarations with the module\'s own `.nuxt` when the tsconfig takes its types from a playground', async () => {
- expect(routesBuild).toMatch(new RegExp(`\\.\\./tsconfig.json\`? takes its generated types from another app's \`?.nuxt\`?; declarations are generated with \`?.nuxt/tsconfig.json\`? instead. Add a \`?tsconfig.json\`? in the module directory that extends \`?./.nuxt/tsconfig.json\`?. ${guide('module-tsconfig')}`))
- expect(await readFile(join(routesRootDir, 'playground/.nuxt/types/nitro-routes.d.ts'), 'utf-8')).toContain('/api/secret')
- for (const file of await listFiles(join(routesRootDir, 'dist'))) {
- if (file.includes('.')) {
- expect(await readFile(join(routesRootDir, 'dist', file), 'utf-8'), file).not.toMatch(/must-not-be-published|playground|\.nuxt/)
- }
- }
- })
-
- it('should type the responses of routes the module registers and leave other routes unknown', async () => {
- expect(await readFile(join(routesRootDir, '.nuxt/types/nitro-routes.d.ts'), 'utf-8')).toContain('/api/own')
- const { default: ts } = await import('typescript')
- const files = ts.getParsedCommandLineOfConfigFile(join(routesRootDir, '.nuxt/tsconfig.json'), {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} })!.fileNames
- expect(files.map(file => relative(routesRootDir, file)).filter(file => file.includes('routes.d.ts')).sort()).toEqual(['../sibling/types/routes.d.ts', 'docs/types/routes.d.ts', 'playground/types/routes.d.ts'])
- expect(await readFile(join(routesRootDir, 'dist/runtime/composables/useOwn.d.ts'), 'utf-8')).toBe(`export declare const useOwn: () => import("nuxt/app").AsyncData<{\n own: "module-owned";\n} | undefined, import("nuxt/app").NuxtError | undefined>;\n`)
- expect(await readFile(join(routesRootDir, 'dist/runtime/composables/useGlobal.d.ts'), 'utf-8')).toBe('export declare const useGlobal: () => Fake.Thing;\n')
- expect(routesBuild).not.toMatch(/type errors? (?:was|were) reported/)
- for (const name of ['useSecret', 'useSibling', 'useDocs']) {
- expect(await readFile(join(routesRootDir, `dist/runtime/composables/${name}.d.ts`), 'utf-8'), name).toBe(`export declare const ${name}: () => import("nuxt/app").AsyncData | undefined>;\n`)
- }
- const component = await readFile(join(routesRootDir, 'dist/runtime/components/Routes.vue.d.ts'), 'utf-8')
- expect(component).toContain('own: import("vue").Ref<{\n own: "module-owned";\n } | undefined, {\n own: "module-owned";\n } | undefined>;')
- expect(component).toContain('secret: import("vue").Ref;')
- })
-
- it('should give every relative specifier in runtime declarations an extension that resolves', async () => {
- expect(await unresolvedSpecifiers(join(runtimeShapeRootDir, 'dist'))).toEqual([])
- })
-
- it('should name inferred types by package when the generated tsconfig maps a package to its real path', async () => {
- const types = await readFile(join(portableRootDir, 'dist/module.d.mts'), 'utf-8')
- expect(types).toMatch(/Thing<\{/)
- expect(types).toMatch(/["']fake-schema["']/)
- })
-
- it('should keep value exports as values in `types.d.mts`', async () => {
- const types = await readFile(join(valueExportsRootDir, 'dist/types.d.mts'), 'utf-8')
- expect(types).toMatchInlineSnapshot(`
- "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
-
- declare module '#app' {
- interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
- }
-
- declare module '@nuxt/schema' {
- interface NuxtHooks extends ModuleHooks {}
- interface RuntimeConfig extends ModuleRuntimeConfig {}
- interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
- }
-
- export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs'
- "
- `)
- expect(await readFile(join(valueExportsIsolatedRootDir, 'dist/types.d.mts'), 'utf-8')).toBe(types)
-
- for (const root of [valueExportsRootDir, valueExportsIsolatedRootDir]) {
- const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--noEmit', '-p', join(root, 'playground/consumer.tsconfig.json')], { nodeOptions: { cwd: repoRoot } })
- expect(stdout + stderr, root).toBe('')
- expect(exitCode).toBe(0)
- }
- })
-
- it('should generate types when no ModuleOptions are exported', async () => {
- const types = await readFile(join(secondDistDir, 'types.d.mts'), 'utf-8')
- expect(types).toMatchInlineSnapshot(`
- "import type { NuxtModule } from '@nuxt/schema'
-
- import type { default as Module, ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
-
- declare module '#app' {
- interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
- }
-
- declare module '@nuxt/schema' {
- interface NuxtHooks extends ModuleHooks {}
- interface RuntimeConfig extends ModuleRuntimeConfig {}
- interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
- }
-
- export type ModuleOptions = typeof Module extends NuxtModule ? Partial : Record
-
- export { type ModuleHooks, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs'
- "
- `)
- })
-
- it('should generate module metadata when the module entry imports runtime code', async () => {
- const meta = await readFile(join(thirdDistDir, 'module.json'), 'utf-8')
- expect(JSON.parse(meta)).toMatchObject({ configKey: 'myModule', name: 'my-module' })
- })
-
- it('should externalise runtime imports made through relative, aliased and `.vue` specifiers', async () => {
- const moduleCode = await readFile(join(thirdDistDir, 'module.mjs'), 'utf-8')
- const specifiers = findStaticImports(moduleCode).map(i => i.specifier).filter(s => s.includes('runtime'))
- expect(specifiers.sort()).toMatchInlineSnapshot(`
- [
- "./runtime/composables/useShape.js",
- "./runtime/utils/aliased.js",
- "./runtime/utils/name.js",
- ]
- `)
- })
-
- it('should add extensions to runtime imports when the path has spaces or non-ASCII characters', async () => {
- const moduleDts = await readFile(join(encodedRootDir, 'dist/module.d.mts'), 'utf-8')
- const runtimeImport = findStaticImports(moduleDts).find(i => i.specifier.includes('runtime'))
- expect(runtimeImport!.code.trim()).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`)
- })
-
- it('should build a module under a path with spaces and non-ASCII characters', async () => {
- const encodedDistDir = join(encodedRootDir, 'dist')
- const runtimeSpecifiers = (code: string) => findStaticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort()
-
- expect(runtimeSpecifiers(await readFile(join(encodedDistDir, 'module.mjs'), 'utf-8'))).toEqual([
- './runtime/composables/useShape.js',
- './runtime/utils/aliased.js',
- './runtime/utils/name.js',
- ])
- expect(JSON.parse(await readFile(join(encodedDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module', configKey: 'myModule' })
- expect(await readFile(join(encodedDistDir, 'types.d.mts'), 'utf-8')).toContain('from \'./module.mjs\'')
-
- const runtimeFiles = (dir: string) => listFiles(join(dir, 'runtime')).then(files => files.sort())
- expect(await runtimeFiles(encodedDistDir)).toEqual(await runtimeFiles(thirdDistDir))
- })
-
- it('should point imports of a runtime JSX file at its `.jsx` output', async () => {
- const runtime = join(thirdDistDir, 'runtime')
- expect(await readFile(join(runtime, 'components/JsxCard.vue'), 'utf-8')).toContain(`import JsxComponent from "./JsxComponent.jsx";`)
- expect(await readFile(join(runtime, 'components/JsxSlot.jsx'), 'utf-8')).toMatchInlineSnapshot(`
- "import { defineComponent } from "vue";
- import { useNuxtApp } from "#app";
- import JsxComponent from "./JsxComponent.jsx";
- export const useSlotApp = () => useNuxtApp();
- export default defineComponent((_, { slots }) => () => );
- "
- `)
- expect(await readFile(join(runtime, 'components/JsxSlot.d.ts'), 'utf-8')).toContain('export declare const useSlotApp: () => import("nuxt/app").NuxtApp;')
- const moduleDts = await readFile(join(thirdDistDir, 'module.d.mts'), 'utf-8')
- expect(findStaticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx')
- })
-
- it('should compile JSX in server runtime files and the files they import, and preserve it elsewhere', async () => {
- const runtime = join(thirdDistDir, 'runtime')
- expect(existsSync(join(runtime, 'server/render.jsx'))).toBe(false)
- for (const file of ['utils/strong.js', 'utils/bold.js']) {
- expect(await readFile(join(runtime, file), 'utf-8'), file).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`)
- }
- expect(await readFile(join(runtime, 'utils/label.jsx'), 'utf-8')).toContain('label ')
- expect(JSON.parse(await readFile(join(thirdDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module' })
- expect(await readFile(join(runtime, 'server/render.js'), 'utf-8')).toMatchInlineSnapshot(`
- "import { strong } from "../utils/strong.js";
- import { jsx as _jsx } from "vue/jsx-runtime";
- export const render = (label) => /* @__PURE__ */ _jsx("p", { children: strong(label) });
- "
- `)
- expect(await readFile(join(runtime, 'server/render.d.ts'), 'utf-8')).toMatchInlineSnapshot(`
- "import { useSlotApp } from '../components/JsxSlot.jsx';
- export type SlotApp = ReturnType;
- export declare const render: (label: string) => import("vue/jsx-runtime").JSX.Element;
- "
- `)
- })
-
- describe('with plain `tsdown` and `builder()`', () => {
- const env = { ...process.env, NODE_ENV: '', TEST: '' }
- const ejectedExampleRootDir = rootDir.replace('example', '.temp-example-ejected')
-
- const hashDir = async (dir: string) => {
- const files = (await readdir(dir, { recursive: true, withFileTypes: true })).filter(file => file.isFile())
- return Object.fromEntries(await Promise.all(files.map(async (file) => {
- const path = join(file.parentPath, file.name)
- return [relative(dir, path), createHash('sha256').update(await readFile(path)).digest('hex')] as const
- })))
- }
-
- const writeTsdownConfig = (dir: string, options: string, { imports = [] as string[], hooks = [] as string[] } = {}) => writeFile(join(dir, 'tsdown.config.ts'), [
- builderImport,
- ...imports,
- '',
- 'export default {',
- ...hooks,
- ` plugins: [builder(${options})],`,
- '}',
- '',
- ].join('\n'))
-
- const eject = async (dir: string) => {
- const pkgPath = join(dir, 'package.json')
- const { build, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8'))
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2))
- await writeTsdownConfig(dir, build ? JSON.stringify(build) : '')
- }
-
- const ejectBuildConfig = async (dir: string) => {
- const pkgPath = join(dir, 'package.json')
- const { build: _, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8'))
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2))
- await rm(join(dir, 'build.config.ts'))
- await writeTsdownConfig(dir, `{
- entries: ['src/utils', './src/vite.ts', { input: 'src/content', name: 'content' }, 'src/nested/helper', { input: 'src/shared/', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }],
- externals,
- replace: { __MODULE_VERSION__: JSON.stringify('1.2.3') },
- }`, {
- imports: [`import { writeFileSync } from 'node:fs'`, `import { join } from 'node:path'`, `import { externals } from './build/externals.ts'`],
- hooks: [
- ` hooks: {`,
- ` 'build:prepare'(ctx) {`,
- ` writeFileSync(join(ctx.options.cwd, 'src/generated.ts'), 'export const generated = "from build:before"\\n')`,
- ` },`,
- ` },`,
- ],
- })
- }
-
- const ejectReplace = async (dir: string) => {
- const pkgPath = join(dir, 'package.json')
- const { build: _build, unbuild: _unbuild, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8'))
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2))
- await rm(join(dir, 'build.config.ts'))
- await writeTsdownConfig(dir, `{
- entries: ['./src/unplugin'],
- externals: ['#build/ui', 'ext-pkg'],
- replace: { delimiters: ['', ''], values: { "process.argv.includes('--uiDev')": 'false' } },
- }`)
- }
-
- it('should build the same `dist` as `nuxt-module-build build` did without it, for every module that builds', async () => {
- await rm(ejectedExampleRootDir, { recursive: true, force: true })
- await cp(rootDir, ejectedExampleRootDir, { recursive: true })
- const fixtures: Array<[dir: string, eject: (dir: string) => Promise]> = [
- [ejectedExampleRootDir, eject],
- ...[secondRootDir, thirdRootDir, fourthRootDir, encodedRootDir, noRuntimeRootDir, vueOnlyRootDir, annotatedRootDir, transpileRootDir, solutionRootDir, join(parentTsconfigRootDir, 'packages/mod'), portableRootDir, stylesheetsRootDir, runtimeShapeRootDir, routesRootDir, autoPrepareRootDir, semanticErrorRootDir].map(dir => [dir, eject] as [string, typeof eject]),
- [buildConfigRootDir, ejectBuildConfig],
- [replaceRootDir, ejectReplace],
- ]
- await Promise.all(fixtures.map(async ([dir, ejectFixture]) => {
- await exec('pnpm', ['nuxt-module-build', 'build', dir], { nodeOptions: { cwd: repoRoot, env }, throwOnError: true })
- const built = await hashDir(join(dir, 'dist'))
- expect(Object.keys(built), dir).toContain('module.json')
- await ejectFixture(dir)
- await exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env }, throwOnError: true })
- expect(await hashDir(join(dir, 'dist')), dir).toEqual(built)
- await exec('pnpm', ['nuxt-module-build', 'build', dir], { nodeOptions: { cwd: repoRoot, env }, throwOnError: true })
- expect(await hashDir(join(dir, 'dist')), dir).toEqual(built)
- }))
- }, 300 * 1000)
-
- it('should explain failed builds and remove their partial output', async () => {
- await Promise.all([typeErrorRootDir, vueErrorRootDir, isolatedRootDir].map(eject))
- const [typeError, vueError, isolated] = await Promise.all([typeErrorRootDir, vueErrorRootDir, isolatedRootDir].map(dir => exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env } })))
- for (const [result, dir] of [[typeError, typeErrorRootDir], [vueError, vueErrorRootDir]] as const) {
- expect(result!.exitCode, dir).not.toBe(0)
- expect(result!.stdout + result!.stderr, dir).toContain('Type declarations could not be generated')
- expect(existsSync(join(dir, 'dist')), dir).toBe(false)
- }
- expect(isolated!.exitCode).not.toBe(0)
- expect(isolated!.stdout + isolated!.stderr).toMatch(/Declaration generation failed under `?isolatedDeclarations/)
- })
- })
-
- it('should pack the `dist` paths in `publishConfig` with pnpm, and `dist` with npm, without warnings', async () => {
- const packed = async (flow: string) => JSON.parse((await exec('tar', ['-xzOf', join(packDir, flow, 'my-module-1.0.0.tgz'), 'package/package.json'], { throwOnError: true })).stdout)
- const { publishConfig } = JSON.parse(await readFile(join(rootDir, 'package.json'), 'utf-8'))
- expect(await packed('source-exports')).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main })
- expect(await packed('source-exports')).not.toHaveProperty('publishConfig')
- expect(await packed('dist')).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main })
- for (const flow of flows) {
- const output = flowOutput.get(flow.name)!.pack
- expect(output, flow.name).toContain('Build complete')
- expect(output, flow.name).not.toContain('`package.json`')
- }
- })
-
- it('should refuse to build source exports for a pack by npm, including when a pnpm script runs it', async () => {
- const { stdout, stderr, exitCode } = await exec('node', [...packProbeArgs, join(repoRoot, 'src/cli.ts'), 'build'], { nodeOptions: { cwd: sourceFlowRootDir, env: npmPackFromPnpmScript() } })
- expect(exitCode, `${packProbeContext()}\n${stdout}${stderr}`).not.toBe(0)
- expect(stdout + stderr).toMatch(/`npm(?:@[\d.]+)?` packs these fields of `package\.json` as written, and they point at TypeScript sources or paths that `files` leaves out: `exports`, `main` \(`\.\/\.nuxt\/module-builder\/types\.d\.mts`, `\.\/src\/module\.ts`, `\.\/src\/utils\.ts`\)\./)
- expect(existsSync(join(sourceFlowRootDir, 'dist/module.mjs'))).toBe(true)
- })
-
- describe.each(flows)('$name flow', ({ name, rootDir, nodeTypeErrors }) => {
- const distDir = join(rootDir, 'dist')
- const runtimeDir = join(distDir, 'runtime')
- const typeErrors = (output: string) => output.split('\n').filter(line => line.includes('error TS'))
-
- it('should type the playground and its config through the module\'s exports', () => {
- expect(typeErrors(flowOutput.get(name)!.appTypes)).toEqual([])
- expect(typeErrors(flowOutput.get(name)!.nodeTypes)).toEqual(nodeTypeErrors)
- })
-
- it('should render the playground with the module installed by name', async () => {
- expect(await readFile(join(rootDir, 'playground/.output/public/index.html'), 'utf-8')).toContain('Nuxt module playground!')
- })
-
- it('should reference `@nuxt/schema` rather than `nuxt/schema` in module declarations', async () => {
- const types = await readFile(join(distDir, 'module.d.mts'), 'utf-8')
- expect(types).toContain('import("@nuxt/schema")')
- expect(types).not.toContain('import("nuxt/schema")')
- })
-
- it('should generate all files', async () => {
- const files = await readdir(distDir)
- expect(files).toMatchInlineSnapshot(`
- [
- "module.d.mts",
- "module.json",
- "module.mjs",
- "runtime",
- "types.d.mts",
- "utils.d.mts",
- "utils.mjs",
- ]
- `)
-
- const runtime = await readdir(join(runtimeDir, 'plugins'))
- expect(runtime).toMatchInlineSnapshot(`
- [
- "plugin.d.ts",
- "plugin.js",
- ]
- `)
- })
-
- it('should copy non-code files in the runtime directory', async () => {
- expect(await readdir(join(runtimeDir, 'assets'))).toMatchInlineSnapshot(`
- [
- "config.json",
- ]
- `)
- expect(await readFile(join(runtimeDir, 'components/TestMe.css'), 'utf-8')).toBe('.test-me{color:#639}')
- })
-
- it('should give every relative specifier in runtime declarations an extension that resolves', async () => {
- expect(await unresolvedSpecifiers(runtimeDir)).toEqual([])
- })
-
- it('should write types to output directory', async () => {
- const types = await readFile(join(distDir, 'types.d.mts'), 'utf-8')
- expect(types).toMatchInlineSnapshot(`
- "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
-
- declare module '#app' {
- interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
- }
-
- declare module '@nuxt/schema' {
- interface NuxtHooks extends ModuleHooks {}
- interface RuntimeConfig extends ModuleRuntimeConfig {}
- interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
- }
-
- export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs'
- "
- `)
- })
-
- it('should generate module metadata as separate JSON file', async () => {
- const meta = await readFile(join(distDir, 'module.json'), 'utf-8')
- const tsdownPkg = await readPackageJSON('tsdown')
- expect(JSON.parse(meta)).toMatchObject(
- {
- builder: {
- '@nuxt/module-builder': version,
- 'tsdown': tsdownPkg.version,
- },
- configKey: 'myModule',
- name: 'my-module',
- version: '1.0.0',
- },
- )
- })
-
- it('should generate typed plugin', async () => {
- const pluginDts = await readFile(join(distDir, 'runtime/plugins/plugin.d.ts'), 'utf-8')
- const appAlias = `import\\("nuxt/app"\\)`
- expect(pluginDts).toMatch(/^export type SharedTypeFromRuntime = 'shared-type';$/m)
- expect(pluginDts).toMatch(
- new RegExp(
- `declare const _default: ${appAlias}\\.Plugin<\\{\\s*injection: "injected";\\s*\\}> & ${appAlias}\\.ObjectPlugin<\\{\\s*injection: "injected";\\s*\\}>;`,
- ),
- )
- expect(pluginDts).toMatch(/^export default _default;$/m)
- })
-
- it('should not leak build-only virtual aliases into emitted runtime declarations', async () => {
- const files = await listFiles(runtimeDir)
- const declarations = files.filter(file => /\.d\.[^/]*ts$/.test(file))
- expect(declarations.length).toBeGreaterThan(0)
- for (const file of declarations) {
- const contents = await readFile(join(runtimeDir, file), 'utf-8')
- expect(contents, file).not.toMatch(/(["'])#app(?:\/[^"']*)?\1/)
- expect(contents, file).not.toMatch(/import\("#app(?:\/[^"]*)?"\)/)
- }
- })
-
- it('should resolve every shape of `#app` alias in runtime declarations', async () => {
- const declaration = await readFile(join(runtimeDir, 'composables/useAliasedApp.d.ts'), 'utf-8')
- expect(declaration).toMatch(/declare const useAppInstance: \(\) => import\("nuxt\/app"\)\.NuxtApp;/)
- expect(declaration).toMatch(/declare const useAppRouter: \(\) => import\("vue-router"\)\./)
- expect(declaration).toMatch(/declare const useAppCookie: \(name: string\) => import\("nuxt\/app"\)\.CookieRef)
- const deepDeclaration = await readFile(join(runtimeDir, 'composables/useAppNuxt.d.ts'), 'utf-8')
- expect(deepDeclaration).toMatch(/declare const useAppFromNuxt: \(\) => import\("nuxt\/app"\)\.NuxtApp;/)
- })
-
- it('should correctly add extensions to imports from runtime/ directory', async () => {
- const moduleDts = await readFile(join(distDir, 'module.d.mts'), 'utf-8')
- const runtimeImport = findStaticImports(moduleDts).find(i => i.specifier.includes('runtime'))
- expect(runtimeImport!.code.trim()).toMatchInlineSnapshot(`"import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";"`)
- })
-
- it('should generate components correctly', async () => {
- const componentFile = await readFile(join(distDir, 'runtime/components/TestMe.vue'), 'utf-8')
- await expect(componentFile.replace(/\r\n/g, '\n')).toMatchFileSnapshot('__snapshots__/TestMe.vue')
-
- const componentDeclarationFile = await readFile(join(distDir, 'runtime/components/TestMe.vue.d.ts'), 'utf-8')
- await expect(componentDeclarationFile.replace(/\r\n/g, '\n')).toMatchFileSnapshot('__snapshots__/TestMe.vue.d.ts')
- })
-
- it('should generate components with \n\n\n
\n \n`,
+ 'src/runtime/components/ThingState.vue': `\n\n\n \n \n`,
+ 'test/fixture/nuxt.config.ts': `export default defineNuxtConfig({})\n`,
+ 'src/runtime/fields.ts': FIELDS,
+ 'src/runtime/server/fields.ts': FIELDS,
+ 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.server.json', compilerOptions: { useDefineForClassFields: false } }),
+ [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`,
+ [`${store('fake-logger')}/index.js`]: `export const createLogger = () => ({ log: console.log })\n`,
+ [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`,
+ [`${store('fake-shared')}/index.js`]: `import { createLogger } from 'fake-logger'\nexport const createModuleLogger = () => createLogger()\n`,
+ 'src/runtime/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`,
+ 'src/runtime/server/log.ts': `import { createLogger } from 'fake-logger'\n\nexport const serverLogger = createLogger()\n`,
+ 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json', './tsconfig.server.json')), compilerOptions: { types: ['vitest/importMeta'] } }),
+ },
+ links: {
+ 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger': store('fake-logger'),
+ 'node_modules/fake-logger': store('fake-logger'),
+ 'node_modules/fake-shared': store('fake-shared'),
+ },
+ })
+
+ const moduleProject = {
+ 'tsconfig.module.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { erasableSyntaxOnly: true, useDefineForClassFields: false } }),
+ 'tsconfig.override.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { useDefineForClassFields: true } }),
+ 'tsconfig.json': REFERENCES('./tsconfig.module.json'),
+ }
+ dirs.moduleProject = await fixture('.temp-builder/module-project', { config: PLUGIN, module: source => source + FIELDS, files: moduleProject })
+ dirs.tsconfigOption = await fixture('.temp-builder/tsconfig-option', { config: `export default { tsconfig: 'tsconfig.override.json', plugins: [builder()] }\n`, module: source => source + FIELDS, files: moduleProject })
+ dirs.singleTsconfig = await fixture('.temp-builder/single-tsconfig', {
+ config: PLUGIN,
+ module: source => source + FIELDS,
+ files: { 'tsconfig.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] }) },
+ })
+
+ await Promise.all([
+ step('compose', tsdown(dirs.compose)),
+ step('packageImports', tsdown(dirs.packageImports)),
+ ...['source', 'files'].flatMap(name => [
+ step(`unpublishable-${name}:tsdown`, tsdown(dirs[`unpublishable-${name}`]!)),
+ step(`unpublishable-${name}:cli`, cli(['build', dirs[`unpublishable-${name}`]!])),
+ ]),
+ ...Object.keys(variants).map(name => step(name, tsdown(dirs[name]!))),
+ step('contexts', tsdown(dirs.contexts)).then(() => step('contexts:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.contexts }))),
+ step('moduleProject', tsdown(dirs.moduleProject, [], { CI: '' })),
+ step('tsconfigOption', tsdown(dirs.tsconfigOption)),
+ step('singleTsconfig', tsdown(dirs.singleTsconfig)),
+ step('published', run('node', [tsdownBin], { cwd: repoRoot })).then(() => step('published:import', run('node', ['--input-type=module', '-e', `const root = await import('@nuxt/module-builder')\nconst { builder } = await import('@nuxt/module-builder/tsdown')\nconsole.log(JSON.stringify(['builder' in root, builder().name]))`]))),
+ ])
+})
+
+describe('builder', () => {
+ it('should run the config\'s hooks before its own, so `build:prepare` can generate sources, and compose with its plugins and options', async () => {
+ const dir = dirs.compose!
+ expect(expectBuilt('compose')).not.toContain('Error')
+ expect((await read(dir, 'hooks.log')).trim().split('\n')).toEqual(['build:prepare', 'inputOptions', 'build:done true true'])
+ expect(exists(dir, 'dist/stale.txt')).toBe(false)
+ const module = await read(dir, 'dist/module.mjs')
+ expect(module).toContain('from build:prepare')
+ expect(module).toContain('replaced by a user plugin')
+ expect(module).toContain('from "fake-ext"')
+ expect(module).not.toContain('bundled-fake-ext')
+ expect(module).toContain('from "./runtime/utils/answer.js"')
+ expect(JSON.parse(await read(dir, 'dist/module.json'))).toMatchObject({ name: 'my-module', configKey: 'myModule' })
+ })
+
+ it('should write files a plugin emits before checking the paths of `package.json`', async () => {
+ expect(await read(dirs.compose!, 'dist/config.cjs')).toBe('module.exports = {}\n')
+ const warning = expectBuilt('compose').split('\n').find(line => line.includes('do not exist after the build'))
+ expect(warning).toContain('./dist/missing.mjs')
+ expect(warning).not.toContain('config.cjs')
+ })
+
+ it('should refuse package `imports` that the output imports and that would not work once installed', async () => {
+ expect(expectFailed('packageImports')).toContain(`The build output imports these \`imports\` of \`package.json\`, which would not work once installed. Pointing at TypeScript sources, which Node does not load from \`node_modules\`: \`#ext/*\` (\`./src/ext/*.ts\`).`)
+ expect(exists(dirs.packageImports!, 'dist')).toBe(false)
+ const module = await read(dirs.compose!, 'dist/module.mjs')
+ expect(module).toContain('"#ext/value"')
+ expect(module).toContain('through imports')
+ expect(module).not.toContain('#internal/value')
+ })
+
+ it('should refuse to build when a published path points at a TypeScript source or at a file the pack leaves out', () => {
+ const messages = {
+ source: 'Pointing at TypeScript sources, which Node does not load from `node_modules`: `exports` (`./src/module.ts`).',
+ files: 'Pointing at paths that the pack leaves out: `exports` (`./lib/module.mjs`).',
+ }
+ for (const [name, message] of Object.entries(messages)) {
+ for (const command of ['tsdown', 'cli']) {
+ expect(expectFailed(`unpublishable-${name}:${command}`), command).toContain(message)
+ }
+ expect(exists(dirs[`unpublishable-${name}`]!, 'dist')).toBe(false)
+ }
+ })
+
+ it('should be published at `@nuxt/module-builder/tsdown`, not at the package root', () => {
+ expectBuilt('published')
+ expect(JSON.parse(expectBuilt('published:import'))).toEqual([false, 'nuxt-module-builder'])
+ })
+
+ it('should reject one plugin instance shared by two configs', () => {
+ expect(expectFailed('shared')).toContain('The same `builder()` plugin is used in more than one tsdown config.')
+ })
+
+ it.each(['format', 'entry', 'platform'])('should fail when another plugin changes `%s`, which it sets', (option) => {
+ expect(expectFailed(option)).toMatch(new RegExp(`Another tsdown plugin changed \`${option}\`.*, which \`builder\\(\\)\` sets\\. ${guide('options-builder-sets')}`))
+ expect(exists(dirs[option]!, 'dist')).toBe(false)
+ })
+
+ it('should fail when `outputOptions` changes the file names of the bundled entries, and remove the partial output', () => {
+ expect(expectFailed('entryFileNames')).toMatch(/The build did not emit `(module|utils)\.mjs`, `(module|utils)\.mjs`\./)
+ expect(exists(dirs.entryFileNames!, 'dist')).toBe(false)
+ })
+
+ it('should break the size report down by entry and runtime directory only when it is a summary', () => {
+ expect(sizeRows(expectBuilt('compose'))).toEqual(['dist/module.mjs', 'dist/runtime/'])
+ expect(sizeRows(expectBuilt('summary'))).toEqual([])
+ })
+})
+
+describe('with a root tsconfig that only lists references', () => {
+ it('should type runtime components with their own context and pass the type check', async () => {
+ const dir = dirs.contexts!
+ expect(expectBuilt('contexts')).not.toContain('type error')
+ expect(await read(dir, 'dist/runtime/components/ThingState.d.vue.ts')).toMatch(/loggedIn: boolean;\s+user: \{\s+name: string;\s+\} \| null;/)
+ expect(await read(dir, 'dist/runtime/components/Triggered.vue')).toMatch(/type: \[\s*String,\s*Array,\s*Boolean\s*\]/)
+ const generated = async (name: string) => JSON.parse(await read(dir, `.nuxt/tsconfig.${name}.json`))
+ for (const name of ['app', 'node', 'server', 'shared']) {
+ const config = await generated(name)
+ expect(config.files, name).toEqual(expect.arrayContaining([join(dir, 'src/env.d.ts'), join(dir, 'ambient.d.ts'), join(dir, 'types/virtual.d.ts')]))
+ expect(config.files, name).not.toContain(join(dir, 'src/augments.d.ts'))
+ expect(config.compilerOptions.types, name).toContain('vitest/importMeta')
+ }
+ for (const name of ['nuxt', 'nuxt.node']) {
+ expect(await read(dir, `.nuxt/${name}.d.ts`), name).toContain('/// ')
+ }
+ expect(await read(dir, '.nuxt/nuxt.shared.d.ts')).not.toContain('augments.d.ts')
+ expect(await read(dir, '.nuxt/nuxt.node.d.ts')).toContain('/// ')
+ const buildTypes = (await read(dir, '.nuxt/types/build.d.ts')).split('\n')
+ expect(buildTypes).toContain('declare module "#build/my-module-virtual";')
+ expect(buildTypes).not.toContain('declare module "#build/my-module-virtual.mjs";')
+ expect((await generated('app')).include).not.toContain('../**/*')
+ expect(expectBuilt('contexts:typecheck')).toBe('')
+ })
+
+ it('should transform each runtime file with the referenced project that includes it', async () => {
+ expect(await read(dirs.contexts!, 'dist/runtime/fields.js')).toContain('\tvalue;')
+ expect(await read(dirs.contexts!, 'dist/runtime/server/fields.js')).not.toContain('value;')
+ })
+
+ it('should name a dependency in runtime declarations by its package when only another part of the module imports it', async () => {
+ expect(await read(dirs.contexts!, 'dist/runtime/logger.d.ts')).toContain('import("fake-logger").LoggerInstance')
+ })
+
+ it('should give tsdown the project that includes the module entry, unless the config sets `tsconfig`', async () => {
+ const ownsField = async (dir: string) => (await read(dir, 'dist/module.mjs')).includes('\tvalue;')
+ const output = expectBuilt('moduleProject')
+ expect(output).toContain('tsconfig: tsconfig.module.json')
+ expect(output).toMatch(/Set `?isolatedDeclarations: true`? in `?tsconfig\.module\.json`?/)
+ expect(await ownsField(dirs.moduleProject!)).toBe(false)
+ expect(expectBuilt('tsconfigOption')).toContain('tsconfig: tsconfig.override.json')
+ expect(await ownsField(dirs.tsconfigOption!)).toBe(true)
+ expect(expectBuilt('singleTsconfig')).toContain('tsconfig: tsconfig.json')
+ expect(await read(dirs.singleTsconfig!, 'dist/module.d.mts')).toBe(await read(dirs.moduleProject!, 'dist/module.d.mts'))
+ })
+})
diff --git a/test/cli.spec.ts b/test/cli.spec.ts
new file mode 100644
index 00000000..7f279aff
--- /dev/null
+++ b/test/cli.spec.ts
@@ -0,0 +1,1551 @@
+import { mkdir, readFile, rename, rm, symlink, writeFile } from 'node:fs/promises'
+import { pathToFileURL } from 'node:url'
+import { findStaticImports } from 'mlly'
+import { version as nuxtVersion } from 'nuxt/package.json'
+import { join, relative, resolve } from 'pathe'
+import { readPackageJSON } from 'pkg-types'
+import type { PackageJson } from 'pkg-types'
+import { satisfies } from 'verkit'
+import { beforeAll, describe, expect, it } from 'vitest'
+
+import { version } from '../package.json'
+import { guide } from '../src/build/guide.ts'
+import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts'
+import type { Result } from './utils.ts'
+import { bin, builderImport, cli, cliBin, exampleDir, exists, fixture, listFiles, read, repoRoot, run, succeed, tsdownBin, unresolvedSpecifiers } from './utils.ts'
+
+const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '**/tsdown.config.ts'] }
+const ISOLATED = {
+ 'tsconfig.json': JSON.stringify({ ...LEGACY_TSCONFIG, compilerOptions: { isolatedDeclarations: true } }),
+ 'src/utils.ts': 'export const myModuleUtils = (): void => {}\n',
+}
+const REFERENCES = (node: string) => JSON.stringify({
+ files: [],
+ exclude: ['dist', 'node_modules', 'playground'],
+ references: [node, './.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json'].map(path => ({ path })),
+})
+
+const annotate = (source: string) => [
+ `import type { NuxtModule } from '@nuxt/schema'`,
+ source.replace(/export default defineNuxtModule()?\(\{/, (_, options = '') => `const module: NuxtModule${options} = defineNuxtModule${options}({`),
+ 'export default module',
+].join('\n')
+
+const minimalModule = (name: string) => `import { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({\n meta: { name: '${name}', configKey: '${name}' },\n setup() {},\n})\n`
+
+const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}`
+
+const fakeCache = {
+ 'node_modules/fake-cache/package.json': JSON.stringify({ name: 'fake-cache', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ 'node_modules/fake-cache/index.js': `export const defineCached = handler => handler\n`,
+ 'node_modules/fake-cache/index.d.ts': `import type { Handler } from 'fake-h3'\nexport declare const defineCached: (handler: () => string) => Handler\n`,
+ 'node_modules/fake-cache/node_modules/fake-h3/package.json': JSON.stringify({ name: 'fake-h3', type: 'module', exports: { '.': { types: './index.d.ts' } } }),
+ 'node_modules/fake-cache/node_modules/fake-h3/index.d.ts': `export interface Handler { (): string, __h3: 2 }\n`,
+}
+
+const VALUE_EXPORTS = `export function defineMyModuleConfig(): void {}
+export const myModuleVersion = '1.0.0'
+export const Mode = { Light: 0, Dark: 1 } as const
+export type Mode = typeof Mode[keyof typeof Mode]
+`
+
+const consumer = {
+ 'playground/consumer.ts': `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module'
+import type { ModuleOptions } from 'my-module'
+
+defineMyModuleConfig()
+const options: ModuleOptions = { apiKey: myModuleVersion }
+const light: number = Mode.Light
+const dark: Mode = Mode.Dark
+void [light, dark, options]
+`,
+ 'playground/consumer.tsconfig.json': JSON.stringify({
+ compilerOptions: { moduleResolution: 'bundler', module: 'ESNext', target: 'ESNext', lib: ['ESNext'], strict: true, noEmit: true, skipLibCheck: true },
+ include: ['consumer.ts'],
+ }),
+}
+
+const runtimeSpecifiers = (code: string) => findStaticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort()
+
+const dirs: Record = {}
+let sourceWithoutDist = false
+const results: Record = {}
+const result = (name: string) => {
+ const found = results[name]
+ if (!found) {
+ throw new Error(`\`${name}\` did not run, as a step before it failed`)
+ }
+ return found
+}
+const output = (name: string) => result(name).output
+const step = async (name: string, result: Promise) => {
+ const settled = await result
+ results[name] = settled
+ return settled
+}
+const inOrder = async (...steps: Array<[name: string, run: () => Promise]>) => {
+ for (const [name, run] of steps) {
+ if ((await step(name, run())).exitCode !== 0) {
+ return false
+ }
+ }
+ return true
+}
+
+beforeAll(async () => {
+ const examplePkg = JSON.parse(await readFile(join(exampleDir, 'package.json'), 'utf-8'))
+ const base = await fixture('.temp-cli/base', { files: { 'tsconfig.json': JSON.stringify(LEGACY_TSCONFIG) } })
+ await succeed(cli(['prepare', base]))
+ const from = base
+
+ dirs.runtime = await fixture('.temp-cli/runtime with spaces ü', {
+ from,
+ module: source => [
+ `import type { DeepPartial } from 'fake-types'`,
+ `import type FakeCjs from 'fake-cjs-types'`,
+ `import { defineThing } from 'fake-kit'`,
+ source,
+ `import { name } from './runtime/utils/name.ts'`,
+ `import { aliased } from '#runtime/utils/aliased'`,
+ `import { useShape } from './runtime/composables/useShape.ts'`,
+ `import type TestMe from './runtime/components/TestMe.vue'`,
+ `import type JsxComponent from './runtime/components/JsxComponent.tsx'`,
+ `export const runtimeRefs = [name, aliased, useShape]`,
+ `export type TestMeType = typeof TestMe`,
+ `export type JsxComponentType = typeof JsxComponent`,
+ `export type { NuxtApp } from '#app'`,
+ `export interface ExtraOptions { deep?: DeepPartial<{ a: string }>, cjs?: FakeCjs.Options }`,
+ `export const thing = defineThing({ name: 'portable' })`,
+ '',
+ ].join('\n'),
+ pkg: pkg => ({ ...pkg, imports: { '#runtime/*': './src/runtime/*.ts' } }),
+ files: {
+ 'src/runtime/composables/useShape.ts': `import { shape } from '../utils/shape.ts'\n\nexport const useShape = (): string => shape\n`,
+ 'src/runtime/utils/name.ts': `export const name: string = 'name'\n`,
+ 'src/runtime/utils/aliased.ts': `export const aliased: string = 'aliased'\n`,
+ 'src/runtime/utils/shape.ts': `export const shape: string = 'shape'\n`,
+ 'src/runtime/components/JsxCard.vue': `\n\n\n \n \n`,
+ 'src/runtime/components/JsxSlot.tsx': `import { defineComponent } from 'vue'\nimport { useNuxtApp } from '#app'\nimport JsxComponent from './JsxComponent'\n\nexport const useSlotApp = () => useNuxtApp()\n\nexport default defineComponent((_, { slots }) => () => )\n`,
+ 'src/runtime/server/render.tsx': `import { useSlotApp } from '../components/JsxSlot'\nimport { strong } from '../utils/strong'\n\nexport type SlotApp = ReturnType\n\nexport const render = (label: string) => {strong(label)}
\n`,
+ 'src/runtime/server/render.stories.ts': `import JsxSlot from '../components/JsxSlot'\n\nexport const tested = JsxSlot\n`,
+ 'src/runtime/utils/strong.tsx': `import { bold } from './bold'\n\nexport const strong = (label: string) => {bold(label)} \n`,
+ 'src/runtime/utils/bold.tsx': `export const bold = (label: string) => {label} \n`,
+ 'src/runtime/utils/label.tsx': `export const label = label \n`,
+ 'node_modules/fake-cjs-types/package.json': JSON.stringify({ name: 'fake-cjs-types', types: './index.d.ts' }),
+ 'node_modules/fake-cjs-types/index.d.ts': `declare namespace FakeCjs { interface Options { level: number } }\nexport = FakeCjs\n`,
+ 'node_modules/fake-dep/package.json': JSON.stringify({ name: 'fake-dep', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ 'node_modules/fake-dep/index.js': `export const helper = () => 'bundled-fake-dep'\n`,
+ 'node_modules/fake-dep/index.d.ts': `export declare const helper: () => string\n`,
+ 'node_modules/fake-types/package.json': JSON.stringify({ name: 'fake-types', types: './index.d.ts' }),
+ 'node_modules/fake-types/index.d.ts': `export type DeepPartial = { [K in keyof T]?: DeepPartial }\n`,
+ [`${store('fake-schema')}/package.json`]: JSON.stringify({ name: 'fake-schema', types: './index.d.ts' }),
+ [`${store('fake-schema')}/index.d.ts`]: `export interface Thing { options: T }\n`,
+ [`${store('fake-kit')}/package.json`]: JSON.stringify({ name: 'fake-kit', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ [`${store('fake-kit')}/index.d.ts`]: `import type { Thing } from 'fake-schema'\nexport declare function defineThing(options: T): Thing\n`,
+ [`${store('fake-kit')}/index.js`]: `export const defineThing = options => ({ options })\n`,
+ '.nuxt/nuxt.d.ts': source => `/// \n${source}`,
+ 'src/runtime/server/routes/[...slug].ts': `export default (slug: string) => slug\n`,
+ 'src/runtime/utils/self.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const getApiKey = (options: ModuleOptions) => options.apiKey\n`,
+ 'src/runtime/cache/lru.ts': `export const lru: string = 'lru'\n`,
+ 'src/runtime/server/handler.ts': `// @ts-ignore build-time virtual
+import options from '#internal/nuxt.config.mjs'
+// @ts-ignore app alias
+import app from '~/app.config'
+// @ts-ignore app alias
+import root from '@/root'
+import { useNuxtApp } from '#app'
+import { helper } from 'fake-dep'
+import { lru } from '#fixture-cache'
+import { local } from '../utils/local'
+
+export default (): unknown[] => [options, app, root, useNuxtApp, helper(), lru, local]
+`,
+ 'src/runtime/utils/local.ts': `export const local: string = 'local'\n`,
+ 'src/runtime/utils/options.ts': `import type { DeepPartial } from 'fake-types'\nimport { helper } from 'fake-dep'\n\nexport type Options = DeepPartial<{ a: { b: string } }>\nexport const defineOptions = (options: Options) => ({ options, helper })\n`,
+ 'src/runtime/utils/typo.ts': `export const count: number = 'one'\nexport const double = (value: number): number => value * 2\n`,
+ 'src/runtime/components/Typo.vue': `\n\n\n {{ props.label }} {{ count }} \n \n`,
+ 'src/runtime/components/Sized.vue': `\n\n\n\n\n \n \n`,
+ 'src/runtime/composables/useSize.ts': `import { computed } from 'vue'\nimport type { Props } from '../components/Sized.vue'\n\nexport function useSize(props: Props) {\n return computed(() => props.size)\n}\n`,
+ },
+ paths: { '#fixture-cache': ['../src/runtime/cache/lru'], 'fake-schema': [`../${store('fake-schema')}`] },
+ links: {
+ 'node_modules/.pnpm/fake-kit@1.0.0/node_modules/fake-schema': store('fake-schema'),
+ 'node_modules/fake-schema': store('fake-schema'),
+ 'node_modules/fake-kit': store('fake-kit'),
+ },
+ })
+
+ dirs.runtimeLink = join(repoRoot, '.temp-cli/runtime-link')
+ await rm(dirs.runtimeLink, { force: true })
+ await symlink(dirs.runtime, dirs.runtimeLink)
+
+ dirs.isolated = await fixture('.temp-cli/isolated', {
+ from,
+ module: source => annotate(`${source}\n${VALUE_EXPORTS}`),
+ remove: ['.nuxt'],
+ files: {
+ ...ISOLATED,
+ ...consumer,
+ 'src/runtime/styles/card.css': `@import "./base.css";\n\n.card {\n user-select: none;\n & .title { font-weight: bold; }\n &:hover { color: rebeccapurple; }\n}\n`,
+ 'src/runtime/styles/base.css': `.base { margin: 0px 0px; }\n`,
+ 'src/runtime/styles/_variables.scss': `$primary: #00dc82;\n`,
+ 'src/runtime/styles/theme.scss': `@use "variables" as v;\n.theme { color: v.$primary; .nested { padding: 1px; } }\n`,
+ 'src/runtime/styles/indented.sass': `.indented\n color: blue\n`,
+ 'src/runtime/styles/legacy.less': `@c: red;\n.less { color: @c; }\n`,
+ 'src/runtime/types/ambient.d.ts': `declare global { interface Window { __fixture: true } }\nexport {}\n`,
+ 'src/runtime/types/app.d.ts': `import type { NuxtApp } from '#app'\nexport type App = NuxtApp\n`,
+ 'src/runtime/plugins/styled.ts': `import '../styles/card.css'\nimport '../styles/theme.scss'\n\nexport const styled = true\n`,
+ },
+ })
+
+ dirs.types = await fixture('.temp-cli/types', {
+ from,
+ module: source => `${source.replace('export interface ModuleOptions', 'interface ModuleOptions')}\n${VALUE_EXPORTS}`,
+ files: consumer,
+ })
+
+ dirs.minimal = await fixture('.temp-cli/minimal', {
+ from,
+ config: `export default {\n plugins: [builder({ entries: ['./src/utils', { input: 'src/components/', outDir: 'dist/components' }] })],\n}\n`,
+ module: annotate(minimalModule('minimal')),
+ remove: ['src/runtime'],
+ files: {
+ ...ISOLATED,
+ ...Object.fromEntries(await Promise.all(['TestMe.vue', 'TestMe.css', 'TestMeSetup.vue'].map(async file => [`src/components/${file}`, await read(exampleDir, 'src/runtime/components', file)]))),
+ },
+ })
+
+ dirs.shape = await fixture('.temp-cli/shape', {
+ from,
+ config: `export default {\n plugins: [builder({ entries: ['./src/utils', './src/utils/merge.ts', './src/data.json'] })],\n}\n`,
+ files: {
+ '.nuxt/app.config.ts': `export default { theme: { buildMachineOnly: 'must-not-be-published' as const } }\n`,
+ 'external.ts': `export const answer = 42\n`,
+ ...Object.fromEntries(['fake-polyfill', 'fake-register'].flatMap(name => [
+ [`node_modules/${name}/package.json`, JSON.stringify({ name, type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } })],
+ [`node_modules/${name}/index.js`, `globalThis.__order = [...globalThis.__order ?? [], '${name}']\n`],
+ [`node_modules/${name}/index.d.ts`, `export {}\n`],
+ ])),
+ 'src/data.json': `{ "answer": 42 }\n`,
+ 'src/utils/merge.ts': `export const merge = (a: T, b: T): T => ({ ...a, ...b })\n`,
+ 'src/shared/constants.ts': `import { LIMIT } from './limits'\n\nexport const CONSTANT = LIMIT\n`,
+ 'src/shared/limits.ts': `export const LIMIT = 10\n`,
+ 'src/types.ts': `export interface RootType { root: string }\n`,
+ 'src/types/middlewares.ts': `export type RequestSizeLimiter = { maxRequestSizeInBytes: number }\n`,
+ 'src/runtime/server/limiter.ts': `import { type RequestSizeLimiter } from '../../types/middlewares'\nimport {} from 'nuxt/app'\nimport '../disabled/side'\n\nexport const limit = (options: RequestSizeLimiter) => options.maxRequestSizeInBytes\n`,
+ 'src/routing.ts': `import { readFileSync } from 'node:fs'\nimport { generate } from './kit/gen'\nimport type { RootType } from './types'\n\nexport interface RouteInfo { path: string, root: RootType }\nexport const localizeRoutes = (file: string): string => generate(readFileSync(file, 'utf8'))\n`,
+ 'src/kit/gen.ts': `import { createHash } from 'node:crypto'\n\nexport const generate = (input: string) => createHash('sha1').update(input).digest('hex')\n`,
+ 'src/runtime/composables/useLocaleRoute.ts': `import { RouteInfo } from '../../routing'\n\nexport const useLocaleRoute = (route: RouteInfo) => route\n`,
+ 'src/runtime/types.ts': `export interface RuntimeType { runtime: string }\n`,
+ 'src/runtime/server/uses.ts': [
+ `import { merge } from '../../utils/merge'`,
+ `import { CONSTANT } from '../../shared/constants'`,
+ `import type { RootType } from '../../types'`,
+ `import type { RuntimeType } from '../types'`,
+ ``,
+ `export const combine = (a: RootType & RuntimeType, b: RootType & RuntimeType) => [merge(a, b), CONSTANT] as const`,
+ ``,
+ ].join('\n'),
+ 'src/runtime/escaping.ts': `export const load = () => import('../../external')\n`,
+ 'src/runtime/composables/mock.ts': `export const defineThing = () => 'mock'\n`,
+ 'src/runtime/disabled/composables/defineThing.ts': `export { defineThing } from '../../composables/mock'\n`,
+ 'src/runtime/disabled/index.ts': `import './side'\nexport { defineThing } from './composables/defineThing'\n`,
+ 'src/runtime/disabled/side.ts': `globalThis.__side = true\n`,
+ 'src/runtime/order/interleaved.ts': [
+ `import 'fake-register'`,
+ `import { level } from './levels'`,
+ `export * from './reexported'`,
+ `import './order.css'`,
+ `export { useState } from '#imports'`,
+ `import 'fake-polyfill'`,
+ `import './effect'`,
+ `import { ref } from 'vue'`,
+ ``,
+ `export const value = ref(level)`,
+ ``,
+ ].join('\n'),
+ 'src/runtime/order/levels.ts': `export const level = 1\n`,
+ 'src/runtime/order/reexported.ts': `export const reexported = 1\n`,
+ 'src/runtime/order/effect.ts': `globalThis.__effect = true\n`,
+ 'src/runtime/order/order.css': `.order { color: red }\n`,
+ 'src/runtime/content/index.ts': `export * from '../components/TestMe.vue'\nexport * from '../components/TestMeSetup.vue'\nexport * from './prose'\n`,
+ 'src/runtime/content/prose.ts': `export * from './levels'\nexport interface ProseThing { title: string }\n`,
+ 'src/runtime/content/levels.ts': `export const proseLevel = 1\n`,
+ 'src/runtime/utils/provider.ts': `import type { ModuleOptions } from '../../module'\n\nexport const defineProvider = (options: ModuleOptions) => options\n`,
+ 'src/runtime/utils/props.ts': `export interface BaseProps { size?: number }\n`,
+ 'src/runtime/composables/useThemeConfig.ts': `import appConfig from '#build/app.config'\n\nexport const useThemeConfig = () => appConfig.theme\n`,
+ 'src/runtime/composables/useButton.ts': `import theme, { variants } from '#build/ui/button'\nimport * as config from '#build/app.config'\n\nexport const useButton = () => ({ slots: theme.slots, size: variants.size, ui: config.default.ui })\n`,
+ 'src/runtime/components/Button.vue': `\n\n\n \n \n`,
+ 'src/runtime/components/Sized.vue': `\n\n\n {{ theme }}
\n \n`,
+ },
+ })
+
+ dirs.loader = await fixture('.temp-cli/loader', {
+ from,
+ module: `import { deps } from './deps.ts'\nimport { deep } from './deep/a.ts'\n${minimalModule('my-module')}\nexport const loaded = [deps, deep]\nexport { nativeValue } from './native-helper.ts'\nexport { internal } from '#internal/value'\n`,
+ remove: ['.nuxt'],
+ pkg: pkg => ({ ...pkg, imports: { '#internal/*': './src/internal/*.ts' } }),
+ files: {
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { paths: { '*': ['./src/*'] } } }),
+ 'src/@nuxt/kit.ts': 'export const defineNuxtModule = (_: unknown) => ({ SHADOWED: true })\n',
+ 'src/native-helper.ts': `import { inner } from './nested/inner.ts'\n\nexport const nativeValue: string = inner\n`,
+ 'src/nested/inner.ts': `export const inner: string = 'loaded helper'\n`,
+ 'src/internal/value.ts': `export const internal: string = 'through imports'\n`,
+ 'node_modules/fake-cjs-marker/package.json': JSON.stringify({ name: 'fake-cjs-marker', version: '1.0.0', main: 'index.js' }),
+ 'node_modules/fake-cjs-marker/index.js': `const marker = 'mentions import.meta in a string'\nmodule.exports = { value: marker.length }\n`,
+ 'node_modules/fake-esm-split/package.json': JSON.stringify({ name: 'fake-esm-split', version: '1.0.0', type: 'module', exports: { '.': { import: './index.js', require: './index.cjs' } } }),
+ 'node_modules/fake-esm-split/index.js': `export { value } from './inner.js'\nexport { other } from './other.js'\n`,
+ 'node_modules/fake-esm-split/inner.js': `import cjs from 'fake-cjs-marker'\nexport const value = cjs.value\n`,
+ 'node_modules/fake-esm-split/other.js': `import cjs from 'fake-cjs-marker'\nexport const other = cjs.value + 1\n`,
+ 'node_modules/fake-esm-split/index.cjs': `module.exports = { value: 0, other: 1 }\n`,
+ 'src/deps.ts': `// @ts-ignore untyped\nimport cjs from 'fake-cjs-marker'\n// @ts-ignore untyped\nimport { value, other } from 'fake-esm-split'\n\nexport const deps: unknown[] = [cjs, value, other]\n`,
+ 'src/deep/a.ts': `export { deep } from './b.ts'\n`,
+ 'src/deep/b.ts': `import pkg from '../../package.json' with { type: 'json' }\n\nexport const deep: string = pkg.name\n`,
+ 'probe.ts': `import type Module from './.nuxt/module-builder/types.mjs'\n\nexport const meta: Promise<{ configKey?: string }> = ({} as typeof Module).getMeta!()\n`,
+ },
+ })
+
+ dirs.unloadable = await fixture('.temp-cli/unloadable', {
+ from,
+ module: source => `import { name as packageName } from '../package.json'
+import { Level } from './levels.ts'
+
+enum Mode { Stub = 'stub' }
+class Holder { constructor(public value: string) {} }
+${source.replace(`name: 'my-module'`, 'name: new Holder(`${packageName}-${Mode.Stub}-${Level.High}`).value')}
+export { myModuleUtils } from './utils.js'
+export { helper } from './helpers'
+export { kit } from './kit'
+export type { Kit } from './kit'
+`,
+ files: {
+ 'src/levels.ts': `export enum Level { High = 'high' }\n`,
+ 'src/helpers.ts': `export const helper = (): string => 'helper'\n`,
+ 'src/kit/index.ts': `export const kit = (): string => 'kit'\nexport type Kit = ReturnType\n`,
+ },
+ })
+
+ dirs.unloadableDist = await fixture('.temp-cli/unloadable-dist', {
+ from,
+ module: source => `${source}\nif (new URL(import.meta.url).pathname.endsWith('.mjs')) {\n throw new Error('fails once built')\n}\n`,
+ })
+
+ dirs.isolatedError = await fixture('.temp-cli/isolated-error', { from, files: { 'tsconfig.json': ISOLATED['tsconfig.json'] } })
+
+ dirs.typeError = await fixture('.temp-cli/type-error', {
+ from,
+ remove: ['src/runtime/components'],
+ files: {
+ ...fakeCache,
+ 'src/runtime/utils.ts': `export const Anonymous = class { private secret = 1 }\n`,
+ 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`,
+ },
+ })
+
+ dirs.vueError = await fixture('.temp-cli/vue-error', {
+ from,
+ module: minimalModule('vue-error'),
+ remove: ['src/runtime'],
+ files: {
+ ...fakeCache,
+ 'src/runtime/components/Cached.vue': `\n\n\n cached \n \n`,
+ 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`,
+ },
+ })
+
+ dirs.solution = await fixture('.temp-cli/solution', {
+ from,
+ files: {
+ 'tsconfig.json': JSON.stringify({ files: [], references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.server.json' }] }),
+ 'tsconfig.app.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', include: ['.nuxt/nuxt.d.ts', 'src/**/*'], exclude: ['src/runtime/server/**'] }),
+ 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { paths: { '#server-only': ['./src/runtime/server/only.ts'] } }, include: ['src/runtime/server/**/*'] }),
+ 'src/runtime/server/only.ts': `export interface ServerOnly { id: string }\n`,
+ 'src/runtime/server/api/[id].get.ts': `import type { ServerOnly } from '#server-only'\n\nexport default (value: ServerOnly) => value.id\n`,
+ },
+ })
+
+ const loggerStore = store('fake-logger')
+ const parent = await fixture('.temp-cli/parent', {
+ from,
+ files: {
+ [`${loggerStore}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.mts', default: './dist/index.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } } }),
+ [`${loggerStore}/dist/utils.d.mts`]: `export declare const noop: () => void\n`,
+ [`${loggerStore}/dist/utils.mjs`]: `export const noop = () => {}\n`,
+ [`${loggerStore}/dist/core.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\n`,
+ [`${loggerStore}/dist/core.d.mts`]: `export interface LoggerInstance { log: (message: string) => void }\n`,
+ [`${loggerStore}/dist/index.d.ts`]: `import type { LoggerInstance } from './core'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`,
+ [`${loggerStore}/dist/index.d.mts`]: `import type { LoggerInstance } from './core.mjs'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`,
+ [`${loggerStore}/dist/index.mjs`]: `export const createLogger = () => ({ log: console.log })\n`,
+ 'src/runtime/logger.ts': `import { createLogger } from 'fake-logger'\nimport { noop } from 'fake-logger/utils'\n\nexport const logger = createLogger()\nexport const silence = noop\n`,
+ },
+ paths: { 'fake-logger': [`../${loggerStore}`] },
+ })
+ dirs.parent = join(parent, 'packages/mod')
+ await mkdir(join(dirs.parent, 'node_modules'), { recursive: true })
+ for (const file of ['src', 'package.json', 'tsdown.config.ts']) {
+ await rename(join(parent, file), join(dirs.parent, file))
+ }
+ await symlink(join(parent, loggerStore), join(dirs.parent, 'node_modules/fake-logger'))
+
+ const { build: _, ...sourcePkg } = examplePkg
+ dirs.routes = await fixture('.temp-cli/routes/mod', {
+ from,
+ module: source => source
+ .replace('import { defineNuxtModule, addPlugin, createResolver }', 'import { defineNuxtModule, addPlugin, addServerHandler, createResolver }')
+ .replace(`addPlugin(resolver.resolve('./runtime/plugins/plugin'))`, `addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addServerHandler({ route: '/api/own', handler: resolver.resolve('./runtime/server/api/own') })`),
+ remove: ['tsconfig.json'],
+ pkg: () => sourcePkg,
+ files: {
+ '.nuxtrc': source => `${source.trimEnd()}\nworkspaceDir=..\n`,
+ '../tsconfig.json': JSON.stringify({ extends: './mod/playground/.nuxt/tsconfig.json', compilerOptions: { types: ['fake-global-types'] }, exclude: ['**/dist', '**/node_modules', '**/tsdown.config.ts'] }),
+ 'node_modules/fake-global-types/package.json': JSON.stringify({ name: 'fake-global-types', types: 'index.d.ts' }),
+ 'node_modules/fake-global-types/index.d.ts': `declare namespace Fake {\n interface Thing { id: number }\n function current(): Thing\n}\n`,
+ 'src/runtime/composables/useGlobal.ts': `export const useGlobal = () => Fake.current()\n`,
+ 'src/runtime/server/api/own.ts': `export default () => ({ own: 'module-owned' as const })\n`,
+ 'src/runtime/composables/useOwn.ts': `import { useFetch } from '#app'\n\nexport const useOwn = () => useFetch('/api/own')\n`,
+ 'src/runtime/composables/useSecret.ts': `import { useFetch } from '#app'\n\nexport const useSecret = () => useFetch('/api/secret')\n`,
+ 'src/runtime/composables/useSibling.ts': `import { useFetch } from '#app'\n\nexport const useSibling = () => useFetch('/api/sibling')\n`,
+ 'src/runtime/composables/useDocs.ts': `import { useFetch } from '#app'\n\nexport const useDocs = () => useFetch('/api/docs')\n`,
+ 'src/runtime/components/Routes.vue': `\n\n\n
\n \n`,
+ 'playground/server/api/secret.ts': `export default () => ({ localRoute: 'must-not-be-published' as const })\n`,
+ 'playground/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/secret': { default: 'must-not-be-published' }\n }\n}\n`,
+ 'docs/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/docs': { default: 'must-not-be-published' }\n }\n}\n`,
+ '../sibling/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/sibling': { default: 'must-not-be-published' }\n }\n}\n`,
+ },
+ })
+
+ const shapeOptions = (outDir: string) => `{ entries: [{ input: './src/utils', name: 'helpers' }, { input: 'src/shared/', outDir: '${outDir}/shared' }] }`
+ const shapes = {
+ object: `export default {\n outDir: 'out',\n sourcemap: true,\n plugins: [builder(${shapeOptions('out')})],\n}\n`,
+ array: `export default [\n { entry: { cli: 'src/cli.ts' }, outDir: 'dist-cli', dts: false },\n { plugins: [builder(${shapeOptions('out')})], outDir: 'out' },\n]\n`,
+ function: `export default (_, { watch: { restart } }) => ({\n plugins: [Promise.resolve(builder(${shapeOptions('dist')}))],\n})\n`,
+ }
+ for (const [shape, config] of Object.entries(shapes)) {
+ dirs[shape] = await fixture(`.temp-cli/${shape}-export`, {
+ config,
+ remove: ['.nuxt'],
+ module: source => `${source}export { other } from './shared/value.ts'\n`,
+ files: {
+ 'src/shared/value.ts': `export { other } from './other.ts'\n`,
+ 'src/shared/other.ts': `export const other: string = 'other'\n`,
+ 'src/cli.ts': `export const cli: string = 'cli'\n`,
+ },
+ })
+ }
+ dirs.flags = await fixture('.temp-cli/flags', { config: `export default {\n sourcemap: true,\n plugins: [builder()],\n}\n`, pkg: ({ typesVersions: _, ...pkg }) => pkg })
+
+ const failing = {
+ builderHooks: `export default {\n plugins: [builder({ hooks: { 'build:before': () => {} } })],\n}\n`,
+ configCwd: `export default {\n cwd: './elsewhere',\n plugins: [builder()],\n}\n`,
+ configEnum: `enum Mode { Build }\nexport default {\n define: { __MODE__: String(Mode.Build) },\n plugins: [builder()],\n}\n`,
+ withoutPlugin: `export default {}\n`,
+ entriesOnly: `export default [{ entry: { utils: 'src/utils.ts' }, dts: false }]\n`,
+ withoutTsdown: `export default {\n plugins: [builder({ entries: [{ input: './src/utils', name: 'helpers' }] })],\n}\n`,
+ }
+ for (const [name, config] of Object.entries(failing)) {
+ dirs[name] = await fixture(`.temp-cli/${name}`, { config })
+ }
+ await writeFile(join(dirs.withoutTsdown, 'no-tsdown.mjs'), `import { registerHooks } from 'node:module'\n\nregisterHooks({\n resolve(specifier, context, nextResolve) {\n if (/^(?:tsdown|rolldown)(?:\\/|$)/.test(specifier)) {\n throw Object.assign(new Error(\`Cannot find package '\${specifier}'\`), { code: 'ERR_MODULE_NOT_FOUND' })\n }\n return nextResolve(specifier, context)\n },\n})\n`)
+
+ dirs.starExports = await fixture('.temp-cli/star-exports', {
+ config: `export default {\n plugins: [builder()],\n}\n`,
+ module: `import { defineNuxtModule } from '@nuxt/kit'\nimport type { ModuleOptions } from './types/index.ts'\n\nexport * from './types/index.ts'\nexport type * from './types/runtime.ts'\n\nexport default defineNuxtModule({\n meta: { name: 'my-module', configKey: 'myModule' },\n defaults: { apiKey: '' },\n})\n`,
+ files: {
+ 'src/types/index.ts': `export * from './hooks.ts'\n\nexport interface ModuleOptions {\n apiKey: string\n}\n`,
+ 'src/types/hooks.ts': `export interface ModuleHooks {\n 'my-module:init': () => void\n}\n`,
+ 'src/types/runtime.ts': `export interface ModuleRuntimeHooks {\n 'my-module:runtime-hook': () => void\n}\n\nexport interface ModulePublicRuntimeConfig {\n NAME: string\n}\n`,
+ ...Object.fromEntries(['.nuxt/module-builder/types.mjs', 'dist/types.mjs'].flatMap((types, index) => [
+ [`probe-${index}.ts`, `import type {} from './${types}'\nimport type { RuntimeNuxtHooks } from '#app'\nimport type { NuxtHooks, PublicRuntimeConfig } from '@nuxt/schema'\n\nexport type Augmented = [NuxtHooks['my-module:init'], RuntimeNuxtHooks['my-module:runtime-hook'], PublicRuntimeConfig['NAME']]\n`],
+ [`probe-${index}.tsconfig.json`, JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { noEmit: true, skipLibCheck: types.startsWith('.nuxt') }, include: [], files: [`probe-${index}.ts`] })],
+ ])),
+ },
+ })
+
+ const selfListed = (pkg: PackageJson) => ({ ...pkg, name: 'self-listed-module' })
+ const selfListedFiles = {
+ '.nuxtrc': (source: string) => `${source}\nmodules[]=self-listed-module\n`,
+ 'nuxt.config.ts': `export default { modules: [['self-listed-module', { apiKey: 'from-config' }]] }\n`,
+ }
+ const logOptions = (source: string) => source.replace('setup(_options, _nuxt) {', 'setup(_options, _nuxt) {\n console.log(`[setup] ${_options.apiKey}`)')
+ dirs.selfListedDist = await fixture('.temp-cli/self-listed-dist', { remove: ['.nuxt'], pkg: selfListed, module: logOptions, files: selfListedFiles })
+ dirs.selfListedSource = await fixture('.temp-cli/self-listed-source', { remove: ['.nuxt'], pkg: pkg => ({ ...selfListed(pkg), exports: { '.': './src/module.ts' }, main: './src/module.ts' }), module: logOptions, files: selfListedFiles })
+
+ const addTypeTemplate = (source: string, extra = '') => source
+ .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'')
+ .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ` addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addTypeTemplate({ filename: 'types/my-module.d.ts', getContents: () => 'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n' })\n const configured: unknown = _nuxt.options.myModule\n void configured${extra}`)
+
+ dirs.ownPackage = await fixture('.temp-cli/own-package', {
+ config: 'export default { plugins: [builder()] }\n',
+ remove: ['.nuxt'],
+ pkg: pkg => ({ ...pkg, exports: examplePkg.exports, main: examplePkg.main, types: examplePkg.types, publishConfig: examplePkg.publishConfig, imports: { '#my-helpers': './src/helpers.ts' } }),
+ module: source => addTypeTemplate(source).replace(`createResolver } from '@nuxt/kit'`, `createResolver } from '@nuxt/kit'\n\nexport type { Helper } from '#my-helpers'\nexport type { Extra } from './extra'`),
+ files: {
+ 'tsconfig.json': source => JSON.stringify({ extends: './tsconfig.options.json', ...JSON.parse(source), exclude: undefined }),
+ 'tsconfig.options.json': JSON.stringify({ compilerOptions: { types: ['vitest/importMeta'] }, exclude: ['dist', 'node_modules', 'playground'] }),
+ 'src/helpers.ts': `export interface Helper {\n name: string\n}\n`,
+ 'src/extra.d.ts': `export interface Extra {\n id: string\n}\n`,
+ 'shared/options.ts': `import type { Extra, ModuleOptions } from 'my-module'\n\nexport const sharedApiKey = (options: ModuleOptions, extra: Extra): string => options.apiKey + extra.id\n// @ts-expect-error a string is not a number\nexport const extraId = (extra: Extra): number => extra.id\n`,
+ 'src/runtime/composables/useUtils.ts': `import { myModuleUtils } from 'my-module/utils'\n\nexport const useUtils = (): () => void => myModuleUtils\n`,
+ 'src/runtime/server/options.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const apiKey = (options: ModuleOptions): string => options.apiKey\n`,
+ },
+ })
+
+ dirs.ownPackageIsolated = await fixture('.temp-cli/own-package-isolated', {
+ config: 'export default { plugins: [builder()] }\n',
+ remove: ['.nuxt'],
+ pkg: pkg => ({ ...pkg, imports: { '#payload': './src/nested/payload.ts' } }),
+ module: [
+ `import { defineNuxtModule } from '@nuxt/kit'`,
+ `import type { NuxtModule } from '@nuxt/schema'`,
+ `import type { Payload } from '#payload'`,
+ `import type { Shape } from './nested/shape.ts'`,
+ ``,
+ `export interface ModuleOptions {\n payload?: Payload\n shape?: Shape\n}`,
+ ``,
+ `const module: NuxtModule = defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' } })`,
+ ``,
+ `export default module`,
+ ``,
+ ].join('\n'),
+ files: {
+ 'src/nested/payload.ts': `export interface Payload {\n value: string\n}\n`,
+ 'src/nested/shape.ts': `export interface Shape {\n sides: number\n}\n`,
+ 'src/utils.ts': `export const myModuleUtils = (): void => {}\n`,
+ 'src/runtime/composables/usePayload.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const usePayload = (options: ModuleOptions): string | undefined => options.payload?.value\n`,
+ 'tsconfig.module.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { isolatedDeclarations: true, declaration: true, allowJs: false } }),
+ 'tsconfig.json': REFERENCES('./tsconfig.module.json'),
+ },
+ })
+
+ dirs.ownPackageError = await fixture('.temp-cli/own-package-error', {
+ config: 'export default { plugins: [builder()] }\n',
+ files: {
+ [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`,
+ [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }),
+ [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`,
+ 'src/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`,
+ 'tsconfig.json': REFERENCES('./.nuxt/tsconfig.node.json'),
+ },
+ links: {
+ 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger': store('fake-logger'),
+ 'node_modules/fake-shared': store('fake-shared'),
+ },
+ })
+
+ dirs.legacyPrepare = await fixture('.temp-cli/legacy-prepare', {
+ config: 'export default { plugins: [builder()] }\n',
+ remove: ['.nuxt'],
+ module: source => addTypeTemplate(source, `\n void _nuxt.callHook('my-module:init', 'shared-type')`),
+ files: {
+ 'src/runtime/server/options.ts': `export const apiKey = (options: { apiKey: string }): string => options.apiKey\n`,
+ 'tsconfig.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', 'tsdown.config.ts', 'nuxt.config.ts'] }),
+ 'nuxt.config.ts': `export default { buildDir: '.nuxt-custom' }\n`,
+ },
+ })
+
+ dirs.source = await fixture('.temp-cli/source', {
+ config: `export default {\n publint: true,\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n`,
+ remove: ['.nuxt', 'playground/.nuxt', 'playground/.output'],
+ pkg: ({ typesVersions: _, ...pkg }) => ({
+ ...pkg,
+ exports: { '.': { types: './.nuxt/module-builder/types.d.mts', default: './src/module.ts' }, './utils': './src/utils.ts' },
+ main: './src/module.ts',
+ types: './.nuxt/module-builder/types.d.mts',
+ scripts: { prepack: `node ${JSON.stringify(cliBin)} build` },
+ publishConfig: {
+ exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } },
+ main: './dist/module.mjs',
+ types: './dist/types.d.mts',
+ typesVersions: { '*': { utils: ['./dist/utils.d.mts'] } },
+ },
+ }),
+ module: source => source.replace(`import type { SharedTypeFromRuntime } from './runtime/plugins/plugin'`, `type SharedTypeFromRuntime = 'shared-type'`),
+ })
+
+ dirs.dist = await fixture('.temp-cli/dist', {
+ remove: ['.nuxt', 'playground/.nuxt'],
+ pkg: pkg => ({ ...pkg, scripts: { prepack: `node ${JSON.stringify(tsdownBin)}` } }),
+ })
+
+ const nuxt = (args: string[], cwd = repoRoot) => run('node', [join(repoRoot, 'node_modules/nuxt/bin/nuxt.mjs'), ...args], { cwd })
+ const typecheck = (dir: string, context: string) => run(bin('vue-tsc'), ['--noEmit', '-p', join(dir, `playground/.nuxt/tsconfig.${context}.json`)], { cwd: dir })
+ const consumerCheck = (dir: string) => run(bin('tsc'), ['--noEmit', '-p', join(dir, 'playground/consumer.tsconfig.json')])
+ const listed = (dir: string, project: string) => run(bin('vue-tsc'), ['-p', project, '--noEmit', '--listFilesOnly'], { cwd: dir })
+ const pack = (dir: string, command: string) => mkdir(join(dir, '.pack')).then(() => run(command, ['pack', '--pack-destination', join(dir, '.pack')], { cwd: dir }))
+
+ await Promise.all([
+ step('runtime', cli(['build', dirs.runtimeLink])),
+ step('isolated', cli(['build', dirs.isolated])).then(() => step('isolated:consumer', consumerCheck(dirs.isolated))),
+ step('types', cli(['build', dirs.types])).then(() => step('types:consumer', consumerCheck(dirs.types))),
+ step('minimal', cli(['build', dirs.minimal])),
+ step('minimal:outDir', cli(['build', '--outDir', '..', dirs.minimal])),
+ step('minimal:stub', cli(['build', '--stub', dirs.minimal])),
+ step('minimal:prepare-stub', cli(['prepare', '--stub', dirs.minimal])),
+ step('shape', cli(['build', dirs.shape])),
+ step('loader:prepare', cli(['prepare', dirs.loader])).then(() => Promise.all([
+ step('loader', cli(['build', dirs.loader])),
+ step('loader:probe', run(bin('tsc'), ['--ignoreConfig', '--noEmit', '--strict', '--skipLibCheck', '--allowImportingTsExtensions', '--module', 'nodenext', '--moduleResolution', 'nodenext', join(dirs.loader, 'probe.ts')])),
+ ])),
+ step('unloadable', cli(['build', dirs.unloadable])),
+ step('unloadable:prepare', cli(['prepare', dirs.unloadable])),
+ step('unloadableDist', cli(['build', dirs.unloadableDist])),
+ step('isolatedError', cli(['build', dirs.isolatedError])),
+ step('typeError', cli(['build', dirs.typeError])),
+ step('vueError', cli(['build', dirs.vueError])),
+ step('solution', cli(['build', dirs.solution])),
+ step('parent', cli(['build', dirs.parent])),
+ inOrder(['routes:prepare', () => cli(['prepare', dirs.routes!])], ['routes:playground', () => nuxt(['prepare', join(dirs.routes!, 'playground')])], ['routes', () => cli(['build', dirs.routes!])]),
+ ...['object', 'array', 'function'].map(shape => step(`${shape}:prepare`, cli(['prepare', dirs[shape]!])).then(() => step(shape, cli(['build', dirs[shape]!])))),
+ step('flags', cli(['build', '--outDir', 'custom', '--no-sourcemap', dirs.flags])),
+ step('builderHooks', cli(['build', dirs.builderHooks!])),
+ step('builderHooks:prepare', cli(['prepare', dirs.builderHooks!])),
+ step('configCwd', cli(['prepare', dirs.configCwd!]))
+ .then(() => writeFile(join(dirs.configCwd!, 'tsdown.config.ts'), `${builderImport}\nexport default {\n cwd: '.',\n plugins: [builder()],\n}\n`))
+ .then(() => step('configCwd:fixed', cli(['prepare', dirs.configCwd!]))),
+ step('configEnum', cli(['build', dirs.configEnum!])),
+ step('configEnum:prepare', cli(['prepare', dirs.configEnum!])),
+ step('withoutPlugin', cli(['build', dirs.withoutPlugin!])),
+ step('withoutPlugin:prepare', cli(['prepare', dirs.withoutPlugin!])),
+ step('entriesOnly', cli(['build', dirs.entriesOnly!])),
+ step('withoutTsdown:root', run('node', ['--import', pathToFileURL(join(dirs.withoutTsdown!, 'no-tsdown.mjs')).href, '--input-type=module', '-e', `await import('tsdown').then(() => console.log('tsdown found'), () => {})\nconst root = await import(${JSON.stringify(pathToFileURL(join(repoRoot, 'src/index.ts')).href)})\nconsole.log(Object.keys(root).sort().join(','))`], { cwd: dirs.withoutTsdown })),
+ step('withoutTsdown', run('node', ['--import', pathToFileURL(join(dirs.withoutTsdown!, 'no-tsdown.mjs')).href, cliBin, 'build', dirs.withoutTsdown!], { cwd: dirs.withoutTsdown })),
+ step('starExports:prepare', cli(['prepare', dirs.starExports])).then(() => step('starExports', cli(['build', dirs.starExports]))).then(() => Promise.all([0, 1].map(index =>
+ step(`starExports:probe-${index}`, run(bin('tsc'), ['-p', `probe-${index}.tsconfig.json`], { cwd: dirs.starExports })),
+ ))),
+ step('selfListedDist', cli(['build', dirs.selfListedDist])),
+ step('selfListedSource', cli(['prepare', dirs.selfListedSource])),
+ step('ownPackage', cli(['prepare', dirs.ownPackage])).then(() => Promise.all([
+ step('ownPackage:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.ownPackage })),
+ ...['app', 'server', 'shared'].map(name => step(`ownPackage:${name}`, listed(dirs.ownPackage!, `.nuxt/tsconfig.${name}.json`))),
+ ])),
+ step('ownPackageIsolated', cli(['prepare', dirs.ownPackageIsolated])).then(() => Promise.all([
+ step('ownPackageIsolated:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.ownPackageIsolated })),
+ step('ownPackageIsolated:app', listed(dirs.ownPackageIsolated!, '.nuxt/tsconfig.app.json')),
+ ])),
+ step('ownPackageError', cli(['prepare', dirs.ownPackageError])),
+ step('legacyPrepare', cli(['prepare', dirs.legacyPrepare])).then(() => Promise.all([
+ step('legacyPrepare:typecheck', run(bin('vue-tsc'), ['--noEmit'], { cwd: dirs.legacyPrepare })),
+ step('legacyPrepare:files', run(bin('vue-tsc'), ['--noEmit', '--listFilesOnly'], { cwd: dirs.legacyPrepare })),
+ ])),
+ (async () => {
+ if (!await inOrder(['source:prepare', () => cli(['prepare', dirs.source!])], ['source:playground', () => nuxt(['prepare', 'playground'], dirs.source)])) {
+ return
+ }
+ await Promise.all([
+ step('source:app', typecheck(dirs.source!, 'app')),
+ step('source:node', typecheck(dirs.source!, 'node')),
+ step('source:npm', run('node', [...packProbeArgs, cliBin, 'build'], { cwd: dirs.source, env: npmPackFromPnpmScript() })),
+ ])
+ sourceWithoutDist = !exists(dirs.source!, 'dist')
+ await Promise.all([
+ step('source:generate', nuxt(['generate', 'playground'], dirs.source)),
+ inOrder(['source:pack', () => pack(dirs.source!, 'pnpm')], ['source:attw', () => run(bin('attw'), [join(dirs.source!, '.pack/my-module-1.0.0.tgz'), '--ignore-rules', 'cjs-resolves-to-esm'], { cwd: dirs.source })]),
+ ])
+ })(),
+ (async () => {
+ if (!await inOrder(['dist:prepare', () => cli(['prepare', dirs.dist!])], ['dist:build', () => run('node', [tsdownBin], { cwd: dirs.dist })], ['dist:playground', () => nuxt(['prepare', 'playground'], dirs.dist)])) {
+ return
+ }
+ await Promise.all([step('dist:app', typecheck(dirs.dist!, 'app')), step('dist:node', typecheck(dirs.dist!, 'node'))])
+ await inOrder(['dist:generate', () => nuxt(['generate', 'playground'], dirs.dist)], ['dist:pack', () => pack(dirs.dist!, 'npm')])
+ })(),
+ ])
+})
+
+const expectBuilt = (name: string) => {
+ const { exitCode, output } = result(name)
+ expect(exitCode, output).toBe(0)
+ return output
+}
+
+const expectFailed = (name: string) => {
+ const { exitCode, output } = result(name)
+ expect(exitCode, output).not.toBe(0)
+ return output
+}
+
+describe('a module that imports runtime code, built through a symlink, under a path with spaces and non-ASCII characters', () => {
+ const dist = () => join(dirs.runtime!, 'dist')
+
+ it('should generate module metadata', async () => {
+ expectBuilt('runtime')
+ expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ configKey: 'myModule', name: 'my-module' })
+ })
+
+ it('should externalise runtime imports made through relative, aliased and `.vue` specifiers', async () => {
+ expect(runtimeSpecifiers(await read(dist(), 'module.mjs'))).toEqual([
+ './runtime/composables/useShape.js',
+ './runtime/utils/aliased.js',
+ './runtime/utils/name.js',
+ ])
+ const moduleDts = await read(dist(), 'module.d.mts')
+ expect(findStaticImports(moduleDts).find(i => i.specifier.includes('plugins'))!.code.trim()).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`)
+ expect(findStaticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx')
+ expect(moduleDts).toContain('from "nuxt/app"')
+ expect(moduleDts).not.toContain('#app')
+ })
+
+ it('should point imports of a runtime JSX file at its `.jsx` output', async () => {
+ expect(await read(dist(), 'runtime/components/JsxCard.vue')).toContain(`import JsxComponent from "./JsxComponent.jsx";`)
+ expect(await read(dist(), 'runtime/components/JsxSlot.jsx')).toMatchInlineSnapshot(`
+ "import { defineComponent } from "vue";
+ import { useNuxtApp } from "#app";
+ import JsxComponent from "./JsxComponent.jsx";
+ export const useSlotApp = () => useNuxtApp();
+ export default defineComponent((_, { slots }) => () => );
+ "
+ `)
+ expect(await read(dist(), 'runtime/components/JsxSlot.d.ts')).toContain('export declare const useSlotApp: () => import("nuxt/app").NuxtApp;')
+ })
+
+ it('should compile JSX in server runtime files and the files they import, and preserve it elsewhere', async () => {
+ expect(exists(dist(), 'runtime/server/render.jsx')).toBe(false)
+ for (const file of ['utils/strong.js', 'utils/bold.js']) {
+ expect(await read(dist(), 'runtime', file), file).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`)
+ }
+ expect(await read(dist(), 'runtime/utils/label.jsx')).toContain('label ')
+ expect(await read(dist(), 'runtime/server/render.js')).toMatchInlineSnapshot(`
+ "import { strong } from "../utils/strong.js";
+ import { jsx as _jsx } from "vue/jsx-runtime";
+ export const render = (label) => /* @__PURE__ */ _jsx("p", { children: strong(label) });
+ "
+ `)
+ expect(await read(dist(), 'runtime/server/render.d.ts')).toMatchInlineSnapshot(`
+ "import { useSlotApp } from '../components/JsxSlot.jsx';
+ export type SlotApp = ReturnType;
+ export declare const render: (label: string) => import("vue/jsx-runtime").JSX.Element;
+ "
+ `)
+ })
+
+ it('should keep every non-relative runtime import as written', async () => {
+ expect(findStaticImports(await read(dist(), 'runtime/server/handler.js')).map(i => i.specifier)).toEqual([
+ '#internal/nuxt.config.mjs',
+ '~/app.config',
+ '@/root',
+ '#app',
+ 'fake-dep',
+ '#fixture-cache',
+ '../utils/local.js',
+ ])
+ expect(findStaticImports(await read(dist(), 'runtime/utils/options.d.ts')).map(i => i.specifier)).toEqual(['fake-types'])
+ })
+
+ it('should not emit dependencies or bundler helpers into the runtime directory', async () => {
+ const files = await listFiles(join(dist(), 'runtime'))
+ expect(files.filter(file => /node_modules|_virtual/.test(file))).toEqual([])
+ for (const file of files.filter(file => /\.m?[jt]s$/.test(file))) {
+ expect(await read(dist(), 'runtime', file), file).not.toMatch(/bundled-fake-dep|DeepPartial/)
+ }
+ })
+
+ it('should keep types of packages that are not dependencies external in module declarations', async () => {
+ const types = await read(dist(), 'module.d.mts')
+ expect(types).toMatch(/from "fake-types"/)
+ expect(types).toMatch(/from "fake-cjs-types"/)
+ expect(types).not.toMatch(/DeepPartial/)
+ })
+
+ it('should name inferred types by package when the generated tsconfig maps a package to its real path', async () => {
+ const types = await read(dist(), 'module.d.mts')
+ expect(types).toMatch(/Thing<\{/)
+ expect(types).toMatch(/["']fake-schema["']/)
+ })
+
+ it('should keep bracketed file names in runtime output', () => {
+ expect(exists(dist(), 'runtime/server/routes/[...slug].js')).toBe(true)
+ expect(exists(dist(), 'runtime/server/routes/[...slug].d.ts')).toBe(true)
+ })
+
+ it('should resolve imports of the package itself to its source in declarations', async () => {
+ expect(await read(dist(), 'runtime/utils/self.d.ts')).toMatch(/=> string;/)
+ })
+
+ it('should warn about type errors that do not affect runtime declarations and build anyway', async () => {
+ const output = expectBuilt('runtime')
+ expect(output).toMatch(/2 type errors were reported while generating declarations for `?src\/runtime`?; the declarations were emitted\. If the module's own type check \(for example `?nuxt typecheck`? or `?vue-tsc --noEmit`?\) passes/)
+ expect(output).toContain('src/runtime/utils/typo.ts(1,14): error TS2322')
+ expect(output).toContain('src/runtime/components/Typo.vue(3,7): error TS2322')
+ expect(output.match(/type errors? (?:was|were) reported/g)).toHaveLength(1)
+ expect(output).toContain(guide('other-type-errors'))
+ expect(output).not.toContain('TS2307')
+ expect(await read(dist(), 'runtime/utils/typo.d.ts')).toBe('export declare const count: number;\nexport declare const double: (value: number) => number;\n')
+ const component = await read(dist(), 'runtime/components/Typo.vue.d.ts')
+ expect(component).toContain('label: string')
+ expect(component).toBe(await read(dist(), 'runtime/components/Typo.d.vue.ts'))
+ const composable = await read(dist(), 'runtime/composables/useSize.d.ts')
+ expect(composable).toContain(`import type { Props } from '../components/Sized.vue';`)
+ expect(composable).toMatch(/export declare function useSize\(props: Props\): import\("vue"\)\.ComputedRef<"xs" \| "sm" \| "md" \| undefined>;/)
+ })
+
+ it('should give every relative specifier in runtime declarations an extension that resolves', async () => {
+ expect(await unresolvedSpecifiers(dist())).toEqual([])
+ })
+})
+
+describe('a module with `isolatedDeclarations` and no `.nuxt`', () => {
+ const dist = () => join(dirs.isolated!, 'dist')
+
+ it('should prepare the module before building it', async () => {
+ expect(expectBuilt('isolated')).toMatch(new RegExp(`\\.nuxt\`? not found, running \`?nuxt-module-build prepare\`? first\\..*${guide('preparing-nuxt')}`))
+ expect(await read(dist(), 'runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
+ })
+
+ it('should build an annotated module while still inferring runtime types', async () => {
+ const moduleTypes = await read(dist(), 'module.d.mts')
+ expect(moduleTypes).toContain('NuxtModule')
+ expect(moduleTypes).toMatch(/apiKey: string/)
+ expect(await read(dist(), 'runtime/plugins/plugin.d.ts')).toContain('import("nuxt/app").Plugin<')
+ expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ name: 'my-module', configKey: 'myModule' })
+ })
+
+ it('should keep value exports as values in `types.d.mts`', async () => {
+ expect(await read(dist(), 'types.d.mts')).toMatchInlineSnapshot(`
+ "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
+
+ declare module '#app' {
+ interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
+ }
+
+ declare module '@nuxt/schema' {
+ interface NuxtHooks extends ModuleHooks {}
+ interface RuntimeConfig extends ModuleRuntimeConfig {}
+ interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
+ }
+
+ export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs'
+ "
+ `)
+ expect(expectBuilt('isolated:consumer')).toBe('')
+ })
+
+ it('should flatten, prefix and minify runtime CSS', async () => {
+ const card = await read(dist(), 'runtime/styles/card.css')
+ expect(card).toMatch(/^@import "\.\/base\.css";/)
+ expect(card).toContain('.card .title{font-weight:700}')
+ expect(card).toContain('.card:hover{color:#639}')
+ expect(card).toContain('-webkit-user-select:none')
+ expect(card).not.toMatch(/&|\n/)
+ })
+
+ it('should compile runtime Sass to CSS and skip partials', async () => {
+ const styles = join(dist(), 'runtime/styles')
+ expect(await listFiles(styles)).toEqual(['base.css', 'card.css', 'indented.css', 'legacy.less', 'theme.css'])
+ expect(await read(styles, 'theme.css')).toMatch(/^\.theme \.nested \{\s*padding: 1px;\s*\}$/m)
+ expect(await read(styles, 'theme.css')).toContain('color: #00dc82;')
+ expect(await read(styles, 'indented.css')).toContain('color: blue;')
+ })
+
+ it('should copy runtime declaration files verbatim, apart from `#app`', async () => {
+ expect(await read(dist(), 'runtime/types/ambient.d.ts')).toBe(await read(dirs.isolated!, 'src/runtime/types/ambient.d.ts'))
+ expect(await read(dist(), 'runtime/types/app.d.ts')).toBe(`import type { NuxtApp } from 'nuxt/app'\nexport type App = NuxtApp\n`)
+ })
+
+ it('should point stylesheet imports in runtime scripts at the emitted files', async () => {
+ const styled = await read(dist(), 'runtime/plugins/styled.js')
+ expect(styled).toContain('import "../styles/card.css";')
+ expect(styled).toContain('import "../styles/theme.css";')
+ expect(styled).not.toContain('theme.scss')
+ })
+})
+
+describe('a module without exported `ModuleOptions`', () => {
+ it('should generate types that infer them and keep value exports as values', async () => {
+ expectBuilt('types')
+ expect(await read(dirs.types!, 'dist/types.d.mts')).toMatchInlineSnapshot(`
+ "import type { NuxtModule } from '@nuxt/schema'
+
+ import type { default as Module, ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
+
+ declare module '#app' {
+ interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
+ }
+
+ declare module '@nuxt/schema' {
+ interface NuxtHooks extends ModuleHooks {}
+ interface RuntimeConfig extends ModuleRuntimeConfig {}
+ interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
+ }
+
+ export type ModuleOptions = typeof Module extends NuxtModule ? Partial : Record
+
+ export { defineMyModuleConfig, Mode, type ModuleHooks, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs'
+ "
+ `)
+ expect(expectBuilt('types:consumer')).toBe('')
+ })
+})
+
+describe('a module without a runtime directory', () => {
+ it('should build its entries and a directory that contains only single-file components', async () => {
+ expectBuilt('minimal')
+ expect(await listFiles(join(dirs.minimal!, 'dist'))).toMatchInlineSnapshot(`
+ [
+ "components",
+ "components/TestMe.css",
+ "components/TestMe.d.vue.ts",
+ "components/TestMe.vue",
+ "components/TestMe.vue.d.ts",
+ "components/TestMeSetup.d.vue.ts",
+ "components/TestMeSetup.vue",
+ "components/TestMeSetup.vue.d.ts",
+ "module.d.mts",
+ "module.json",
+ "module.mjs",
+ "types.d.mts",
+ "utils.d.mts",
+ "utils.mjs",
+ ]
+ `)
+ })
+
+ it('should refuse an `outDir` outside the module root', () => {
+ expect(expectFailed('minimal:outDir')).toContain(`\`--outDir ..\` resolves to \`${resolve(dirs.minimal!, '..')}\`, which is not inside the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`)
+ expect(exists(dirs.minimal!, 'package.json')).toBe(true)
+ })
+
+ it('should fail on `--stub` and point at what replaces it', () => {
+ for (const command of ['build', 'prepare']) {
+ expect(expectFailed(command === 'build' ? 'minimal:stub' : 'minimal:prepare-stub'), command).toContain(`\`nuxt-module-build ${command} --stub\` has been removed. With pnpm or Yarn 4, point \`package.json\` at the module's sources. Otherwise, build \`dist\` with \`tsdown\` and rebuild it with \`tsdown --watch\`. ${guide('stub-builds')}`)
+ }
+ })
+})
+
+describe('a module whose runtime files import files around them', () => {
+ const dist = () => join(dirs.shape!, 'dist')
+
+ it('should keep the imports and re-exports of each runtime file as written, in source order', async () => {
+ expectBuilt('shape')
+ const runtime = join(dist(), 'runtime')
+ expect(await read(runtime, 'disabled/index.js')).toMatchInlineSnapshot(`
+ "import "./side.js";
+ export { defineThing } from "./composables/defineThing.js";
+ "
+ `)
+ expect(await read(runtime, 'disabled/composables/defineThing.js')).toMatchInlineSnapshot(`
+ "export { defineThing } from "../../composables/mock.js";
+ "
+ `)
+ expect(await read(runtime, 'content/index.js')).toMatchInlineSnapshot(`
+ "export * from "../components/TestMe.vue";
+ export * from "../components/TestMeSetup.vue";
+ export * from "./prose.js";
+ "
+ `)
+ expect(await read(runtime, 'content/index.d.ts')).toMatchInlineSnapshot(`
+ "export * from '../components/TestMe.vue';
+ export * from '../components/TestMeSetup.vue';
+ export * from './prose.js';
+ "
+ `)
+ expect(await read(runtime, 'content/prose.d.ts')).toMatchInlineSnapshot(`
+ "export * from './levels.js';
+ export interface ProseThing {
+ title: string;
+ }
+ "
+ `)
+ expect(await read(runtime, 'order/interleaved.js')).toMatchInlineSnapshot(`
+ "import "fake-register";
+ import { level } from "./levels.js";
+ export * from "./reexported.js";
+ import "./order.css";
+ export { useState } from "#imports";
+ import "fake-polyfill";
+ import "./effect.js";
+ import { ref } from "vue";
+ export const value = ref(level);
+ "
+ `)
+ })
+
+ it('should point runtime imports outside the runtime directory at the files emitted for them', async () => {
+ expect(await read(dist(), 'runtime/server/uses.js')).toMatchInlineSnapshot(`
+ "import { merge } from "../../utils/merge.mjs";
+ import { CONSTANT } from "../../shared/constants.js";
+ export const combine = (a, b) => [merge(a, b), CONSTANT];
+ "
+ `)
+ expect(await read(dist(), 'runtime/server/uses.d.ts')).toMatchInlineSnapshot(`
+ "import type { RootType } from '../../_external/src/types.js';
+ import type { RuntimeType } from '../types.js';
+ export declare const combine: (a: RootType & RuntimeType, b: RootType & RuntimeType) => readonly [RootType & RuntimeType, 10];
+ "
+ `)
+ expect(await read(dist(), 'runtime/escaping.js')).toContain(`import("../_external/external.js")`)
+ expect(await read(dist(), 'shared/constants.js')).toMatchInlineSnapshot(`
+ "import { LIMIT } from "./limits.js";
+ export const CONSTANT = LIMIT;
+ "
+ `)
+ const files = await listFiles(dist())
+ expect(files.filter(file => !file.startsWith('runtime'))).toMatchInlineSnapshot(`
+ [
+ "_external",
+ "_external/external.d.ts",
+ "_external/external.js",
+ "_external/src",
+ "_external/src/types.d.ts",
+ "data.d.mts",
+ "data.mjs",
+ "module.d.mts",
+ "module.json",
+ "module.mjs",
+ "routing.d.ts",
+ "shared",
+ "shared/constants.d.ts",
+ "shared/constants.js",
+ "shared/limits.d.ts",
+ "shared/limits.js",
+ "types",
+ "types.d.mts",
+ "types/middlewares.d.ts",
+ "utils",
+ "utils.d.mts",
+ "utils.mjs",
+ "utils/merge.d.mts",
+ "utils/merge.mjs",
+ ]
+ `)
+ expect(files.filter(file => /^runtime\/(?:types|server|utils)/.test(file))).toMatchInlineSnapshot(`
+ [
+ "runtime/server",
+ "runtime/server/limiter.d.ts",
+ "runtime/server/limiter.js",
+ "runtime/server/uses.d.ts",
+ "runtime/server/uses.js",
+ "runtime/types.d.ts",
+ "runtime/types.js",
+ "runtime/utils",
+ "runtime/utils/props.d.ts",
+ "runtime/utils/props.js",
+ "runtime/utils/provider.d.ts",
+ "runtime/utils/provider.js",
+ ]
+ `)
+ })
+
+ it('should emit only declarations for files outside the runtime directory that runtime files use as types', async () => {
+ expect(await read(dist(), 'runtime/server/limiter.js')).toMatchInlineSnapshot(`
+ "import "../disabled/side.js";
+ export const limit = (options) => options.maxRequestSizeInBytes;
+ "
+ `)
+ expect(await read(dist(), 'runtime/composables/useLocaleRoute.js')).toMatchInlineSnapshot(`
+ "export const useLocaleRoute = (route) => route;
+ "
+ `)
+ expect(await read(dist(), 'routing.d.ts')).toMatchInlineSnapshot(`
+ "import type { RootType } from './_external/src/types.js';
+ export interface RouteInfo {
+ path: string;
+ root: RootType;
+ }
+ export declare const localizeRoutes: (file: string) => string;
+ "
+ `)
+ for (const file of ['routing.js', 'kit', 'types/middlewares.js', 'types.d.ts', 'types.js', '_external/src/types.js']) {
+ expect(exists(dist(), file), file).toBe(false)
+ }
+ })
+
+ it('should type imports of build-time aliases as `any` in declarations', async () => {
+ const runtime = join(dist(), 'runtime')
+ expect(await read(runtime, 'composables/useThemeConfig.d.ts')).toContain('useThemeConfig: () => any;')
+ expect(await read(runtime, 'composables/useButton.d.ts')).toMatchInlineSnapshot(`
+ "export declare const useButton: () => {
+ slots: any;
+ size: any;
+ ui: any;
+ };
+ "
+ `)
+ expect(await read(runtime, 'components/Button.d.vue.ts')).toMatchInlineSnapshot(`
+ "type __VLS_Props = {
+ size?: string;
+ };
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {
+ classes: any[];
+ }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
+ declare const _default: typeof __VLS_export;
+ export default _default;
+ "
+ `)
+ expect(exists(runtime, 'components/Sized.vue.d.ts')).toBe(true)
+ })
+
+ it('should give every relative specifier in declarations an extension that resolves', async () => {
+ expect(await unresolvedSpecifiers(dist())).toEqual([])
+ })
+})
+
+describe('a module whose entry Node cannot import natively, with a wildcard `paths` entry', () => {
+ it('should prepare it without handing it to jiti', async () => {
+ expect(expectBuilt('loader:prepare')).not.toContain('ERR_INTERNAL_ASSERTION')
+ expect(await read(dirs.loader!, '.nuxt/nuxt.node.d.ts')).toContain('/// ')
+ expect(await read(dirs.loader!, '.nuxt/types/modules.d.ts')).toContain(`typeof import(${JSON.stringify(join(dirs.loader!, 'src/module'))}).default`)
+ })
+
+ it('should re-export the module\'s default export from the types that `prepare` writes', () => {
+ expect(expectBuilt('loader:probe')).toBe('')
+ })
+
+ it('should bundle the `imports` of `package.json` and the files they point at', async () => {
+ expectBuilt('loader')
+ const built = await read(dirs.loader!, 'dist/module.mjs')
+ expect(built).toContain('loaded helper')
+ expect(built).toContain('through imports')
+ expect(built).not.toContain('#internal')
+ })
+
+ it('should not let a wildcard `paths` entry shadow real packages when loading meta', async () => {
+ expect(JSON.parse(await read(dirs.loader!, 'dist/module.json'))).toMatchObject({ name: 'my-module', configKey: 'my-module' })
+ })
+})
+
+describe('a module whose code Node cannot load', () => {
+ it('should fail to build and prepare, with how to rewrite each import and each piece of syntax', async () => {
+ const line = (await read(dirs.unloadable!, 'src/module.ts')).split('\n').findIndex(line => line.includes('./utils.js')) + 1
+ for (const name of ['unloadable', 'unloadable:prepare']) {
+ const output = expectFailed(name)
+ expect(output, name).toContain([
+ 'Module code has to load with Node, which strips types and resolves imports as written:',
+ ' - src/levels.ts:1:1: `enum` (use an `as const` object and a union type of its values)',
+ ' - src/module.ts:1:37: `../package.json` is JSON (use `import pkg from \'../package.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)',
+ ' - src/module.ts:4:1: `enum` (use an `as const` object and a union type of its values)',
+ ' - src/module.ts:5:28: parameter property (declare the field and assign it in the constructor)',
+ ].join('\n'))
+ expect(output, name).toMatch(/src\/module\.ts:\d+:\d+: angle-bracket type assertion \(write `value as Type`\)/)
+ expect(output, name).toContain([
+ ` - src/module.ts:${line}:31: \`./utils.js\` (use \`./utils.ts\`)`,
+ ` - src/module.ts:${line + 1}:24: \`./helpers\` (use \`./helpers.ts\`)`,
+ ` - src/module.ts:${line + 2}:21: \`./kit\` (use \`./kit/index.ts\`)`,
+ `Change each one as suggested. ${guide('module-code-loads-with-node')}`,
+ ].join('\n'))
+ expect(output, name).not.toContain(`:${line + 3}:`)
+ }
+ expect(exists(dirs.unloadable!, 'dist')).toBe(false)
+ })
+
+ it('should fail and remove the output when the built module cannot be loaded', () => {
+ expect(expectFailed('unloadableDist')).toContain('Cannot load `dist/module.mjs` to write `module.json`: fails once built')
+ expect(exists(dirs.unloadableDist!, 'dist')).toBe(false)
+ })
+})
+
+describe('a module whose declarations cannot be generated', () => {
+ it('should surface isolated declaration diagnostics when the tsconfig opts in', () => {
+ const output = expectFailed('isolatedError')
+ expect(output).toMatch(/Declaration generation failed under `?isolatedDeclarations/)
+ expect(output).toMatch(/TS90\d\d/)
+ expect(output).toContain(guide('isolated-declarations'))
+ expect(output).not.toMatch(/Type declarations could not be generated/)
+ expect(exists(dirs.isolatedError!, 'dist')).toBe(false)
+ })
+
+ it('should explain type errors that prevent declaration generation', () => {
+ const output = expectFailed('typeError')
+ expect(output).toMatch(/TS4094/)
+ expect(output).toMatch(/Type declarations could not be generated/)
+ expect(output).toMatch(/cannot reference by name.*explicit type annotation, such as `ReturnType` for a value produced by an imported `fn`:\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/)
+ expect(output).toContain(guide('portability-errors'))
+ expect(exists(dirs.typeError!, 'dist')).toBe(false)
+ })
+
+ it('should fail on portability errors in a single-file component and in a script sharing its program', () => {
+ const output = expectFailed('vueError')
+ expect(output).toMatch(/components\/Cached\.vue\(4,14\): error TS(?:2742|2883)/)
+ expect(output).toMatch(/server\/cached\.ts\(3,14\): error TS(?:2742|2883)/)
+ expect(output).toMatch(/cannot reference by name.*:\n(?:- `\w+` in \S+\n)*- `cachedHandler` in \S*src\/runtime\/components\/Cached\.vue:4\n/)
+ expect(output).toMatch(/\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/)
+ expect(output).toContain(guide('portability-errors'))
+ expect(exists(dirs.vueError!, 'dist')).toBe(false)
+ })
+})
+
+describe('tsconfig lookup', () => {
+ it('should generate declarations for each project of a solution-style tsconfig', async () => {
+ expectBuilt('solution')
+ expect(await read(dirs.solution!, 'dist/runtime/server/api/[id].get.d.ts')).toMatch(/=> string;/)
+ expect(await read(dirs.solution!, 'dist/runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
+ expect(exists(dirs.solution!, 'dist/runtime/components/TestMe.vue.d.ts')).toBe(true)
+ })
+
+ it('should use a tsconfig from a parent directory, naming runtime types by package when it maps the package into the store', async () => {
+ expectBuilt('parent')
+ expect(await read(dirs.parent!, 'dist/runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/)
+ expect(await read(dirs.parent!, 'dist/runtime/logger.d.ts')).toMatch(/import\("fake-logger"\)\.LoggerInstance/)
+ })
+
+ it('should generate declarations with the module\'s own `.nuxt` when the tsconfig takes its types from a playground', async () => {
+ expect(expectBuilt('routes')).toMatch(new RegExp(`\\.\\./tsconfig.json\`? takes its generated types from another app's \`?.nuxt\`?; declarations are generated with \`?.nuxt/tsconfig.json\`? instead. Add a \`?tsconfig.json\`? in the module directory that extends \`?./.nuxt/tsconfig.json\`?. ${guide('module-tsconfig')}`))
+ expect(await read(dirs.routes!, 'playground/.nuxt/types/nitro-routes.d.ts')).toContain('/api/secret')
+ for (const file of await listFiles(join(dirs.routes!, 'dist'))) {
+ if (file.includes('.')) {
+ expect(await read(dirs.routes!, 'dist', file), file).not.toMatch(/must-not-be-published|playground|\.nuxt/)
+ }
+ }
+ })
+
+ it('should type the responses of routes the module registers and leave other routes unknown', async () => {
+ const dir = dirs.routes!
+ expect(await read(dir, '.nuxt/types/nitro-routes.d.ts')).toContain('/api/own')
+ const { default: ts } = await import('typescript')
+ const files = ts.getParsedCommandLineOfConfigFile(join(dir, '.nuxt/tsconfig.json'), {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} })!.fileNames
+ expect(files.map(file => relative(dir, file)).filter(file => file.includes('routes.d.ts')).sort()).toEqual(['../sibling/types/routes.d.ts', 'docs/types/routes.d.ts', 'playground/types/routes.d.ts'])
+ expect(await read(dir, 'dist/runtime/composables/useOwn.d.ts')).toBe(`export declare const useOwn: () => import("nuxt/app").AsyncData<{\n own: "module-owned";\n} | undefined, import("nuxt/app").NuxtError | undefined>;\n`)
+ expect(await read(dir, 'dist/runtime/composables/useGlobal.d.ts')).toBe('export declare const useGlobal: () => Fake.Thing;\n')
+ expect(output('routes')).not.toMatch(/type errors? (?:was|were) reported/)
+ for (const name of ['useSecret', 'useSibling', 'useDocs']) {
+ expect(await read(dir, `dist/runtime/composables/${name}.d.ts`), name).toBe(`export declare const ${name}: () => import("nuxt/app").AsyncData | undefined>;\n`)
+ }
+ const component = await read(dir, 'dist/runtime/components/Routes.vue.d.ts')
+ expect(component).toContain('own: import("vue").Ref<{\n own: "module-owned";\n } | undefined, {\n own: "module-owned";\n } | undefined>;')
+ expect(component).toContain('secret: import("vue").Ref;')
+ })
+})
+
+describe('tsdown configs', () => {
+ it.each([
+ ['an object', 'object', 'out'],
+ ['an array', 'array', 'out'],
+ ['a function', 'function', 'dist'],
+ ])('should prepare and build a module whose tsdown config exports %s', async (_, shape, outDir) => {
+ expect(expectBuilt(`${shape}:prepare`)).not.toContain('ERROR')
+ expect(exists(dirs[shape]!, '.nuxt/tsconfig.json')).toBe(true)
+ expect(exists(dirs[shape]!, '.nuxt/module-builder/types.d.mts')).toBe(true)
+ expectBuilt(shape)
+ const out = join(dirs[shape]!, outDir)
+ expect(await read(out, 'shared/value.mjs')).toContain(`from "./other.mjs"`)
+ expect(exists(out, 'helpers.mjs')).toBe(true)
+ expect(exists(out, 'types.d.mts')).toBe(true)
+ expect(JSON.parse(await read(out, 'module.json'))).toMatchObject({ name: 'my-module' })
+ if (shape === 'array') {
+ expect(await read(dirs[shape]!, 'dist-cli/cli.mjs')).toContain(`const cli = "cli"`)
+ }
+ })
+
+ it('should build with the tsdown config\'s `outDir` and `sourcemap` unless `--outDir` and `--sourcemap` override them', () => {
+ expect(exists(dirs.object!, 'out/module.mjs.map')).toBe(true)
+ expect(exists(dirs.object!, 'out/runtime/plugins/plugin.js.map')).toBe(true)
+ expect(exists(dirs.object!, 'dist')).toBe(false)
+ expectBuilt('flags')
+ expect(exists(dirs.flags!, 'custom/module.json')).toBe(true)
+ expect(exists(dirs.flags!, 'custom/module.mjs.map')).toBe(false)
+ expect(exists(dirs.flags!, 'custom/runtime/plugins/plugin.js.map')).toBe(false)
+ })
+
+ it('should refuse `hooks` in `builder()` and point at tsdown\'s own', () => {
+ for (const name of ['builderHooks', 'builderHooks:prepare']) {
+ expect(expectFailed(name), name).toContain(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`)
+ }
+ })
+
+ it('should fail to prepare with a tsdown config whose `cwd` is another directory', () => {
+ expect(expectFailed('configCwd')).toContain('`tsdown.config.ts` sets `cwd`, but `prepare` reads the module in the directory of the tsdown config.')
+ expectBuilt('configCwd:fixed')
+ })
+
+ it('should fail on a tsdown config that Node cannot load', () => {
+ for (const name of ['configEnum', 'configEnum:prepare']) {
+ const output = expectFailed(name)
+ expect(output, name).toContain('tsdown.config.ts:2:1: `enum` (use an `as const` object and a union type of its values)')
+ expect(output, name).toContain(guide('module-code-loads-with-node'))
+ }
+ })
+
+ it('should fail on a tsdown config without `builder()` and show how to add it', () => {
+ for (const name of ['withoutPlugin', 'withoutPlugin:prepare']) {
+ const output = expectFailed(name)
+ expect(output, name).toContain([
+ '`tsdown.config.ts` does not build the module with `builder()`. Add the plugin:',
+ '',
+ ` import { builder } from '@nuxt/module-builder/tsdown'`,
+ ` import { defineConfig } from 'tsdown'`,
+ '',
+ ` export default defineConfig({`,
+ ` plugins: [builder()],`,
+ ` })`,
+ ].join('\n'))
+ expect(output, name).toContain(guide('tsdown-config'))
+ }
+ expect(expectFailed('entriesOnly')).toContain('`tsdown.config.ts` does not build the module with `builder()`.')
+ expect(exists(dirs.entriesOnly!, 'dist')).toBe(false)
+ })
+
+ it('should load the package root without tsdown, and point at installing it to build', () => {
+ expect(expectBuilt('withoutTsdown:root').trim()).toBe('build,defineBuildConfig,prepare')
+ expect(expectFailed('withoutTsdown')).toContain(guide('install-tsdown'))
+ })
+})
+
+describe('prepare', () => {
+ it('should augment the same interfaces from the types `prepare` writes as from `dist`, through star re-exports', async () => {
+ expectBuilt('starExports:prepare')
+ expectBuilt('starExports')
+ const shims = async (file: string) => (await read(dirs.starExports!, file)).match(/^declare module '[^']+' \{\n[\s\S]*?\n\}$/gm)
+ const sourceShims = await shims('.nuxt/module-builder/types.d.mts')
+ expect(sourceShims).toEqual(await shims('dist/types.d.mts'))
+ expect(sourceShims).toEqual([
+ `declare module '#app' {\n interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}\n}`,
+ `declare module '@nuxt/schema' {\n interface NuxtHooks extends ModuleHooks {}\n interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}\n}`,
+ ])
+ for (const index of [0, 1]) {
+ const { output } = result(`starExports:probe-${index}`)
+ expect(output.split('\n').filter(line => /^(?:src|dist|\.nuxt\/module-builder)\/|^probe-\d\.ts/.test(line)), String(index)).toEqual([])
+ }
+ })
+
+ it('should prepare a module that lists its own package in `.nuxtrc` and `nuxt.config`, with or without `dist`', async () => {
+ const references = async (dir: string) => (await read(dir, '.nuxt/nuxt.node.d.ts')).split('\n').filter(line => line.includes('types="self-listed-module"') || line === '/// ')
+ for (const name of ['selfListedDist', 'selfListedSource']) {
+ expect(expectBuilt(name).match(/\[setup\] .*/g), name).toEqual(['[setup] from-config'])
+ expect(await references(dirs[name]!), name).toEqual(['/// '])
+ }
+ })
+
+ it('should resolve the module\'s own package to declarations of module code in its app, server and shared tsconfigs', async () => {
+ const dir = dirs.ownPackage!
+ expectBuilt('ownPackage')
+ expect(expectBuilt('ownPackage:typecheck')).toBe('')
+ for (const name of ['app', 'server', 'shared']) {
+ const files = expectBuilt(`ownPackage:${name}`).split('\n').map(file => file.trim())
+ expect(files, name).not.toContain(join(dir, 'src/module.ts'))
+ expect(files, name).not.toContain(join(dir, 'src/utils.ts'))
+ expect(files, name).not.toContain(join(dir, 'src/helpers.ts'))
+ expect(files, name).toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'))
+ }
+ expect(output('ownPackage:app')).toContain(join(dir, '.nuxt/module-builder/declarations/src/utils.d.ts'))
+ })
+
+ it('should generate tsconfigs for the module entry, without the playground or the workspace, and with app aliases and root options for module code', async () => {
+ const generated = async (name: string) => JSON.parse(await read(dirs.ownPackage!, `.nuxt/tsconfig.${name}.json`))
+ const [node, app] = [await generated('node'), await generated('app')]
+ expect(node.include).toContain('../src/*.ts')
+ expect(node.compilerOptions.paths['#app']).toBeDefined()
+ expect(node.compilerOptions.paths['#components']).toBeDefined()
+ expect(node.compilerOptions.types).toContain('vitest/importMeta')
+ expect(app.exclude).toContain('../playground')
+ expect(app.include).not.toContain('../../**/*')
+ expect(app.include).toContain('../src/runtime')
+ for (const name of ['app', 'node', 'server', 'shared']) {
+ const { include, exclude } = await generated(name)
+ expect([...include, ...exclude].filter((pattern: string) => pattern.startsWith('../src/dist')), name).toEqual([])
+ }
+ })
+
+ it('should write the declarations of module code with oxc when its tsconfig sets `isolatedDeclarations`', async () => {
+ const dir = dirs.ownPackageIsolated!
+ expect(expectBuilt('ownPackageIsolated')).not.toContain('The build reports the same errors')
+ expect(await read(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts')).toContain('interface Payload')
+ const moduleDeclaration = await read(dir, '.nuxt/module-builder/declarations/src/module.d.ts')
+ expect(moduleDeclaration).toContain('from "./nested/payload.js"')
+ expect(moduleDeclaration).toContain('from "./nested/shape.js"')
+ expect(expectBuilt('ownPackageIsolated:typecheck')).toBe('')
+ const files = expectBuilt('ownPackageIsolated:app')
+ expect(files).toContain(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts'))
+ expect(files).not.toContain(join(dir, 'src/nested/payload.ts'))
+ expect(files).not.toContain(join(dir, 'src/nested/shape.ts'))
+ })
+
+ it('should warn about a declaration error in module code, and write the other declarations', () => {
+ const output = expectBuilt('ownPackageError')
+ expect(output).toContain('The build reports the same errors')
+ expect(output).toContain('src/logger.ts(3,14): error TS2883')
+ expect(exists(dirs.ownPackageError!, '.nuxt/module-builder/declarations/src/module.d.ts')).toBe(true)
+ expect(exists(dirs.ownPackageError!, '.nuxt/module-builder/declarations/types.d.mts')).toBe(true)
+ })
+
+ it('should keep `.nuxt/tsconfig.json` one program over the module\'s sources, with the generated tsconfigs adapted', async () => {
+ const dir = dirs.legacyPrepare!
+ expectBuilt('legacyPrepare')
+ const generated = async (name: string) => JSON.parse(await read(dir, `.nuxt/${name}.json`))
+ expect((await generated('tsconfig.app')).compilerOptions.paths['my-module']).toEqual(['./module-builder/declarations/types.d.mts'])
+ const legacy = await generated('tsconfig')
+ expect(legacy.compilerOptions.paths['my-module']).toBeUndefined()
+ expect(legacy.include).not.toContain('./module-builder/declarations/types.d.mts')
+ expect(legacy.exclude).not.toContain('../src/runtime/server')
+ const typecheck = output('legacyPrepare:typecheck')
+ expect(typecheck).not.toMatch(/error TS5\d{3}/)
+ expect(typecheck.split('\n').filter(line => /^(?:src|\.nuxt)\//.test(line))).toEqual([])
+ const files = output('legacyPrepare:files')
+ expect(files).toContain(join(dir, 'src/module.ts'))
+ expect(files).toContain(join(dir, 'src/runtime/server/options.ts'))
+ expect(files).not.toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'))
+ })
+})
+
+describe('the example', () => {
+ const typeErrors = (name: string) => output(name).split('\n').filter(line => line.includes('error TS'))
+
+ it('should type the playground and its config through the module\'s exports, from its sources without `dist` and from `dist`', () => {
+ for (const name of ['source:app', 'source:node', 'dist:app', 'dist:node']) {
+ expect(typeErrors(name), name).toEqual([])
+ }
+ expect(sourceWithoutDist).toBe(true)
+ })
+
+ it('should render the playground with the module installed by name', async () => {
+ for (const flow of ['source', 'dist']) {
+ expectBuilt(`${flow}:generate`)
+ expect(await read(dirs[flow]!, 'playground/.output/public/index.html')).toContain('Nuxt module playground!')
+ }
+ expect(await read(dirs.source!, 'playground/.nuxt/types/plugins.d.ts')).toContain('src/runtime/plugins/plugin')
+ })
+
+ it('should refuse to build source exports for a pack by npm, including when a pnpm script runs it', () => {
+ const { output, exitCode } = result('source:npm')
+ expect(exitCode, `${packProbeContext()}\n${output}`).not.toBe(0)
+ expect(output).toMatch(/`npm(?:@[\d.]+)?` packs these fields of `package\.json` as written, and they point at TypeScript sources or paths that `files` leaves out: `exports`, `main`, `types` \(`\.\/\.nuxt\/module-builder\/types\.d\.mts`, `\.\/src\/module\.ts`, `\.\/src\/utils\.ts`\)\./)
+ expect(output).toContain(guide('publishing-source-exports'))
+ })
+
+ it('should pack the `dist` paths in `publishConfig` with pnpm, and `dist` with npm, without warnings', async () => {
+ const packed = async (dir: string) => JSON.parse((await succeed(run('tar', ['-xzOf', join(dir, '.pack/my-module-1.0.0.tgz'), 'package/package.json']))))
+ expect(await packed(dirs.source!)).toMatchObject({
+ exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' } },
+ main: './dist/module.mjs',
+ types: './dist/types.d.mts',
+ })
+ expect(await packed(dirs.source!)).not.toHaveProperty('publishConfig')
+ const { publishConfig } = JSON.parse(await read(exampleDir, 'package.json'))
+ expect(await packed(dirs.dist!)).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main })
+ for (const name of ['source:pack', 'dist:pack']) {
+ const output = expectBuilt(name)
+ expect(output, name).toContain('Build complete')
+ expect(output, name).not.toMatch(/\bWARN\b/)
+ }
+ expect(output('source:pack')).toContain('[publint] No issues found')
+ expectBuilt('source:attw')
+ })
+
+ describe('`dist`', () => {
+ const dist = () => join(dirs.dist!, 'dist')
+
+ it('should generate all files', async () => {
+ expect(await listFiles(dist())).toMatchInlineSnapshot(`
+ [
+ "module.d.mts",
+ "module.json",
+ "module.mjs",
+ "runtime",
+ "runtime/assets",
+ "runtime/assets/config.json",
+ "runtime/components",
+ "runtime/components/JsxComponent.d.ts",
+ "runtime/components/JsxComponent.jsx",
+ "runtime/components/TestMe.css",
+ "runtime/components/TestMe.d.vue.ts",
+ "runtime/components/TestMe.vue",
+ "runtime/components/TestMe.vue.d.ts",
+ "runtime/components/TestMeSetup.d.vue.ts",
+ "runtime/components/TestMeSetup.vue",
+ "runtime/components/TestMeSetup.vue.d.ts",
+ "runtime/composables",
+ "runtime/composables/useAliasedApp.d.ts",
+ "runtime/composables/useAliasedApp.js",
+ "runtime/composables/useAppNuxt.d.ts",
+ "runtime/composables/useAppNuxt.js",
+ "runtime/composables/useWrappedFetch.d.ts",
+ "runtime/composables/useWrappedFetch.js",
+ "runtime/plugins",
+ "runtime/plugins/plugin.d.ts",
+ "runtime/plugins/plugin.js",
+ "types.d.mts",
+ "utils.d.mts",
+ "utils.mjs",
+ ]
+ `)
+ })
+
+ it('should reference `@nuxt/schema` rather than `nuxt/schema` in module declarations', async () => {
+ const types = await read(dist(), 'module.d.mts')
+ expect(types).toContain('import("@nuxt/schema")')
+ expect(types).not.toContain('import("nuxt/schema")')
+ })
+
+ it('should copy non-code files in the runtime directory', async () => {
+ expect(await read(dist(), 'runtime/components/TestMe.css')).toBe('.test-me{color:#639}')
+ })
+
+ it('should give every relative specifier in runtime declarations an extension that resolves', async () => {
+ expect(await unresolvedSpecifiers(dist())).toEqual([])
+ })
+
+ it('should write types to output directory', async () => {
+ expect(await read(dist(), 'types.d.mts')).toMatchInlineSnapshot(`
+ "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
+
+ declare module '#app' {
+ interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
+ }
+
+ declare module '@nuxt/schema' {
+ interface NuxtHooks extends ModuleHooks {}
+ interface RuntimeConfig extends ModuleRuntimeConfig {}
+ interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
+ }
+
+ export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs'
+ "
+ `)
+ })
+
+ it('should generate module metadata as separate JSON file', async () => {
+ const tsdownPkg = await readPackageJSON('tsdown')
+ expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({
+ builder: { '@nuxt/module-builder': version, 'tsdown': tsdownPkg.version },
+ configKey: 'myModule',
+ name: 'my-module',
+ version: '1.0.0',
+ })
+ })
+
+ it('should generate typed plugin', async () => {
+ const pluginDts = await read(dist(), 'runtime/plugins/plugin.d.ts')
+ const appAlias = `import\\("nuxt/app"\\)`
+ expect(pluginDts).toMatch(/^export type SharedTypeFromRuntime = 'shared-type';$/m)
+ expect(pluginDts).toMatch(new RegExp(`declare const _default: ${appAlias}\\.Plugin<\\{\\s*injection: "injected";\\s*\\}> & ${appAlias}\\.ObjectPlugin<\\{\\s*injection: "injected";\\s*\\}>;`))
+ expect(pluginDts).toMatch(/^export default _default;$/m)
+ })
+
+ it('should resolve every shape of `#app` alias in runtime declarations, and leak none of them', async () => {
+ const declaration = await read(dist(), 'runtime/composables/useAliasedApp.d.ts')
+ expect(declaration).toMatch(/declare const useAppInstance: \(\) => import\("nuxt\/app"\)\.NuxtApp;/)
+ expect(declaration).toMatch(/declare const useAppRouter: \(\) => import\("vue-router"\)\./)
+ expect(declaration).toMatch(/declare const useAppCookie: \(name: string\) => import\("nuxt\/app"\)\.CookieRef)
+ expect(await read(dist(), 'runtime/composables/useAppNuxt.d.ts')).toMatch(/declare const useAppFromNuxt: \(\) => import\("nuxt\/app"\)\.NuxtApp;/)
+ for (const file of (await listFiles(join(dist(), 'runtime'))).filter(file => /\.d\.[^/]*ts$/.test(file))) {
+ const contents = await read(dist(), 'runtime', file)
+ expect(contents, file).not.toMatch(/(["'])#app(?:\/[^"']*)?\1/)
+ expect(contents, file).not.toMatch(/import\("#app(?:\/[^"]*)?"\)/)
+ }
+ })
+
+ it('should correctly add extensions to imports from runtime/ directory', async () => {
+ const runtimeImport = findStaticImports(await read(dist(), 'module.d.mts')).find(i => i.specifier.includes('runtime'))
+ expect(runtimeImport!.code.trim()).toMatchInlineSnapshot(`"import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";"`)
+ })
+
+ it('should generate components', async () => {
+ for (const file of ['TestMe.vue', 'TestMe.vue.d.ts', 'TestMeSetup.vue', 'TestMeSetup.vue.d.ts', 'TestMeSetup.d.vue.ts']) {
+ await expect((await read(dist(), 'runtime/components', file)).replace(/\r\n/g, '\n')).toMatchFileSnapshot(`__snapshots__/${file}`)
+ }
+ })
+
+ it('should generate wrapped composables', async () => {
+ const expectedErrorType = satisfies(nuxtVersion, '^3') ? 'null' : 'undefined'
+ const errorType = satisfies(nuxtVersion, '^3')
+ ? 'import\\("ofetch"\\)\\.FetchError'
+ : '(?:import\\("ofetch"\\)\\.FetchError|import\\("nuxt/app"\\)\\.NuxtError)'
+ expect(await read(dist(), 'runtime/composables/useWrappedFetch.d.ts')).toMatch(new RegExp(`^export declare const useWrappedFetch: \\(\\) => import\\("nuxt/app"\\)\\.AsyncData;$`, 'm'))
+ })
+
+ it('should preserve JSX in runtime files for the app to compile', async () => {
+ expect(exists(dist(), 'runtime/components/JsxComponent.js')).toBe(false)
+ await expect(await read(dist(), 'runtime/components/JsxComponent.jsx')).toMatchFileSnapshot('__snapshots__/JsxComponent.jsx')
+ await expect(await read(dist(), 'runtime/components/JsxComponent.d.ts')).toMatchFileSnapshot('__snapshots__/JsxComponent.d.ts')
+ })
+ })
+})
diff --git a/test/deprecations.spec.ts b/test/deprecations.spec.ts
deleted file mode 100644
index cccc9add..00000000
--- a/test/deprecations.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { fileURLToPath } from 'node:url'
-import { join } from 'pathe'
-import ts from 'typescript'
-import { describe, expect, it } from 'vitest'
-
-const repoRoot = fileURLToPath(new URL('..', import.meta.url))
-
-function deprecations(source: string) {
- const file = join(repoRoot, 'test/__deprecations__.ts')
- const options: ts.CompilerOptions = {
- allowImportingTsExtensions: true,
- resolveJsonModule: true,
- module: ts.ModuleKind.Preserve,
- moduleResolution: ts.ModuleResolutionKind.Bundler,
- target: ts.ScriptTarget.ES2024,
- strict: true,
- noEmit: true,
- skipLibCheck: true,
- }
- const service = ts.createLanguageService({
- getScriptFileNames: () => [file],
- getScriptVersion: () => '1',
- getScriptSnapshot: name => name === file ? ts.ScriptSnapshot.fromString(source) : ts.sys.fileExists(name) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(name)!) : undefined,
- getCurrentDirectory: () => repoRoot,
- getCompilationSettings: () => options,
- getDefaultLibFileName: ts.getDefaultLibFilePath,
- fileExists: name => name === file || ts.sys.fileExists(name),
- readFile: name => name === file ? source : ts.sys.readFile(name),
- })
- expect(service.getSemanticDiagnostics(file).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([])
- return service.getSuggestionDiagnostics(file)
- .filter(diagnostic => diagnostic.reportsDeprecated)
- .map(diagnostic => ({
- name: source.slice(diagnostic.start, diagnostic.start! + diagnostic.length!),
- advice: ts.displayPartsToString(service.getQuickInfoAtPosition(file, diagnostic.start!)?.tags?.find(tag => tag.name === 'deprecated')?.text),
- }))
-}
-
-describe('deprecations in the editor', () => {
- it('should mark `defineBuildConfig()`', () => {
- expect(deprecations([
- `import { defineBuildConfig } from '../src/index.ts'`,
- `defineBuildConfig({ entries: ['./src/utils'] })`,
- ].join('\n'))).toEqual(Array.from({ length: 2 }, () => ({
- name: 'defineBuildConfig',
- advice: expect.stringMatching(/`builder\(\)` from `@nuxt\/module-builder\/tsdown`, in `tsdown\.config\.ts`/),
- })))
- })
-})
diff --git a/test/legacy.spec.ts b/test/legacy.spec.ts
new file mode 100644
index 00000000..2dfd7a8e
--- /dev/null
+++ b/test/legacy.spec.ts
@@ -0,0 +1,551 @@
+import { createHash } from 'node:crypto'
+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { consola } from 'consola'
+import { findStaticImports } from 'mlly'
+import { join, relative } from 'pathe'
+import ts from 'typescript'
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+
+import { bundledEntries, entryName } from '../src/build/options.ts'
+import { assertNoLegacyBuildConfig, formatUnsupportedOptions, loadBuildConfig, translateBuildConfig, warnDeprecatedBuildConfig } from '../src/legacy/build-config.ts'
+import { guide } from '../src/build/guide.ts'
+import type { FixtureOptions, Result } from './utils.ts'
+import { cli, exists, fixture, listFiles, read, repoRoot, tsdown } from './utils.ts'
+
+const exampleDir = fileURLToPath(new URL('../example', import.meta.url))
+
+describe('translateBuildConfig', () => {
+ const cwd = exampleDir
+ const outDir = join(cwd, 'dist')
+ const translate = (...configs: unknown[]) => translateBuildConfig(configs.map((config, index) => ({ name: `config${index}`, config })), { cwd, outDir })
+
+ it('should name entries the way unbuild did', () => {
+ expect(entryName('src/vite', cwd)).toBe('vite')
+ expect(entryName('./src/runtime/server/index.ts', cwd)).toBe('runtime/server/index')
+ expect(entryName(join(cwd, 'src/cli.mts'), cwd)).toBe('cli')
+ expect(entryName('lib/other', cwd)).toBe('lib/other')
+ })
+
+ it('should resolve entry inputs to their source file, without duplicating the module entry', () => {
+ expect(translate({ entries: ['src/utils', { input: './src/utils.ts', name: 'helpers' }] }).entries).toEqual({
+ utils: './src/utils.ts',
+ helpers: './src/utils.ts',
+ })
+ expect(bundledEntries(cwd, translate({ entries: ['src/module'] }))).toEqual({ module: './src/module.ts' })
+ })
+
+ it('should skip a directory entry for `src/runtime` and keep others', () => {
+ const { directories, unsupported } = translate({ entries: [{ input: 'src/runtime/', outDir: 'dist/runtime' }, { input: 'src/shared/', builder: 'mkdist', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }, { input: 'src/other/', outDir: 'lib' }] })
+ expect(directories).toEqual([
+ { srcDir: join(cwd, 'src/shared'), outDir: join(outDir, 'shared'), ext: 'mjs' },
+ { srcDir: join(cwd, 'src/features'), outDir: join(outDir, 'features'), ext: 'js' },
+ ])
+ expect(unsupported).toEqual(['config0: entries[3].outDir'])
+ })
+
+ it('should match string externals by package name', () => {
+ const [pkg, alias] = translate({ externals: ['fake-pkg', '#alias'] }).neverBundle
+ expect(['fake-pkg', 'fake-pkg/sub'].every(id => pkg!.test(id))).toBe(true)
+ expect(pkg!.test('fake-pkg-other')).toBe(false)
+ expect(alias!.test('#alias/config')).toBe(true)
+ })
+
+ it('should merge replacements with earlier configs taking precedence', () => {
+ expect(translate(
+ { replace: { __A__: '"a"' }, rollup: { replace: { delimiters: ['', ''], values: { __B__: '"b"' } } } },
+ { replace: { __A__: '"overridden"', __C__: '"c"' } },
+ ).replace).toEqual({ values: { __A__: '"a"', __B__: '"b"', __C__: '"c"' }, delimiters: ['', ''], preventAssignment: true })
+ expect(translate({ replace: { __A__: '"a"' }, rollup: { replace: false } }).replace).toBeUndefined()
+ expect(translate(
+ { rollup: { replace: { values: { A: 'a' }, preventAssignment: false, objectGuards: true } } },
+ { rollup: { replace: { preventAssignment: true, objectGuards: false } } },
+ ).replace).toEqual({ values: { A: 'a' }, preventAssignment: false, objectGuards: true })
+ })
+
+ it('should accept options without an effect on the output', () => {
+ expect(translate({
+ declaration: 'node16',
+ failOnWarn: false,
+ name: 'my-module',
+ rootDir: '.',
+ outDir: 'dist',
+ clean: true,
+ entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'mjs', addRelativeDeclarationExtensions: true }],
+ rollup: { emitCJS: false, cjsBridge: false, output: { exports: 'named' } },
+ }).unsupported).toEqual([])
+ })
+
+ it('should keep supported hooks, ignore mkdist hooks and reject the rest', () => {
+ const before = () => {}
+ const done = () => {}
+ const { hooks, ignoredHooks, unsupported } = translate({ hooks: { 'build:before': before, 'rollup:done': done, 'mkdist:entry:options': () => {}, 'rollup:options': () => {} } })
+ expect(hooks).toEqual({ 'build:before': [before], 'rollup:done': [done], 'build:done': [] })
+ expect(ignoredHooks).toEqual(['config0: hooks[\'mkdist:entry:options\']'])
+ expect(unsupported).toEqual(['config0: hooks[\'rollup:options\']'])
+ })
+
+ it('should collect every option without an equivalent', () => {
+ expect(translate(
+ { hooks: { 'build:prepare': () => {} }, rollup: { emitCJS: true, output: { format: 'cjs' } }, stubOptions: {} },
+ { externals: [42], replace: { __FN__: () => '' } },
+ ).unsupported).toEqual([
+ 'config0: hooks[\'build:prepare\']',
+ 'config0: rollup.emitCJS: true',
+ 'config0: rollup.output',
+ 'config0: stubOptions',
+ 'config1: externals[0]',
+ 'config1: replace[\'__FN__\']',
+ ])
+ })
+
+ it('should point each unsupported option at its section of the upgrade guide', () => {
+ const message = formatUnsupportedOptions(['build.config.ts: hooks[\'rollup:options\']', 'build.config.ts: rollup.emitCJS: true', 'build.config.ts: rollup.alias', 'build.config.ts: entries[0].esbuild', 'build.config.ts: stubOptions'])
+ expect(message.split('\n')).toEqual([
+ 'The build config uses options that `@nuxt/module-builder` v2 does not support:',
+ ` - build.config.ts: hooks['rollup:options'] (${guide('hooks')})`,
+ ` - build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`,
+ ` - build.config.ts: rollup.alias (${guide('rollup-options')})`,
+ ` - build.config.ts: entries[0].esbuild (${guide('mkdist-options')})`,
+ ` - build.config.ts: stubOptions (${guide('other-options')})`,
+ `Remove each of them from the file named. ${guide('unsupported-build-options')}`,
+ ])
+ })
+
+ it('should warn about a deprecated config file and ignored hooks in CI too', () => {
+ vi.stubEnv('CI', 'true')
+ const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {})
+ try {
+ const config = { ...translate({}), file: 'build.config.ts', importsUnbuild: true, ignoredHooks: ['build.config.ts: hooks[\'mkdist:entry:options\']'] }
+ warnDeprecatedBuildConfig(config)
+ warnDeprecatedBuildConfig({ ...config, importsUnbuild: false, ignoredHooks: [], field: 'unbuild' })
+ expect(warn.mock.calls.map(([message]) => message)).toEqual([
+ expect.stringMatching(new RegExp(`^Ignoring build\\.config\\.ts: hooks\\['mkdist:entry:options'\\]: .*Remove the hook\\. ${guide('hooks')}$`)),
+ expect.stringMatching(new RegExp(`^\`build\\.config\\.ts\` is deprecated\\. .*instead of \`unbuild\`\\. Move them into \`builder\\(\\)\` in \`tsdown\\.config\\.ts\`\\. ${guide('moving-from-buildconfigts')}$`)),
+ `\`build.config.ts\` is deprecated. Its options are still applied. Move them into \`builder()\` in \`tsdown.config.ts\`. ${guide('moving-from-buildconfigts')}`,
+ expect.stringMatching(new RegExp(`^The \`unbuild\` field of \`package\\.json\` is deprecated\\. .*Rename the field to \`build\`\\. ${guide('build-configuration')}$`)),
+ ])
+ }
+ finally {
+ warn.mockRestore()
+ vi.unstubAllEnvs()
+ }
+ })
+})
+
+describe('loadBuildConfig', () => {
+ let dir: string
+
+ beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'module-builder-'))
+ return () => rm(dir, { recursive: true, force: true })
+ })
+
+ it('should load a config file, then `package.json`', async () => {
+ await writeFile(join(dir, 'build.config.mjs'), `export default [{ externals: ['a'] }, false]\n`)
+ const config = await loadBuildConfig(dir, { build: { externals: ['b'] } }, join(dir, 'dist'))
+ expect(config.file).toBe('build.config.mjs')
+ expect(config.importsUnbuild).toBe(false)
+ expect(config.field).toBe('build')
+ expect(config.neverBundle.map(String)).toEqual(['/^a(?:\\/|$)/', '/^b(?:\\/|$)/'])
+ expect(config.unsupported).toEqual([])
+
+ await rm(join(dir, 'build.config.mjs'))
+ await mkdir(join(dir, 'node_modules/unbuild'), { recursive: true })
+ await writeFile(join(dir, 'node_modules/unbuild/package.json'), JSON.stringify({ name: 'unbuild', type: 'module', exports: './index.js' }))
+ await writeFile(join(dir, 'node_modules/unbuild/index.js'), 'export const defineBuildConfig = config => config\n')
+ await writeFile(join(dir, 'build.config.js'), `import { defineBuildConfig } from 'unbuild'\nexport default [defineBuildConfig({ externals: ['a'] }), { entries: ['src/utils'] }]\n`)
+ expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ importsUnbuild: true, field: undefined, unsupported: ['build.config.js: an array of 2 configs'] })
+
+ await rm(join(dir, 'build.config.js'))
+ await writeFile(join(dir, 'build.config.mts'), 'export default () => ({})\n')
+ await expect(loadBuildConfig(dir, {}, join(dir, 'dist'))).rejects.toThrow(`not a function. Replace the function with the object it returns. ${guide('other-options')}`)
+ await rm(join(dir, 'build.config.mts'))
+
+ expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ file: undefined, unsupported: [] })
+ const fromPkg = await loadBuildConfig(dir, { unbuild: { externals: ['u'] }, build: { externals: ['b'] } }, join(dir, 'dist'))
+ expect(fromPkg.neverBundle.map(String)).toEqual(['/^u(?:\\/|$)/'])
+
+ const inferred = (await loadBuildConfig(dir, { name: '@nuxt/image', imports: { '#image/*': './src/*.ts' } }, join(dir, 'dist'))).neverBundle
+ expect(inferred).toHaveLength(1)
+ expect(['@nuxt/image', '@nuxt/image/utils'].every(id => inferred[0]!.test(id))).toBe(true)
+ expect(inferred[0]!.test('@nuxt/image/runtime/providers/ipx')).toBe(false)
+ })
+
+ it('should list the imports of a config file and of the module code that Node cannot resolve', async () => {
+ const root = join(dir, 'extensions')
+ await mkdir(join(root, 'src/lib'), { recursive: true })
+ await writeFile(join(root, 'options.ts'), `export default { externals: ['o'] }\n`)
+ await writeFile(join(root, 'build.config.ts'), `import options from './options'\nexport default options\n`)
+ await writeFile(join(root, 'src/module.ts'), `import { helper } from './helper'\nexport { shared } from './lib'\nexport default helper\n`)
+ await writeFile(join(root, 'src/helper.ts'), `export const helper = 1\n`)
+ await writeFile(join(root, 'src/lib/index.ts'), `import { shared } from '../../options'\nexport { shared }\n`)
+ await expect(loadBuildConfig(root, { build: { entries: ['src/lib/index'] } }, join(root, 'dist'))).rejects.toThrow([
+ 'Module code has to load with Node, which strips types and resolves imports as written:',
+ ' - build.config.ts:1:21: `./options` (use `./options.ts`)',
+ ' - src/lib/index.ts:1:24: `../../options` (use `../../options.ts`)',
+ ' - src/module.ts:1:24: `./helper` (use `./helper.ts`)',
+ ' - src/module.ts:2:24: `./lib` (use `./lib/index.ts`)',
+ `Change each one as suggested. ${guide('module-code-loads-with-node')}`,
+ ].join('\n'))
+ await writeFile(join(root, 'build.config.ts'), `import options from './options.ts'\nexport default options\n`)
+ expect((await loadBuildConfig(root, {}, join(root, 'dist'))).neverBundle.map(String)).toEqual(['/^o(?:\\/|$)/'])
+ })
+})
+
+describe('assertNoLegacyBuildConfig', () => {
+ it('should refuse a `build` or `unbuild` field of `package.json` alongside `builder()`', () => {
+ expect(() => assertNoLegacyBuildConfig(exampleDir, { build: {} })).toThrow(`The \`build\` field of \`package.json\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and remove the field. ${guide('moving-from-buildconfigts')}`)
+ expect(() => assertNoLegacyBuildConfig(exampleDir, { unbuild: {} })).toThrow('The `unbuild` field of `package.json`')
+ expect(() => assertNoLegacyBuildConfig(exampleDir, {})).not.toThrow()
+ })
+})
+
+describe('deprecations in the editor', () => {
+ it('should mark `defineBuildConfig()`', () => {
+ const file = join(repoRoot, 'test/__deprecations__.ts')
+ const source = [
+ `import { defineBuildConfig } from '../src/index.ts'`,
+ `defineBuildConfig({ entries: ['./src/utils'] })`,
+ ].join('\n')
+ const options: ts.CompilerOptions = {
+ allowImportingTsExtensions: true,
+ resolveJsonModule: true,
+ module: ts.ModuleKind.Preserve,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ target: ts.ScriptTarget.ES2024,
+ strict: true,
+ noEmit: true,
+ skipLibCheck: true,
+ }
+ const service = ts.createLanguageService({
+ getScriptFileNames: () => [file],
+ getScriptVersion: () => '1',
+ getScriptSnapshot: name => name === file ? ts.ScriptSnapshot.fromString(source) : ts.sys.fileExists(name) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(name)!) : undefined,
+ getCurrentDirectory: () => repoRoot,
+ getCompilationSettings: () => options,
+ getDefaultLibFileName: ts.getDefaultLibFilePath,
+ fileExists: name => name === file || ts.sys.fileExists(name),
+ readFile: name => name === file ? source : ts.sys.readFile(name),
+ })
+ expect(service.getSemanticDiagnostics(file).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([])
+ const deprecated = service.getSuggestionDiagnostics(file)
+ .filter(diagnostic => diagnostic.reportsDeprecated)
+ .map(diagnostic => ({
+ name: source.slice(diagnostic.start, diagnostic.start! + diagnostic.length!),
+ advice: ts.displayPartsToString(service.getQuickInfoAtPosition(file, diagnostic.start!)?.tags?.find(tag => tag.name === 'deprecated')?.text),
+ }))
+ expect(deprecated).toEqual(Array.from({ length: 2 }, () => ({
+ name: 'defineBuildConfig',
+ advice: expect.stringMatching(/`builder\(\)` from `@nuxt\/module-builder\/tsdown`, in `tsdown\.config\.ts`/),
+ })))
+ })
+})
+
+describe('nuxt-module-build build without a tsdown config', () => {
+ const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] }
+ const dirs: Record