From 5a99ac91867e3b98b9301e7dadbed4c292e3f0e9 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 16 Nov 2026 13:21:38 +0000 Subject: [PATCH] fix(nitro): report the Nitro version a project actually runs --- packages/nuxt-cli/src/commands/info.ts | 4 +- packages/nuxt-cli/src/dev/tui/index.ts | 6 +- packages/nuxt-cli/src/dev/utils.ts | 4 + packages/nuxt-cli/src/utils/banner.ts | 9 +- packages/nuxt-cli/src/utils/catalog.ts | 20 +- packages/nuxt-cli/src/utils/nitro.ts | 111 +++++++- packages/nuxt-cli/src/utils/pkg.ts | 13 + packages/nuxt-cli/src/utils/workspace.ts | 16 ++ .../test/unit/commands/info-run.spec.ts | 10 + packages/nuxt-cli/test/unit/dev-tui.spec.ts | 14 +- .../nuxt-cli/test/unit/dev/lifecycle.spec.ts | 18 ++ .../nuxt-cli/test/unit/utils/banner.spec.ts | 34 +++ .../nuxt-cli/test/unit/utils/nitro.spec.ts | 239 +++++++++++++++++- packages/nuxt-cli/test/unit/utils/pkg.spec.ts | 13 +- 14 files changed, 476 insertions(+), 35 deletions(-) create mode 100644 packages/nuxt-cli/src/utils/workspace.ts diff --git a/packages/nuxt-cli/src/commands/info.ts b/packages/nuxt-cli/src/commands/info.ts index 646c037b6..14df1383f 100644 --- a/packages/nuxt-cli/src/commands/info.ts +++ b/packages/nuxt-cli/src/commands/info.ts @@ -17,7 +17,7 @@ import { getBuilder } from '../utils/banner' import { printJson } from '../utils/console' import { formatInfoBox } from '../utils/formatting' import { logger } from '../utils/logger' -import { resolveNitroVersion } from '../utils/nitro' +import { readNitroMajor, resolveNitroMajor, resolveNitroVersion } from '../utils/nitro' import { getNuxtConfig } from '../utils/nuxt-config' import { readDependencyPackageJson } from '../utils/package-json' import { detectPackageManager, getPackageManagerVersion } from '../utils/package-managers' @@ -95,7 +95,7 @@ export default defineCommand({ const [modules, nuxtVersion = '-', nitroVersion, packageManager] = await Promise.all([ modulesPromise, getDepVersion('nuxt').then(version => version || getDepVersion('nuxt-nightly')), - resolveNitroVersion(cwd, getDepVersion), + resolveNitroVersion(cwd, getDepVersion, resolveNitroMajor(cwd, readNitroMajor(nuxtConfig))), packageManagerPromise, ]) const configKeys = Object.keys(nuxtConfig).sort() diff --git a/packages/nuxt-cli/src/dev/tui/index.ts b/packages/nuxt-cli/src/dev/tui/index.ts index 2f999c38b..4ff1d79f4 100644 --- a/packages/nuxt-cli/src/dev/tui/index.ts +++ b/packages/nuxt-cli/src/dev/tui/index.ts @@ -18,6 +18,7 @@ import { styleText } from 'node:util' import { resolveStackVersions } from '../../utils/banner' import { withDirectStdout } from '../../utils/console' import { formatDuration, terminalLink } from '../../utils/formatting' +import { resolveNitroMajor } from '../../utils/nitro' import { releaseNotesUrl } from '../../utils/release-notes' import { startupElapsedMs } from '../../utils/startup-clock' @@ -733,7 +734,10 @@ function describeSession( updateLink?: string, ): InfoSection[] { // Until Nuxt has loaded, the installed packages are all there is to go on. - const versions = resolveStackVersions(cwd, { builder: stack?.builder as NuxtOptions['builder'] | undefined }) + const versions = resolveStackVersions(cwd, { + builder: stack?.builder as NuxtOptions['builder'] | undefined, + nitroMajor: resolveNitroMajor(cwd, stack?.nitroMajor), + }) const { listener } = context const server = stack?.server ?? 'nitro' const serverName = SERVER_BUILDER_NAMES[server] ?? server diff --git a/packages/nuxt-cli/src/dev/utils.ts b/packages/nuxt-cli/src/dev/utils.ts index 3c1c1c68d..79271f4a3 100644 --- a/packages/nuxt-cli/src/dev/utils.ts +++ b/packages/nuxt-cli/src/dev/utils.ts @@ -35,6 +35,7 @@ import { clearBuildDir } from '../utils/fs' import { loadKit } from '../utils/kit' import { acquireLock, formatLockError, getTakeoverPid, updateLock } from '../utils/lockfile' import { debug, logger, writeNotice } from '../utils/logger' +import { readNitroMajor } from '../utils/nitro' import { loadNuxtManifest, resolveNuxtManifest, writeNuxtManifest } from '../utils/nuxt' import { getServerBuilderId, resolveServerBuild } from '../utils/server-build' import { createConfigWatcher, FileChangeTracker, getLocalLayerDirs } from './config-watcher' @@ -188,6 +189,8 @@ export interface DevStack { builder?: string /** The server builder's short name, e.g. `nitro` or `vite`, when Nuxt has one. */ server?: string + /** The Nitro major Nuxt resolved, when the installed Nuxt has `_nitroMajor`. */ + nitroMajor?: 2 | 3 } /** A page or server route the app defines, as listed in the dev UI. */ @@ -902,6 +905,7 @@ export class NuxtDevServer extends EventEmitter { this.emit('stack', { builder: typeof builder === 'string' ? builder : undefined, server: getServerBuilderId(nuxt), + nitroMajor: readNitroMajor(nuxt.options), }) } diff --git a/packages/nuxt-cli/src/utils/banner.ts b/packages/nuxt-cli/src/utils/banner.ts index 8613dfc40..49ab4a261 100644 --- a/packages/nuxt-cli/src/utils/banner.ts +++ b/packages/nuxt-cli/src/utils/banner.ts @@ -3,7 +3,7 @@ import type { Nuxt, NuxtBuilder, NuxtConfig, NuxtOptions } from '@nuxt/schema' import { styleText } from 'node:util' import { logger } from './logger' -import { getNitroVersion } from './nitro' +import { getNitroVersion, readNitroMajor } from './nitro' import { getNuxtPkgVersion, getPkgJSON, getPkgVersion } from './pkg' import { getServerBuilderName } from './server-build' @@ -34,6 +34,7 @@ export function showBanner(nuxt: Nuxt) { logger.info(describeStack(nuxt.options.rootDir, { nuxtVersion: nuxt._version, builder: nuxt.options.builder, + nitroMajor: readNitroMajor(nuxt.options), // Nitro is installed with Nuxt whether or not it builds the server. withNitro: getServerBuilderName(nuxt) === 'Nitro', })) @@ -47,17 +48,17 @@ export interface StackVersions { } /** The versions of the framework packages in use, for the banner and the dev UI. */ -export function resolveStackVersions(cwd: string, options: { nuxtVersion?: string, builder?: NuxtOptions['builder'] | NuxtConfig['builder'] } = {}): StackVersions { +export function resolveStackVersions(cwd: string, options: { nuxtVersion?: string, builder?: NuxtOptions['builder'] | NuxtConfig['builder'], nitroMajor?: 2 | 3 } = {}): StackVersions { return { nuxt: options.nuxtVersion || getNuxtPkgVersion(cwd), - nitro: getNitroVersion(cwd), + nitro: getNitroVersion(cwd, options.nitroMajor), builder: getBuilder(cwd, options.builder as Exclude), vue: getPkgVersion(cwd, 'vue', { via: ['nuxt'] }) || null, } } /** The `Nuxt x (with Nitro y, Vite z and Vue w)` line shown at startup. */ -function describeStack(cwd: string, options: { nuxtVersion?: string, builder?: NuxtOptions['builder'] | NuxtConfig['builder'], withNitro?: boolean } = {}): string { +function describeStack(cwd: string, options: { nuxtVersion?: string, builder?: NuxtOptions['builder'] | NuxtConfig['builder'], nitroMajor?: 2 | 3, withNitro?: boolean } = {}): string { const { nuxt: nuxtVersion, nitro, builder, vue: vueVersion } = resolveStackVersions(cwd, options) const nitroVersion = options.withNitro === false ? undefined : nitro diff --git a/packages/nuxt-cli/src/utils/catalog.ts b/packages/nuxt-cli/src/utils/catalog.ts index c6c7a8f1e..d1c0e3c01 100644 --- a/packages/nuxt-cli/src/utils/catalog.ts +++ b/packages/nuxt-cli/src/utils/catalog.ts @@ -1,9 +1,12 @@ import type { PackageJson } from 'pkg-types' -import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { readFileSync, writeFileSync } from 'node:fs' import { parseYAML } from 'confbox/yaml' -import { dirname, join, resolve } from 'pathe' + +import { findPnpmWorkspaceYaml } from './workspace' + +export { findPnpmWorkspaceYaml } const CATALOG_SPECIFIER_RE = /^catalog:(.*)$/ @@ -30,19 +33,6 @@ export function parseCatalogSpecifier(specifier: string | undefined): string | u return match[1] || DEFAULT_CATALOG } -/** Nearest `pnpm-workspace.yaml` at or above `cwd`. */ -export function findPnpmWorkspaceYaml(cwd: string): string | undefined { - for (let dir = resolve(cwd); ; dir = dirname(dir)) { - const filePath = join(dir, 'pnpm-workspace.yaml') - if (existsSync(filePath)) { - return filePath - } - if (dir === dirname(dir)) { - return undefined - } - } -} - const configCache = new Map() /** Discard memoised catalog configuration, so a later read sees changes on disk. */ diff --git a/packages/nuxt-cli/src/utils/nitro.ts b/packages/nuxt-cli/src/utils/nitro.ts index 6b5c6d0ce..40e7dea75 100644 --- a/packages/nuxt-cli/src/utils/nitro.ts +++ b/packages/nuxt-cli/src/utils/nitro.ts @@ -1,7 +1,11 @@ import type { PackageJson } from 'pkg-types' +import { dirname } from 'node:path' + +import { coerce, compare } from 'verkit' import { NUXT_PACKAGES } from './nuxt-packages' -import { getPkgJSON, getPkgVersion } from './pkg' +import { getNuxtPkgVersion, getPkgJSON, getPkgVersion, getProjectPkgJSON } from './pkg' +import { findPnpmWorkspaceYaml } from './workspace' /** * Names Nitro is installed under, newest naming first, so a manifest that @@ -20,6 +24,12 @@ const NITRO_PKGS = ['nitro', 'nitropack'] */ const NITRO_SERVER_PKG = '@nuxt/nitro-server' +/** The Nitro package that provides each Nitro major. */ +const NITRO_MAJOR_PKGS: Record<2 | 3, string> = { 2: 'nitropack', 3: 'nitro' } + +/** The first Nuxt minor to resolve `_nitroMajor`. */ +const NITRO_MAJOR_NUXT_VERSION = '4.7.0' + interface NitroCandidate { /** The name Nitro is installed under. */ name: string @@ -28,18 +38,97 @@ interface NitroCandidate { } /** - * The Nitro packages to look for, the one the installed Nuxt depends on first. + * The Nitro packages to look for. * - * The plain names are kept as later candidates so Nitro is still found when no + * Without a `nitroMajor`, the package the installed Nuxt depends on comes first, + * with the plain names kept as later candidates so Nitro is still found when no * owning manifest can be read (`exports` withholding `package.json`, or Nitro * installed without Nuxt). */ -function getNitroCandidates(cwd: string): NitroCandidate[] { - const candidates: NitroCandidate[] = NITRO_PKGS.map(name => ({ name })) +function getNitroCandidates(cwd: string, nitroMajor?: 2 | 3): NitroCandidate[] { const declared = getNuxtNitroDependency(cwd) + if (nitroMajor) { + const name = NITRO_MAJOR_PKGS[nitroMajor] + const chain = declared?.name === name ? [declared] : [] + const plain: NitroCandidate[] = [{ name }] + // The project's own copy wins when it declares the package, but a hoisted + // unrelated copy must not shadow the one Nuxt declares. + return manifestDeclaresPkg(getProjectPkgJSON(cwd), name) + ? [...plain, ...chain] + : [...chain, ...plain] + } + const candidates: NitroCandidate[] = NITRO_PKGS.map(name => ({ name })) return declared ? [declared, ...candidates] : candidates } +/** Whether a manifest declares `name` in its dependencies or devDependencies. */ +function manifestDeclaresPkg(pkg: PackageJson | null, name: string): boolean { + const { dependencies, devDependencies } = pkg ?? {} + return name in (dependencies ?? {}) || name in (devDependencies ?? {}) +} + +/** + * The Nitro major selected by the project: the project's own dependencies + * first (`nitro` winning when both are listed), then the workspace root when + * it declares exactly one, or `undefined` when neither does. + */ +export function getProjectNitroMajor(cwd: string): 2 | 3 | undefined { + const major = getNitroMajorFromManifest(getProjectPkgJSON(cwd)) + if (major) { + return major + } + + const workspaceYaml = findPnpmWorkspaceYaml(cwd) + const workspaceDir = workspaceYaml && dirname(workspaceYaml) + if (!workspaceDir || workspaceDir === cwd) { + return undefined + } + + const { dependencies, devDependencies } = getProjectPkgJSON(workspaceDir) ?? {} + const deps = { ...dependencies, ...devDependencies } + const hasNitro = 'nitro' in deps + const hasNitropack = 'nitropack' in deps + if (hasNitro === hasNitropack) { + return undefined + } + return hasNitro ? 3 : 2 +} + +/** The Nitro major a manifest's `dependencies` and `devDependencies` select. */ +function getNitroMajorFromManifest(pkg: PackageJson | null): 2 | 3 | undefined { + const { dependencies, devDependencies } = pkg ?? {} + const deps = { ...dependencies, ...devDependencies } + if ('nitro' in deps) { + return 3 + } + if ('nitropack' in deps) { + return 2 + } +} + +/** An internal `_nitroMajor` option, allowing only the values Nuxt resolves. */ +export function readNitroMajor(config: unknown): 2 | 3 | undefined { + const { _nitroMajor } = (config ?? {}) as { _nitroMajor?: unknown } + return _nitroMajor === 2 || _nitroMajor === 3 ? _nitroMajor : undefined +} + +/** Whether the installed Nuxt resolves the `_nitroMajor` option. */ +export function supportsNitroMajor(cwd: string): boolean { + const version = coerce(getNuxtPkgVersion(cwd)) + return !!version && compare(version, NITRO_MAJOR_NUXT_VERSION) >= 0 +} + +/** + * The Nitro major to report, from an explicit value or the project's selection + * once the installed Nuxt resolves the `_nitroMajor` option. + */ +export function resolveNitroMajor(cwd: string, fromNuxt?: 2 | 3): 2 | 3 | undefined { + if (fromNuxt !== undefined) { + return fromNuxt + } + return supportsNitroMajor(cwd) ? getProjectNitroMajor(cwd) : undefined +} + /** * The Nitro package the installed Nuxt depends on, directly or through * `@nuxt/nitro-server`, or `undefined` when no owning manifest can be read. @@ -82,9 +171,12 @@ function getInstalledVersion(cwd: string, candidates: NitroCandidate[]): string return '' } -/** The version of Nitro the installed Nuxt depends on. */ -export function getNitroVersion(cwd: string): string { - return getInstalledVersion(cwd, getNitroCandidates(cwd)) +/** + * The version of Nitro the installed Nuxt depends on, or of the package + * providing `nitroMajor` when it is given. + */ +export function getNitroVersion(cwd: string, nitroMajor?: 2 | 3): string { + return getInstalledVersion(cwd, getNitroCandidates(cwd, nitroMajor)) } /** @@ -95,8 +187,9 @@ export function getNitroVersion(cwd: string): string { export async function resolveNitroVersion( cwd: string, getDepVersion: (name: string) => Promise, + nitroMajor?: 2 | 3, ): Promise { - const candidates = getNitroCandidates(cwd) + const candidates = getNitroCandidates(cwd, nitroMajor) const version = getInstalledVersion(cwd, candidates) if (version) { return version diff --git a/packages/nuxt-cli/src/utils/pkg.ts b/packages/nuxt-cli/src/utils/pkg.ts index fb1895110..c86f40579 100644 --- a/packages/nuxt-cli/src/utils/pkg.ts +++ b/packages/nuxt-cli/src/utils/pkg.ts @@ -1,4 +1,7 @@ +import type { PackageJson } from 'pkg-types' import { readFileSync } from 'node:fs' + +import { resolve } from 'node:path' import { resolveModulePath } from 'exsolve' import { NUXT_PACKAGES } from './nuxt-packages' @@ -66,6 +69,16 @@ export function getPkgJSON(cwd: string, pkg: string, options?: PkgJSONOptions) { return null } +/** The project's own `package.json` in `cwd`. */ +export function getProjectPkgJSON(cwd: string): PackageJson | null { + try { + return JSON.parse(readFileSync(resolve(cwd, 'package.json'), 'utf-8')) + } + catch { + return null + } +} + /** The installed Nuxt version in `cwd`. */ export function getNuxtPkgVersion(cwd: string): string { for (const name of NUXT_PACKAGES) { diff --git a/packages/nuxt-cli/src/utils/workspace.ts b/packages/nuxt-cli/src/utils/workspace.ts new file mode 100644 index 000000000..d75a803a3 --- /dev/null +++ b/packages/nuxt-cli/src/utils/workspace.ts @@ -0,0 +1,16 @@ +import { existsSync } from 'node:fs' + +import { dirname, join, resolve } from 'pathe' + +/** Nearest `pnpm-workspace.yaml` at or above `cwd`. */ +export function findPnpmWorkspaceYaml(cwd: string): string | undefined { + for (let dir = resolve(cwd); ; dir = dirname(dir)) { + const filePath = join(dir, 'pnpm-workspace.yaml') + if (existsSync(filePath)) { + return filePath + } + if (dir === dirname(dir)) { + return undefined + } + } +} diff --git a/packages/nuxt-cli/test/unit/commands/info-run.spec.ts b/packages/nuxt-cli/test/unit/commands/info-run.spec.ts index f3bb13df8..826d925f7 100644 --- a/packages/nuxt-cli/test/unit/commands/info-run.spec.ts +++ b/packages/nuxt-cli/test/unit/commands/info-run.spec.ts @@ -106,6 +106,16 @@ describe('info command', () => { expect(payload.nitroVersion).toMatch(/^\d/) }) + it('should honour an explicit `_nitroMajor` in `nuxt.config`', async () => { + await writeFile(join(cwd, 'package.json'), JSON.stringify({ name: 'app', private: true, dependencies: { nitro: '3.0.0', nitropack: '2.13.6' } })) + await writeFile(join(cwd, 'nuxt.config.mjs'), `export default { _nitroMajor: 2 }`) + + const payload = await runInfoJSON() + + expect(payload.serverBuilder).toBe('nitro@2.13.6') + expect(payload.nitroVersion).toBe('2.13.6') + }) + it.each(['@nuxt/vite-server', 'vite'])('should name the Vite server builder from `%s` without a version', async (builder) => { await writeFile(join(cwd, 'package.json'), JSON.stringify({ name: 'app', private: true, dependencies: { '@nuxt/vite-server': '4.6.4' } })) await writeFile(join(cwd, 'nuxt.config.mjs'), `export default { server: { builder: '${builder}' } }`) diff --git a/packages/nuxt-cli/test/unit/dev-tui.spec.ts b/packages/nuxt-cli/test/unit/dev-tui.spec.ts index e28d89ca1..22da1e7d3 100644 --- a/packages/nuxt-cli/test/unit/dev-tui.spec.ts +++ b/packages/nuxt-cli/test/unit/dev-tui.spec.ts @@ -37,7 +37,11 @@ vi.mock('../../src/dev/listen', async importOriginal => ({ })) // The info view resolves versions from what is installed; pinned so it lists Nitro. -vi.mock('../../src/utils/nitro', () => ({ getNitroVersion: () => '2.13.5' })) +vi.mock('../../src/utils/nitro', () => ({ + getNitroVersion: (_cwd: string, nitroMajor?: 2 | 3) => nitroMajor === 3 ? '3.0.0' : '2.13.5', + resolveNitroMajor: (_cwd: string, fromNuxt?: 2 | 3) => fromNuxt, + readNitroMajor: () => undefined, +})) const copied: string[] = [] vi.mock('tinyclip', () => ({ @@ -3030,6 +3034,14 @@ describe('panel info view', () => { expect(frame).not.toContain('Nitro') }) }) + + it('uses the stack nitro major when resolving the Nitro version', async () => { + await withPanel(async (ui, settle) => { + ui.setStack({ builder: 'vite', server: 'nitro', nitroMajor: 3 }) + process.stdin.emit('keypress', 'i', { name: 'i', sequence: 'i' }) + expect(await settle()).toMatch(/Server builder\s+Nitro 3\.0\.0/) + }) + }) }) describe('panel shortcut routing', () => { diff --git a/packages/nuxt-cli/test/unit/dev/lifecycle.spec.ts b/packages/nuxt-cli/test/unit/dev/lifecycle.spec.ts index 5e658c34a..1f7a95f26 100644 --- a/packages/nuxt-cli/test/unit/dev/lifecycle.spec.ts +++ b/packages/nuxt-cli/test/unit/dev/lifecycle.spec.ts @@ -294,6 +294,24 @@ describe('dev server stack', () => { { builder: 'vite', server: 'nitro' }, ]) }) + + it('should report the nitro major Nuxt resolved', async () => { + const nuxt = createNuxt({ builder: 'vite', _nitroMajor: 3, server: { builder: { bundle: () => {} } } }) as FakeNuxt & { serverBuild?: unknown } + loadNuxt.mockImplementation(() => Promise.resolve(nuxt)) + buildNuxt.mockImplementation(async () => { + nuxt.serverBuild = { name: 'nitro', label: 'Nitro', capabilities: { server: true, dev: true } } + }) + const server = createServer({ captureUIEvents: true }) + const seen: unknown[] = [] + server.on('stack', stack => seen.push(stack)) + + await server.init() + + expect(seen).toEqual([ + { builder: 'vite', server: 'custom', nitroMajor: 3 }, + { builder: 'vite', server: 'nitro', nitroMajor: 3 }, + ]) + }) }) describe('dev server failures', () => { diff --git a/packages/nuxt-cli/test/unit/utils/banner.spec.ts b/packages/nuxt-cli/test/unit/utils/banner.spec.ts index 08d70b03a..f48068ac4 100644 --- a/packages/nuxt-cli/test/unit/utils/banner.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/banner.spec.ts @@ -26,13 +26,16 @@ const CWD_VERSIONS: Record> = { const NUXT_WITH_NITROPACK = { name: 'nuxt', version: '4.4.6', dependencies: { nitropack: '^2.13.4' } } const NUXT_WITH_NITRO_SERVER = { name: 'nuxt', version: '5.0.0', dependencies: { '@nuxt/nitro-server': '^5.0.0' } } +const NUXT_WITH_NITROPACK_SERVER = { name: 'nuxt', version: '4.7.0', dependencies: { '@nuxt/nitro-server': '^4.7.0' } } const NITRO_SERVER = { name: '@nuxt/nitro-server', version: '5.0.0', dependencies: { nitro: '^3.0.0' } } +const NITROPACK_SERVER = { name: '@nuxt/nitro-server', version: '4.7.0', dependencies: { nitropack: '^2.13.6' } } const MANIFESTS: Record> = { '/any': { nuxt: NUXT_WITH_NITROPACK }, '/missing': { nuxt: NUXT_WITH_NITROPACK }, '/vite-plus': { nuxt: NUXT_WITH_NITROPACK }, '/nitro-v3': { 'nuxt': NUXT_WITH_NITRO_SERVER, '@nuxt/nitro-server': NITRO_SERVER }, + '/nitro-v3-major': { 'nuxt': NUXT_WITH_NITROPACK_SERVER, '@nuxt/nitro-server': NITROPACK_SERVER }, '/direct-server': { 'nuxt': NUXT_WITH_NITROPACK, '@nuxt/nitro-server': NITRO_SERVER }, '/no-owner': {}, '/no-nitro': {}, @@ -61,6 +64,7 @@ vi.mock('../../../src/utils/pkg', () => ({ } return CWD_VERSIONS[cwd]?.[pkg] ?? VERSIONS[pkg] ?? '' }), + getProjectPkgJSON: vi.fn(() => null), })) const { getBuilder, showBanner } = await import('../../../src/utils/banner') @@ -112,6 +116,36 @@ describe('showBanner', () => { `) }) + it('should follow nuxt\'s internal nitro major over its declared nitropack', async () => { + const renderer = await render(() => + showBanner({ _version: '4.7.0', options: { rootDir: '/nitro-v3-major', builder: 'vite', _nitroMajor: 3 } } as unknown as Nuxt)) + + expect(screen(renderer)).toMatchInlineSnapshot(` + "│ + ● Nuxt 4.7.0 (with Nitro 3.0.0, Vite 7.3.1 and Vue 3.5.39)" + `) + }) + + it('should follow nuxt\'s internal nitro major 2 over its declared nitro', async () => { + const renderer = await render(() => + showBanner({ _version: '5.0.0', options: { rootDir: '/nitro-v3', builder: 'vite', _nitroMajor: 2 } } as unknown as Nuxt)) + + expect(screen(renderer)).toMatchInlineSnapshot(` + "│ + ● Nuxt 5.0.0 (with Nitro 2.13.4, Vite 7.3.1 and Vue 3.5.39)" + `) + }) + + it('should keep the nuxt-declared nitropack when the nitro major is missing or invalid', async () => { + const renderer = await render(() => + showBanner({ _version: '4.7.0', options: { rootDir: '/nitro-v3-major', builder: 'vite', _nitroMajor: 4 } } as unknown as Nuxt)) + + expect(screen(renderer)).toMatchInlineSnapshot(` + "│ + ● Nuxt 4.7.0 (with Nitro 2.13.4, Vite 7.3.1 and Vue 3.5.39)" + `) + }) + it('should follow nuxt\'s declared nitropack over a directly installed @nuxt/nitro-server', async () => { const renderer = await render(() => showBanner({ _version: '4.4.6', options: { rootDir: '/direct-server', builder: 'vite' } } as unknown as Nuxt)) diff --git a/packages/nuxt-cli/test/unit/utils/nitro.spec.ts b/packages/nuxt-cli/test/unit/utils/nitro.spec.ts index 861f57dca..20dbacb6f 100644 --- a/packages/nuxt-cli/test/unit/utils/nitro.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/nitro.spec.ts @@ -2,12 +2,19 @@ import type { PackageJson } from 'pkg-types' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getNitroVersion, resolveNitroVersion } from '../../../src/utils/nitro' -import { getPkgJSON, getPkgVersion } from '../../../src/utils/pkg' +import { getNitroVersion, getProjectNitroMajor, readNitroMajor, resolveNitroMajor, resolveNitroVersion, supportsNitroMajor } from '../../../src/utils/nitro' +import { getNuxtPkgVersion, getPkgJSON, getPkgVersion, getProjectPkgJSON } from '../../../src/utils/pkg' +import { findPnpmWorkspaceYaml } from '../../../src/utils/workspace' + +vi.mock('../../../src/utils/workspace', () => ({ + findPnpmWorkspaceYaml: vi.fn(), +})) vi.mock('../../../src/utils/pkg', () => ({ + getNuxtPkgVersion: vi.fn(), getPkgJSON: vi.fn(), getPkgVersion: vi.fn(), + getProjectPkgJSON: vi.fn(), })) /** Describe the packages installed in the project by name. */ @@ -16,9 +23,144 @@ function installed(pkgs: Record) { vi.mocked(getPkgVersion).mockImplementation((_cwd, pkg) => pkgs[pkg]?.version ?? '') } +/** Describe the project's own `package.json`. */ +function project(pkg: PackageJson) { + vi.mocked(getProjectPkgJSON).mockReturnValue(pkg) +} + +/** Describe the `package.json` read at each directory. */ +function manifests(byDir: Record) { + vi.mocked(getProjectPkgJSON).mockImplementation(dir => byDir[dir] ?? null) +} + +/** Describe a workspace root at `/workspace` whose project declares nothing. */ +function workspaceRoot(pkg: PackageJson) { + vi.mocked(findPnpmWorkspaceYaml).mockReturnValue('/workspace/pnpm-workspace.yaml') + manifests({ + '/project': {}, + '/workspace': pkg, + }) +} + beforeEach(() => { + vi.mocked(findPnpmWorkspaceYaml).mockReset() + vi.mocked(getNuxtPkgVersion).mockReset() vi.mocked(getPkgJSON).mockReset() vi.mocked(getPkgVersion).mockReset() + vi.mocked(getProjectPkgJSON).mockReset() +}) + +describe('getProjectNitroMajor', () => { + it('should select 3 for nitro and 2 for nitropack', () => { + project({ dependencies: { nitro: '^3.0.0' } }) + expect(getProjectNitroMajor('/project')).toBe(3) + + project({ dependencies: { nitropack: '^2.13.4' } }) + expect(getProjectNitroMajor('/project')).toBe(2) + }) + + it('should prefer nitro when both are declared', () => { + project({ dependencies: { nitro: '^3.0.0', nitropack: '^2.13.4' } }) + expect(getProjectNitroMajor('/project')).toBe(3) + }) + + it('should read devDependencies too', () => { + project({ devDependencies: { nitropack: '^2.13.4' } }) + expect(getProjectNitroMajor('/project')).toBe(2) + }) + + it('should return undefined when neither is declared', () => { + project({}) + expect(getProjectNitroMajor('/project')).toBeUndefined() + }) + + it('should follow the workspace root when it declares exactly one package', () => { + workspaceRoot({ dependencies: { nitro: '^3.0.0' } }) + expect(getProjectNitroMajor('/project')).toBe(3) + + workspaceRoot({ devDependencies: { nitropack: '^2.13.4' } }) + expect(getProjectNitroMajor('/project')).toBe(2) + }) + + it('should ignore a workspace root that declares both packages', () => { + workspaceRoot({ dependencies: { nitro: '^3.0.0', nitropack: '^2.13.4' } }) + expect(getProjectNitroMajor('/project')).toBeUndefined() + }) + + it('should prefer the project manifest over the workspace root', () => { + vi.mocked(findPnpmWorkspaceYaml).mockReturnValue('/workspace/pnpm-workspace.yaml') + manifests({ + '/project': { dependencies: { nitropack: '^2.13.4' } }, + '/workspace': { dependencies: { nitro: '^3.0.0' } }, + }) + + expect(getProjectNitroMajor('/project')).toBe(2) + }) + + it('should ignore a workspace root that is the project itself', () => { + vi.mocked(findPnpmWorkspaceYaml).mockReturnValue('/project/pnpm-workspace.yaml') + project({}) + + expect(getProjectNitroMajor('/project')).toBeUndefined() + }) +}) + +describe('readNitroMajor', () => { + it('should read 2 and 3 only', () => { + expect(readNitroMajor({ _nitroMajor: 2 })).toBe(2) + expect(readNitroMajor({ _nitroMajor: 3 })).toBe(3) + }) + + it('should ignore a missing or other value', () => { + expect(readNitroMajor({})).toBeUndefined() + expect(readNitroMajor(null)).toBeUndefined() + expect(readNitroMajor({ _nitroMajor: 4 })).toBeUndefined() + }) +}) + +describe('supportsNitroMajor', () => { + it('should be true from 4.7.0 and false before it', () => { + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.7.0') + expect(supportsNitroMajor('/project')).toBe(true) + + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.6.2') + expect(supportsNitroMajor('/project')).toBe(false) + }) + + it('should ignore a prerelease or nightly suffix', () => { + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.7.0-2611.abc') + expect(supportsNitroMajor('/project')).toBe(true) + + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.6.2-2611.abc') + expect(supportsNitroMajor('/project')).toBe(false) + }) +}) + +describe('resolveNitroMajor', () => { + it('should use the major passed from Nuxt', () => { + expect(resolveNitroMajor('/project', 3)).toBe(3) + }) + + it('should derive on a supported Nuxt when no major is passed', () => { + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.7.0') + project({ dependencies: { nitro: '^3.0.0' } }) + + expect(resolveNitroMajor('/project')).toBe(3) + }) + + it('should ignore project declarations on an older Nuxt', () => { + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.6.2') + project({ dependencies: { nitro: '^3.0.0' } }) + + expect(resolveNitroMajor('/project')).toBeUndefined() + }) + + it('should ignore the workspace root on an older Nuxt', () => { + vi.mocked(getNuxtPkgVersion).mockReturnValue('4.6.2') + workspaceRoot({ dependencies: { nitro: '^3.0.0' } }) + + expect(resolveNitroMajor('/project')).toBeUndefined() + }) }) describe('getNitroVersion', () => { @@ -103,6 +245,72 @@ describe('getNitroVersion', () => { expect(getNitroVersion('/project')).toBe('') }) + + it('should report the matching package over the one nuxt depends on', () => { + installed({ + 'nuxt': { dependencies: { '@nuxt/nitro-server': '^5.0.0' } }, + '@nuxt/nitro-server': { dependencies: { nitropack: '^2.13.4' } }, + 'nitro': { version: '3.0.0' }, + 'nitropack': { version: '2.13.4' }, + }) + + expect(getNitroVersion('/project', 3)).toBe('3.0.0') + }) + + it('should select nitropack for major 2 even when nuxt declares nitro', () => { + installed({ + 'nuxt': { dependencies: { '@nuxt/nitro-server': '^5.0.0' } }, + '@nuxt/nitro-server': { dependencies: { nitro: '^3.0.0' } }, + 'nitro': { version: '3.0.0' }, + 'nitropack': { version: '2.13.4' }, + }) + + expect(getNitroVersion('/project', 2)).toBe('2.13.4') + }) + + it('should fall back to nuxt\'s declared chain when the matching package is not directly installed', () => { + installed({ + 'nuxt': { dependencies: { '@nuxt/nitro-server': '^5.0.0' } }, + '@nuxt/nitro-server': { dependencies: { nitro: '^3.0.0' } }, + }) + project({ dependencies: { nitro: '^3.0.0' } }) + vi.mocked(getPkgVersion).mockImplementation((_cwd, pkg, options) => pkg === 'nitro' && options?.via ? '3.0.0' : '') + + expect(getNitroVersion('/project', 3)).toBe('3.0.0') + }) + + it('should prefer the project copy of the matching package', () => { + installed({ + nuxt: { dependencies: { nitro: '^3.0.0' } }, + nitro: { version: '3.0.0' }, + }) + project({ dependencies: { nitro: '^3.0.0' } }) + vi.mocked(getPkgVersion).mockImplementation((_cwd, _pkg, options) => options?.via ? '3.5.0' : '4.0.0') + + expect(getNitroVersion('/project', 3)).toBe('4.0.0') + }) + + it('should prefer the nuxt-declared chain when the project does not declare the package', () => { + installed({ + nuxt: { dependencies: { nitropack: '^2.13.4' } }, + nitropack: { version: '2.13.4' }, + }) + project({}) + vi.mocked(getPkgVersion).mockImplementation((_cwd, _pkg, options) => options?.via ? '2.13.4' : '9.9.9') + + expect(getNitroVersion('/project', 2)).toBe('2.13.4') + }) + + it('should keep today\'s lookup when no major is given', () => { + installed({ + nuxt: { dependencies: { nitropack: '^2.13.4' } }, + nitro: { version: '3.0.0' }, + nitropack: { version: '2.13.4' }, + }) + project({ dependencies: { nitro: '^3.0.0' } }) + + expect(getNitroVersion('/project')).toBe('2.13.4') + }) }) describe('resolveNitroVersion', () => { @@ -132,4 +340,31 @@ describe('resolveNitroVersion', () => { await expect(resolveNitroVersion('/project', async () => undefined)).resolves.toBeUndefined() }) + + it('should respect the nitro major selected by the project', async () => { + installed({ + 'nuxt': { dependencies: { '@nuxt/nitro-server': '^5.0.0' } }, + '@nuxt/nitro-server': { dependencies: { nitropack: '^2.13.4' } }, + 'nitro': { version: '3.0.0' }, + 'nitropack': { version: '2.13.4' }, + }) + project({ dependencies: { nitro: '^3.0.0' } }) + + await expect(resolveNitroVersion( + '/project', + async name => ({ nitro: '^3.0.0', nitropack: '^2.13.4' }[name]), + getProjectNitroMajor('/project'), + )).resolves.toBe('3.0.0') + }) + + it('should fall back to the declared version of the selected major', async () => { + installed({ nuxt: { dependencies: { nitro: '^3.0.0' } } }) + project({ dependencies: { nitropack: '^2.13.4' } }) + + await expect(resolveNitroVersion( + '/project', + async name => ({ nitro: '^3.0.0', nitropack: '^2.13.4' }[name]), + getProjectNitroMajor('/project'), + )).resolves.toBe('^2.13.4') + }) }) diff --git a/packages/nuxt-cli/test/unit/utils/pkg.spec.ts b/packages/nuxt-cli/test/unit/utils/pkg.spec.ts index 071b7c8ba..d53e9c894 100644 --- a/packages/nuxt-cli/test/unit/utils/pkg.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/pkg.spec.ts @@ -1,8 +1,9 @@ import { fileURLToPath } from 'node:url' +import { join } from 'pathe' import { describe, expect, it } from 'vitest' -import { getPkgJSON } from '../../../src/utils/pkg' +import { getPkgJSON, getProjectPkgJSON } from '../../../src/utils/pkg' /** This package's own directory, where its dependencies resolve from. */ const packageDir = fileURLToPath(new URL('../../../', import.meta.url)) @@ -28,3 +29,13 @@ describe('getPkgJSON', () => { expect(getPkgJSON(packageDir, 'nuxt', { strict: true })?.name).toBe('nuxt') }) }) + +describe('getProjectPkgJSON', () => { + it('should read the project manifest in cwd', () => { + expect(getProjectPkgJSON(packageDir)?.name).toBe('@nuxt/cli') + }) + + it('should return null when cwd has no package.json', () => { + expect(getProjectPkgJSON(join(packageDir, 'missing'))).toBeNull() + }) +})