Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/nuxt-cli/src/commands/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 5 additions & 1 deletion packages/nuxt-cli/src/dev/tui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions packages/nuxt-cli/src/dev/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -902,6 +905,7 @@ export class NuxtDevServer extends EventEmitter<DevServerEventMap> {
this.emit('stack', {
builder: typeof builder === 'string' ? builder : undefined,
server: getServerBuilderId(nuxt),
nitroMajor: readNitroMajor(nuxt.options),
})
}

Expand Down
9 changes: 5 additions & 4 deletions packages/nuxt-cli/src/utils/banner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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',
}))
Expand All @@ -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<NuxtOptions['builder'], NuxtBuilder>),
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

Expand Down
20 changes: 5 additions & 15 deletions packages/nuxt-cli/src/utils/catalog.ts
Original file line number Diff line number Diff line change
@@ -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:(.*)$/

Expand All @@ -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<string, Catalogs | undefined>()

/** Discard memoised catalog configuration, so a later read sees changes on disk. */
Expand Down
111 changes: 102 additions & 9 deletions packages/nuxt-cli/src/utils/nitro.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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))
}

/**
Expand All @@ -95,8 +187,9 @@ export function getNitroVersion(cwd: string): string {
export async function resolveNitroVersion(
cwd: string,
getDepVersion: (name: string) => Promise<string | undefined>,
nitroMajor?: 2 | 3,
): Promise<string | undefined> {
const candidates = getNitroCandidates(cwd)
const candidates = getNitroCandidates(cwd, nitroMajor)
const version = getInstalledVersion(cwd, candidates)
if (version) {
return version
Expand Down
13 changes: 13 additions & 0 deletions packages/nuxt-cli/src/utils/pkg.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions packages/nuxt-cli/src/utils/workspace.ts
Original file line number Diff line number Diff line change
@@ -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
}
}
}
10 changes: 10 additions & 0 deletions packages/nuxt-cli/test/unit/commands/info-run.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}' } }`)
Expand Down
14 changes: 13 additions & 1 deletion packages/nuxt-cli/test/unit/dev-tui.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => ({
Expand Down Expand Up @@ -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', () => {
Expand Down
Loading
Loading