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
3 changes: 2 additions & 1 deletion knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"pkg-types",
"scule",
"semver",
"ufo"
"ufo",
"youch"
]
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/nuxi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"ufo": "^1.5.4",
"unbuild": "^3.5.0",
"unplugin-purge-polyfills": "^0.0.7",
"vitest": "^3.0.9"
"vitest": "^3.0.9",
"youch": "^4.1.0-beta.6"
}
}
8 changes: 8 additions & 0 deletions packages/nuxi/src/commands/dev-child.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ export default defineCommand({
devContext,
})

nuxtDev.on('loading:error', (_error) => {
sendIPCMessage({ type: 'nuxt:internal:dev:loading:error', error: {
message: _error.message,
stack: _error.stack,
name: _error.name,
code: _error.code,
} })
})
nuxtDev.on('loading', (message) => {
sendIPCMessage({ type: 'nuxt:internal:dev:loading', message })
})
Expand Down
18 changes: 18 additions & 0 deletions packages/nuxi/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { isBun, isTest } from 'std-env'
import { showVersions } from '../utils/banner'
import { _getDevServerDefaults, _getDevServerOverrides } from '../utils/dev'
import { overrideEnv } from '../utils/env'
import { renderError } from '../utils/error'
import { loadKit } from '../utils/kit'
import { logger } from '../utils/logger'
import { cwdArgs, dotEnvArgs, envNameArgs, legacyRootDirArgs, logLevelArgs } from './_shared'
Expand Down Expand Up @@ -123,6 +124,7 @@ type DevProxy = Awaited<ReturnType<typeof _createDevProxy>>
async function _createDevProxy(nuxtOptions: NuxtOptions, listenOptions: Partial<ListenOptions>) {
const jiti = createJiti(nuxtOptions.rootDir)
let loadingMessage = 'Nuxt dev server is starting...'
let error: Error | undefined
let loadingTemplate = nuxtOptions.devServer.loadingTemplate
for (const url of nuxtOptions.modulesDir) {
// @ts-expect-error this is for backwards compatibility
Expand All @@ -138,6 +140,10 @@ async function _createDevProxy(nuxtOptions: NuxtOptions, listenOptions: Partial<
let address: string | undefined

const handler = (req: IncomingMessage, res: ServerResponse) => {
if (error) {
renderError(req, res, error)
return
}
if (!address) {
res.statusCode = 503
res.setHeader('Content-Type', 'text/html')
Expand Down Expand Up @@ -169,6 +175,12 @@ async function _createDevProxy(nuxtOptions: NuxtOptions, listenOptions: Partial<
setLoadingMessage: (_msg: string) => {
loadingMessage = _msg
},
setError: (_error: Error) => {
error = _error
},
clearError() {
error = undefined
},
}
}

Expand All @@ -183,6 +195,7 @@ async function _startSubprocess(devProxy: DevProxy, rawArgs: string[], listenArg
}

const restart = async () => {
devProxy.clearError()
// Kill previous process with restart signal (not supported on Windows)
if (process.platform === 'win32') {
kill('SIGTERM')
Expand Down Expand Up @@ -226,6 +239,11 @@ async function _startSubprocess(devProxy: DevProxy, rawArgs: string[], listenArg
else if (message.type === 'nuxt:internal:dev:loading') {
devProxy.setAddress(undefined)
devProxy.setLoadingMessage(message.message)
devProxy.clearError()
}
else if (message.type === 'nuxt:internal:dev:loading:error') {
devProxy.setAddress(undefined)
devProxy.setError(message.error)
}
else if (message.type === 'nuxt:internal:dev:restart') {
restart()
Expand Down
66 changes: 31 additions & 35 deletions packages/nuxi/src/utils/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Nuxt, NuxtConfig } from '@nuxt/schema'
import type { FSWatcher } from 'chokidar'
import type { Jiti } from 'jiti'
import type { HTTPSOptions, Listener, ListenOptions, ListenURL } from 'listhen'
import type { RequestListener, ServerResponse } from 'node:http'
import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'

import EventEmitter from 'node:events'
Expand All @@ -22,12 +22,14 @@ import { clearBuildDir } from '../utils/fs'
import { loadKit } from '../utils/kit'
import { logger } from '../utils/logger'
import { loadNuxtManifest, resolveNuxtManifest, writeNuxtManifest } from '../utils/nuxt'
import { renderError } from './error'

export type NuxtDevIPCMessage =
| { type: 'nuxt:internal:dev:ready', port: number }
| { type: 'nuxt:internal:dev:loading', message: string }
| { type: 'nuxt:internal:dev:restart' }
| { type: 'nuxt:internal:dev:rejection', message: string }
| { type: 'nuxt:internal:dev:loading:error', error: Error }

export interface NuxtDevContext {
public?: boolean
Expand All @@ -53,10 +55,7 @@ interface NuxtDevServerOptions {
devContext: NuxtDevContext
}

export async function createNuxtDevServer(
options: NuxtDevServerOptions,
listenOptions?: Partial<ListenOptions>,
) {
export async function createNuxtDevServer(options: NuxtDevServerOptions, listenOptions?: Partial<ListenOptions>) {
// Initialize dev server
const devServer = new NuxtDevServer(options)

Expand Down Expand Up @@ -88,15 +87,15 @@ export async function createNuxtDevServer(
}

// https://regex101.com/r/7HkR5c/1
const RESTART_RE
= /^(?:nuxt\.config\.[a-z0-9]+|\.nuxtignore|\.nuxtrc|\.config\/nuxt(?:\.config)?\.[a-z0-9]+)$/
const RESTART_RE = /^(?:nuxt\.config\.[a-z0-9]+|\.nuxtignore|\.nuxtrc|\.config\/nuxt(?:\.config)?\.[a-z0-9]+)$/

class NuxtDevServer extends EventEmitter {
private _handler?: RequestListener
private _distWatcher?: FSWatcher
private _currentNuxt?: Nuxt
private _loadingMessage?: string
private _jiti: Jiti
private _loadingError?: Error

loadDebounced: (reload?: boolean, reason?: string) => void
handler: RequestListener
Expand All @@ -118,20 +117,28 @@ class NuxtDevServer extends EventEmitter {
this._jiti = createJiti(options.cwd)

this.handler = async (req, res) => {
if (this._loadingError) {
this._renderError(req, res)
return
}
await _initPromise
if (this._handler) {
this._handler(req, res)
}
else {
this._renderLoadingScreen(res)
this._renderLoadingScreen(req, res)
}
}

// @ts-expect-error we set it in wrapper function
this.listener = undefined
}

async _renderLoadingScreen(res: ServerResponse) {
_renderError(req: IncomingMessage, res: ServerResponse) {
renderError(req, res, this._loadingError)
}

async _renderLoadingScreen(req: IncomingMessage, res: ServerResponse) {
res.statusCode = 503
res.setHeader('Content-Type', 'text/html')
const loadingTemplate
Expand All @@ -154,13 +161,14 @@ class NuxtDevServer extends EventEmitter {
async load(reload?: boolean, reason?: string) {
try {
await this._load(reload, reason)
this._loadingError = undefined
}
catch (error) {
logger.error(`Cannot ${reload ? 'restart' : 'start'} nuxt: `, error)
this._handler = undefined
this._loadingMessage
= 'Error while loading Nuxt. Please check console and fix errors.'
this.emit('loading', this._loadingMessage)
this._loadingError = error as Error
this._loadingMessage = 'Error while loading Nuxt. Please check console and fix errors.'
this.emit('loading:error', error)
}
}

Expand Down Expand Up @@ -270,28 +278,19 @@ class NuxtDevServer extends EventEmitter {
)
}

await this._currentNuxt.hooks.callHook(
'listen',
this.listener.server,
this.listener,
)
await this._currentNuxt.hooks.callHook('listen', this.listener.server, this.listener)

// Sync internal server info to the internals
// It is important for vite-node to use the internal URL but public proto
const addr = this.listener.address
this._currentNuxt.options.devServer.host = addr.address
this._currentNuxt.options.devServer.port = addr.port
this._currentNuxt.options.devServer.url = _getAddressURL(
addr,
!!this.listener.https,
)
this._currentNuxt.options.devServer.url = _getAddressURL(addr, !!this.listener.https)
this._currentNuxt.options.devServer.https = this.options.devContext.proxy
?.https as boolean | { key: string, cert: string }

if (this.listener.https && !process.env.NODE_TLS_REJECT_UNAUTHORIZED) {
logger.warn(
'You might need `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable to make https work.',
)
logger.warn('You might need `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable to make https work.')
}

await Promise.all([
Expand All @@ -300,10 +299,10 @@ class NuxtDevServer extends EventEmitter {
])

// Watch dist directory
this._distWatcher = chokidar.watch(
resolve(this._currentNuxt.options.buildDir, 'dist'),
{ ignoreInitial: true, depth: 0 },
)
this._distWatcher = chokidar.watch(resolve(this._currentNuxt.options.buildDir, 'dist'), {
ignoreInitial: true,
depth: 0,
})
this._distWatcher.on('unlinkDir', () => {
this.loadDebounced(true, '.nuxt/dist directory has been removed')
})
Expand All @@ -313,13 +312,10 @@ class NuxtDevServer extends EventEmitter {
}

async _watchConfig() {
const configWatcher = chokidar.watch(
[this.options.cwd, join(this.options.cwd, '.config')],
{
ignoreInitial: true,
depth: 0,
},
)
const configWatcher = chokidar.watch([this.options.cwd, join(this.options.cwd, '.config')], {
ignoreInitial: true,
depth: 0,
})
configWatcher.on('all', (event, _file) => {
if (event === 'all' || event === 'ready' || event === 'error' || event === 'raw') {
return
Expand Down
16 changes: 16 additions & 0 deletions packages/nuxi/src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { IncomingMessage, ServerResponse } from 'node:http'
import { Youch } from 'youch'

export async function renderError(req: IncomingMessage, res: ServerResponse, error: unknown) {
const youch = new Youch()
res.statusCode = 500
res.setHeader('Content-Type', 'text/html')
const html = await youch.toHTML(error, {
request: {
url: req.url,
method: req.method,
headers: req.headers,
},
})
res.end(html)
}
6 changes: 4 additions & 2 deletions packages/nuxt-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"semver": "^7.7.1",
"std-env": "^3.8.1",
"tinyexec": "^1.0.1",
"ufo": "^1.5.4"
"ufo": "^1.5.4",
"youch": "^4.1.0-beta.6"
},
"devDependencies": {
"@types/node": "^22.13.14",
Expand All @@ -64,6 +65,7 @@
"typescript": "^5.8.2",
"unbuild": "^3.5.0",
"unplugin-purge-polyfills": "^0.0.7",
"vitest": "^3.0.9"
"vitest": "^3.0.9",
"youch": "^4.1.0-beta.6"
}
}
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.