Skip to content
This repository was archived by the owner on Apr 6, 2023. It is now read-only.
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
6 changes: 3 additions & 3 deletions packages/kit/src/nitro.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Middleware } from 'h3'
import type { NodeMiddleware } from 'h3'
import type { NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack'
import { useNuxt } from './context'

export interface LegacyServerMiddleware {
route?: string,
path?: string,
handle?: Middleware | string
handler: Middleware | string
handle?: NodeMiddleware | string
handler: NodeMiddleware | string
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"execa": "^6.1.0",
"flat": "^5.0.2",
"giget": "^0.1.7",
"h3": "^0.7.21",
"h3": "^0.8.1",
"jiti": "^1.16.0",
"listhen": "^0.3.4",
"mlly": "^0.5.16",
Expand Down
8 changes: 4 additions & 4 deletions packages/nuxi/src/commands/analyze.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { promises as fsp } from 'node:fs'
import { join, resolve } from 'pathe'
import { createApp, defineLazyHandler } from 'h3'
import { createApp, eventHandler, lazyEventHandler, toNodeListener } from 'h3'
import { listen } from 'listhen'
import { writeTypes } from '../utils/prepare'
import { loadKit } from '../utils/kit'
Expand Down Expand Up @@ -37,9 +37,9 @@ export default defineNuxtCommand({

const app = createApp()

const serveFile = (filePath: string) => defineLazyHandler(async () => {
const serveFile = (filePath: string) => lazyEventHandler(async () => {
const contents = await fsp.readFile(filePath, 'utf-8')
return (_req, res) => { res.end(contents) }
return eventHandler((event) => { event.res.end(contents) })
})

console.warn('Do not deploy analyze results! Use `nuxi build` before deploying.')
Expand All @@ -65,7 +65,7 @@ export default defineNuxtCommand({
</ul>
</html>`)

await listen(app)
await listen(toNodeListener(app))

return 'wait' as const
}
Expand Down
3 changes: 2 additions & 1 deletion packages/nuxi/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default defineNuxtCommand({
overrideEnv('development')

const { listen } = await import('listhen')
const { toNodeListener } = await import('h3')
let currentHandler: RequestListener | undefined
let loadingMessage = 'Nuxt is starting...'
const loadingHandler: RequestListener = async (_req, res) => {
Expand Down Expand Up @@ -100,7 +101,7 @@ export default defineNuxtCommand({
writeTypes(currentNuxt).catch(console.error),
buildNuxt(currentNuxt)
])
currentHandler = currentNuxt.server.app
currentHandler = toNodeListener(currentNuxt.server.app)
if (isRestart && args.clear !== false) {
showBanner()
showURL()
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@
"escape-string-regexp": "^5.0.0",
"fs-extra": "^10.1.0",
"globby": "^13.1.2",
"h3": "^0.7.21",
"h3": "^0.8.1",
"hash-sum": "^2.0.0",
"hookable": "^5.4.1",
"knitwork": "^0.1.2",
"magic-string": "^0.26.7",
"mlly": "^0.5.16",
"nitropack": "^0.5.4",
"nitropack": "npm:nitropack-edge@0.5.5-27764245.b884d0c",
"nuxi": "3.0.0-rc.11",
"ohash": "^0.1.5",
"ohmyfetch": "^0.4.19",
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/app/composables/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ref, Ref, watch } from 'vue'
import { parse, serialize, CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
import { appendHeader } from 'h3'
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import destr from 'destr'
import { isEqual } from 'ohash'
import { useNuxtApp } from '../nuxt'
Expand Down Expand Up @@ -70,7 +70,7 @@ function writeClientCookie (name: string, value: any, opts: CookieSerializeOptio
}
}

function writeServerCookie (event: CompatibilityEvent, name: string, value: any, opts: CookieSerializeOptions = {}) {
function writeServerCookie (event: H3Event, name: string, value: any, opts: CookieSerializeOptions = {}) {
if (event) {
// TODO: Try to smart join with existing Set-Cookie headers
appendHeader(event, 'Set-Cookie', serializeCookie(name, value, opts))
Expand Down
6 changes: 3 additions & 3 deletions packages/nuxt/src/app/composables/ssr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-redeclare */
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import { useNuxtApp, NuxtApp } from '../nuxt'

export function useRequestHeaders<K extends string = string> (include: K[]): Record<K, string | undefined>
Expand All @@ -11,8 +11,8 @@ export function useRequestHeaders (include?: any[]) {
return Object.fromEntries(include.filter(key => headers[key]).map(key => [key, headers[key]]))
}

export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): CompatibilityEvent {
return nuxtApp.ssrContext?.event as CompatibilityEvent
export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): H3Event {
return nuxtApp.ssrContext?.event as H3Event
}

export function setResponseStatus (code: number, message?: string) {
Expand Down
8 changes: 2 additions & 6 deletions packages/nuxt/src/app/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createHooks, Hookable } from 'hookable'
import type { RuntimeConfig, AppConfigInput } from '@nuxt/schema'
import { getContext } from 'unctx'
import type { SSRContext } from 'vue-bundle-renderer/runtime'
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'

const nuxtAppCtx = getContext<NuxtApp>('nuxt-app')

Expand Down Expand Up @@ -40,11 +40,7 @@ export interface RuntimeNuxtHooks {

export interface NuxtSSRContext extends SSRContext {
url: string
event: CompatibilityEvent
/** @deprecated Use `event` instead. */
req?: CompatibilityEvent['req']
/** @deprecated Use `event` instead. */
res?: CompatibilityEvent['res']
event: H3Event
runtimeConfig: RuntimeConfig
noSSR: boolean
/** whether we are rendering an SSR error */
Expand Down
10 changes: 6 additions & 4 deletions packages/nuxt/src/core/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { Nuxt } from '@nuxt/schema'
import { resolvePath } from '@nuxt/kit'
import defu from 'defu'
import fsExtra from 'fs-extra'
import { toEventHandler, dynamicEventHandler } from 'h3'
import { dynamicEventHandler } from 'h3'
import { distDir } from '../dirs'
import { ImportProtectionPlugin } from './plugins/import-protection'

Expand All @@ -22,7 +22,6 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
workspaceDir: nuxt.options.workspaceDir,
srcDir: nuxt.options.serverDir,
dev: nuxt.options.dev,
preset: nuxt.options.dev ? 'nitro-dev' : undefined,
buildDir: nuxt.options.buildDir,
analyze: nuxt.options.build.analyze && {
template: 'treemap',
Expand Down Expand Up @@ -190,7 +189,7 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
nuxt.hook('build:compile', ({ compiler }) => {
compiler.outputFileSystem = { ...fsExtra, join } as any
})
nuxt.hook('server:devMiddleware', (m) => { devMiddlewareHandler.set(toEventHandler(m)) })
nuxt.hook('server:devHandler', (h) => { devMiddlewareHandler.set(h) })
nuxt.server = createDevServer(nitro)
nuxt.hook('build:resources', () => {
nuxt.server.reload()
Expand Down Expand Up @@ -230,7 +229,10 @@ async function resolveHandlers (nuxt: Nuxt) {
}

declare module 'nitropack' {
interface NitroRouteOption {
interface NitroRouteConfig {
ssr?: boolean
}
interface NitroRouteOptions {
ssr?: boolean
}
}
12 changes: 3 additions & 9 deletions packages/nuxt/src/core/runtime/nitro/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import type { RenderResponse } from 'nitropack'
import type { Manifest } from 'vite'
import { appendHeader, getQuery } from 'h3'
import devalue from '@nuxt/devalue'
import { createRouter as createMatcher } from 'radix3'
import { joinURL } from 'ufo'
import { renderToString as _renderToString } from 'vue/server-renderer'
import { useRuntimeConfig, useNitroApp, defineRenderHandler } from '#internal/nitro'
import { useRuntimeConfig, useNitroApp, defineRenderHandler, getRouteOptions } from '#internal/nitro'
// eslint-disable-next-line import/no-restricted-paths
import type { NuxtApp, NuxtSSRContext } from '#app'

Expand Down Expand Up @@ -107,9 +106,6 @@ const getSPARenderer = lazyCachedFunction(async () => {
}
})

// Set up route rule matcher
const routerOptions = createMatcher({ routes: useRuntimeConfig().nitro.routes })

const PAYLOAD_CACHE = (process.env.NUXT_PAYLOAD_EXTRACTION && process.env.prerender) ? new Map() : null // TODO: Use LRU cache
const PAYLOAD_URL_RE = /\/_payload(\.[a-zA-Z0-9]+)?.js(\?.*)?$/

Expand All @@ -132,15 +128,13 @@ export default defineRenderHandler(async (event) => {
}
}

// TODO: share across endpoints on event context
const routeOptions = event.context.routeOptions || routerOptions.lookup(url) || {}
// Get route options (currently to apply `ssr: false`)
const routeOptions = getRouteOptions(event)

// Initialize ssr context
const ssrContext: NuxtSSRContext = {
url,
event,
req: event.req,
res: event.res,
runtimeConfig: useRuntimeConfig() as NuxtSSRContext['runtimeConfig'],
noSSR:
!!(process.env.NUXT_NO_SSR) ||
Expand Down
5 changes: 3 additions & 2 deletions packages/schema/src/types/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Compiler, Configuration, Stats } from 'webpack'
import type { TSConfig } from 'pkg-types'
import type { InlineConfig as ViteInlineConfig, ViteDevServer } from 'vite'
import type { Manifest } from 'vue-bundle-renderer'
import type { Middleware } from 'h3'
import type { EventHandler } from 'h3'
import type { ModuleContainer } from './module'
import type { NuxtTemplate, Nuxt, NuxtApp } from './nuxt'
import type { Preset as ImportPreset, Import } from 'unimport'
Expand Down Expand Up @@ -77,6 +77,7 @@ export interface NuxtHooks {
'builder:generateApp': () => HookResult
'pages:extend': (pages: NuxtPage[]) => HookResult
'build:manifest': (manifest: Manifest) => HookResult
'server:devHandler': (handler: EventHandler) => HookResult

// Auto imports
'imports:sources': (presets: ImportPresetWithDeprecation[]) => HookResult
Expand Down Expand Up @@ -158,10 +159,10 @@ export interface NuxtHooks {
'webpack:config': (webpackConfigs: Configuration[]) => HookResult
'webpack:devMiddleware': (middleware: (req: IncomingMessage, res: ServerResponse, next: (err?: any) => any) => any) => HookResult
'webpack:hotMiddleware': (middleware: (req: IncomingMessage, res: ServerResponse, next: (err?: any) => any) => any) => HookResult
'server:devMiddleware': (middleware: (req: IncomingMessage, res: ServerResponse, next: (err?: any) => any) => any) => HookResult
'build:compile': (options: { name: string, compiler: Compiler }) => HookResult
'build:compiled': (options: { name: string, compiler: Compiler, stats: Stats }) => HookResult
'build:resources': (mfs?: Compiler['outputFileSystem']) => HookResult
'server:devMiddleware': (middleware: Middleware) => HookResult
'bundler:change': (shortPath: string) => void
'bundler:error': () => void
'bundler:done': () => void
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"externality": "^0.2.2",
"fs-extra": "^10.1.0",
"get-port-please": "^2.6.1",
"h3": "^0.7.21",
"h3": "^0.8.1",
"knitwork": "^0.1.2",
"magic-string": "^0.26.7",
"mlly": "^0.5.16",
Expand Down
21 changes: 12 additions & 9 deletions packages/vite/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { join, resolve } from 'pathe'
import * as vite from 'vite'
import vuePlugin from '@vitejs/plugin-vue'
import viteJsxPlugin from '@vitejs/plugin-vue-jsx'
import type { Connect, ServerOptions } from 'vite'
import type { ServerOptions } from 'vite'
import { logger } from '@nuxt/kit'
import { getPort } from 'get-port-please'
import { joinURL, withoutLeadingSlash } from 'ufo'
import defu from 'defu'
import type { OutputOptions } from 'rollup'
import { defineEventHandler } from 'h3'
import { cacheDirPlugin } from './plugins/cache-dir'
import { wpfs } from './utils/wpfs'
import type { ViteBuildContext, ViteOptions } from './vite'
Expand Down Expand Up @@ -109,18 +110,20 @@ export async function buildClient (ctx: ViteBuildContext) {
const viteServer = await vite.createServer(clientConfig)
ctx.clientServer = viteServer
await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false })
const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => {
const viteMiddleware = defineEventHandler(async (event) => {
// Workaround: vite devmiddleware modifies req.url
const originalURL = req.url!
const originalURL = event.req.url!
if (!originalURL.startsWith('/__nuxt_vite_node__') && !originalURL.startsWith(clientConfig.base!)) {
req.url = joinURL('/__url', originalURL)
event.req.url = joinURL('/__url', originalURL)
}
viteServer.middlewares.handle(req, res, (err: unknown) => {
req.url = originalURL
next(err)
await new Promise((resolve, reject) => {
viteServer.middlewares.handle(event.req, event.res, (err: Error) => {
event.req.url = originalURL
return err ? reject(err) : resolve(null)
})
})
}
await ctx.nuxt.callHook('server:devMiddleware', viteMiddleware)
})
await ctx.nuxt.callHook('server:devHandler', viteMiddleware)

ctx.nuxt.hook('close', async () => {
await viteServer.close()
Expand Down
12 changes: 6 additions & 6 deletions packages/vite/src/vite-node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { pathToFileURL } from 'node:url'
import { createApp, createError, defineEventHandler, defineLazyEventHandler } from 'h3'
import { createApp, createError, defineEventHandler, defineLazyEventHandler, eventHandler, toNodeListener } from 'h3'
import { ViteNodeServer } from 'vite-node/server'
import fse from 'fs-extra'
import { resolve } from 'pathe'
Expand All @@ -21,7 +21,7 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
name: 'nuxt:vite-node-server',
enforce: 'post',
configureServer (server) {
server.middlewares.use('/__nuxt_vite_node__', createViteNodeMiddleware(ctx, invalidates))
server.middlewares.use('/__nuxt_vite_node__', toNodeListener(createViteNodeApp(ctx, invalidates)))
},
handleHotUpdate ({ file, server }) {
function markInvalidate (mod: ModuleNode) {
Expand All @@ -43,7 +43,7 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
export function registerViteNodeMiddleware (ctx: ViteBuildContext) {
addDevServerHandler({
route: '/__nuxt_vite_node__/',
handler: createViteNodeMiddleware(ctx)
handler: createViteNodeApp(ctx).handler
})
}

Expand All @@ -69,7 +69,7 @@ function getManifest (ctx: ViteBuildContext) {
return manifest
}

function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<string> = new Set()) {
function createViteNodeApp (ctx: ViteBuildContext, invalidates: Set<string> = new Set()) {
const app = createApp()

app.use('/manifest', defineEventHandler(() => {
Expand Down Expand Up @@ -107,7 +107,7 @@ function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<strin
return false
}

return async (event) => {
return eventHandler(async (event) => {
const moduleId = decodeURI(event.req.url!).substring(1)
if (moduleId === '/') {
throw createError({ statusCode: 400 })
Expand All @@ -122,7 +122,7 @@ function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<strin
throw createError({ data: errorData })
})
return module
}
})
}))

return app
Expand Down
Loading