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 packages/devtools-onboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"devDependencies": {
"@nuxt/kit": "catalog:prod",
"@nuxt/schema": "catalog:types",
"nuxt": "catalog:buildtools"
"nuxt": "catalog:buildtools",
"vite": "catalog:buildtools"
}
}
22 changes: 17 additions & 5 deletions packages/devtools-onboard/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const DEVTOOLS_MODULES = new Set([DEVTOOLS, DEVTOOLS_NIGHTLY, `${DEVTOOLS}-edge`
*/
const DEVTOOLS_PACKAGES = [DEVTOOLS_NIGHTLY, DEVTOOLS]

/**
* Where Vite DevTools mounts the hub, so after the restart the real
* `embedded.js` answers at the URL the button was loaded from.
*/
const BASE = '/__devtools/'

function listsDevtools(modules: NuxtOptions['modules']): boolean {
return modules.some((entry) => {
const id = Array.isArray(entry) ? entry[0] : entry
Expand Down Expand Up @@ -59,9 +65,7 @@ export default defineNuxtModule({

const onboarding = createOnboarding({
cwd: nuxt.options.rootDir,
// Where Vite DevTools mounts the hub, so after the restart the real
// `embedded.js` answers at the URL the button was loaded from.
base: '/__devtools/',
base: BASE,
packages: [await devtoolsSpec()],
branding: {
productName: 'Nuxt DevTools',
Expand All @@ -85,8 +89,16 @@ export default defineNuxtModule({
})

nuxt.hook('vite:serverCreated', (server, { isClient }) => {
if (isClient)
server.middlewares.use(onboarding.nodeMiddleware)
if (!isClient)
return
// Nuxt only hands a request to Vite when a middleware is mounted on a
// path other than `/`; otherwise it rewrites the URL to `/__skip_vite/…`.
// Connect strips the mount path, so restore the full URL the
// middleware matches against `base`.
server.middlewares.use(BASE.slice(0, -1), (req, res, next) => {
req.url = req.originalUrl || req.url
onboarding.nodeMiddleware(req, res, next)
})
})
if (!onboarding.disabled)
(nuxt.options.app.head.script ??= []).push({ type: 'module', src: onboarding.scriptSrc, tagPosition: 'bodyClose' })
Expand Down
42 changes: 23 additions & 19 deletions packages/devtools-onboard/test/module.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { Nuxt, NuxtConfig } from '@nuxt/schema'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { ViteDevServer } from 'vite'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { loadNuxt } from 'nuxt'
import { createServer as createViteServer } from 'vite'
import { afterEach, describe, expect, it } from 'vitest'

const onboardModule = fileURLToPath(new URL('../src/module.ts', import.meta.url))
Expand Down Expand Up @@ -56,26 +57,24 @@ function onboardScripts(nuxt: Nuxt) {
return (nuxt.options.app.head.script ?? []).filter(script => typeof script === 'object' && script.src === '/__devtools/embedded.js')
}

type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void

/** Serves what the module mounts on the client Vite server; resolves to its origin. */
async function serveViteMiddleware(nuxt: Nuxt): Promise<string> {
const mounted: Middleware[] = []
// Only `middlewares.use` is read; the rest of a real ViteDevServer is irrelevant here.
const viteServer = { middlewares: { use: (fn: Middleware) => mounted.push(fn) } } as never
/** Serves what the module mounts on a real client Vite server; resolves to its origin. */
async function serveViteMiddleware(nuxt: Nuxt): Promise<{ origin: string, viteServer: ViteDevServer }> {
const viteServer = await createViteServer({ configFile: false, logLevel: 'silent', server: { middlewareMode: true, ws: false } })
cleanups.push(() => viteServer.close())
// Mount only what the module adds, not Vite's own transform middlewares.
viteServer.middlewares.stack.length = 0
await nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false })
const [middleware] = mounted
if (!middleware)
throw new Error('onboarding middleware was not mounted')

const server = createServer((req, res) => middleware(req, res, () => {
res.statusCode = 404
res.end()
}))

const server = createServer(viteServer.middlewares)
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
cleanups.push(() => new Promise(resolve => server.close(() => resolve())))
const { port } = server.address() as { port: number } // listening on a TCP port, never a pipe
return `http://127.0.0.1:${port}`
return { origin: `http://127.0.0.1:${port}`, viteServer }
}

/** Nuxt's dev handler only passes a URL to Vite when a middleware is mounted on a path other than `/`. */
function nuxtRoutesToVite(viteServer: ViteDevServer, url: string) {
return viteServer.middlewares.stack.some(({ route }) => route.length > 1 && url.startsWith(route))
}

const onboardStatus = (origin: string) => fetch(`${origin}/__devtools/__onboard/status`).then(r => r.json())
Expand Down Expand Up @@ -104,7 +103,12 @@ describe('@nuxt/devtools-onboard', () => {
expect(nuxt.options._requiredModules['@nuxt/devtools']).toBeUndefined()
expect(onboardScripts(nuxt)).toHaveLength(1)

const status = await onboardStatus(await serveViteMiddleware(nuxt))
const { origin, viteServer } = await serveViteMiddleware(nuxt)
expect(nuxtRoutesToVite(viteServer, '/__devtools/embedded.js')).toBe(true)
const script = await fetch(`${origin}/__devtools/embedded.js`)
expect(script.headers.get('content-type')).toMatch(/javascript/)

const status = await onboardStatus(origin)
expect(status.state).toBe('idle')
// No lockfile in the fixture, so the package manager falls back to npm.
expect(status.command.slice(0, 3)).toEqual(['npm', 'i', '-D'])
Expand All @@ -114,7 +118,7 @@ describe('@nuxt/devtools-onboard', () => {

it('refuses to install when nobody can confirm it in the terminal', async () => {
const nuxt = await bootNuxt({ dev: true }, { withoutDevtools: true })
const origin = await serveViteMiddleware(nuxt)
const { origin } = await serveViteMiddleware(nuxt)

// Vitest workers get a piped stdin, so no terminal can answer the question.
const install = await fetch(`${origin}/__devtools/__onboard/install`, { method: 'POST' })
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

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

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ catalogs:
unocss: *unocss
unplugin-vue: ^8.0.0
unplugin-vue-markdown: ^32.1.1
vite: *vite
cli:
'@antfu/eslint-config': ^9.5.1
'@antfu/ni': ^30.6.0
Expand Down
Loading