Skip to content
Draft
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
63 changes: 59 additions & 4 deletions packages/nuxi/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isBun, isTest } from 'std-env'

import { initialize } from '../dev'
import { ForkPool } from '../dev/pool'
import { ensurePortlessAvailable, registerPortlessAlias, registerPortlessExitCleanup, removePortlessAlias, resolvePortlessName, resolvePortlessURL } from '../dev/portless'
import { debug, logger } from '../utils/logger'
import { cwdArgs, dotEnvArgs, envNameArgs, extendsArgs, legacyRootDirArgs, logLevelArgs, profileArgs } from './_shared'

Expand Down Expand Up @@ -61,6 +62,11 @@ const command = defineCommand({
description: 'Host to listen on (default: `NUXT_HOST || NITRO_HOST || HOST || nuxtOptions.devServer?.host`)',
},
clipboard: { ...listhenArgs.clipboard, default: false },
portless: {
type: 'boolean',
description: 'Expose the dev server with the external `portless` CLI (https://portless.sh)',
default: false,
},
},
...profileArgs,
sslCert: {
Expand All @@ -76,7 +82,21 @@ const command = defineCommand({
// Prepare
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir)

const listenOverrides = resolveListenOverrides(ctx.args)
if (ctx.args.portless && ctx.args.tunnel) {
throw new Error('`--portless` cannot be used with `--tunnel`.')
}

const portlessName = ctx.args.portless ? await resolvePortlessName(cwd) : undefined
if (ctx.args.portless) {
await ensurePortlessAvailable(cwd)
}

const portlessURL = ctx.args.portless ? await resolvePortlessURL(cwd, portlessName!) : undefined
const syncPortlessAlias = ctx.args.portless
? async (port: number) => await registerPortlessAlias(cwd, portlessName!, port)
: undefined
const listenOverrides = resolveListenOverrides(ctx.args, portlessURL)
let closePortless: (() => Promise<void>) | undefined

// Start the initial dev server in-process with listener
const { listener, close, onRestart, onReady } = await initialize({ cwd, args: ctx.args }, {
Expand All @@ -85,11 +105,36 @@ const command = defineCommand({
showBanner: true,
})

// Disable forking when profiling to capture all activity in one process
if (ctx.args.portless) {
const unregisterPortlessExitCleanup = registerPortlessExitCleanup(cwd, portlessName!)
try {
await syncPortlessAlias!(listener.address.port)
closePortless = async () => {
unregisterPortlessExitCleanup()
await removePortlessAlias(cwd, portlessName!).catch((error) => {
logger.warn((error as Error).message)
})
}
await listener.showURL()
}
catch (error) {
unregisterPortlessExitCleanup()
await removePortlessAlias(cwd, portlessName!).catch(() => {})
await close()
throw error
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

const closeDevServer = async () => {
await closePortless?.()
await close()
}

if (!ctx.args.fork || ctx.args.profile) {
// Disable forking when profiling to capture all activity in one process.
return {
listener,
close,
close: closeDevServer,
}
}

Expand Down Expand Up @@ -120,6 +165,9 @@ const command = defineCommand({
cleanupCurrentFork = await pool.getFork(context, (message) => {
// Handle IPC messages from the fork
if (message.type === 'nuxt:internal:dev:ready') {
if (syncPortlessAlias) {
void syncPortlessAlias(getPortFromAddress(message.address)).catch(error => logger.warn((error as Error).message))
}
if (startTime) {
debug(`Dev server ready for connections in ${Date.now() - startTime}ms`)
}
Expand All @@ -144,6 +192,7 @@ const command = defineCommand({
return {
async close() {
cleanupCurrentFork?.()
await closePortless?.()
await Promise.all([
listener.close(),
close(),
Expand All @@ -162,7 +211,7 @@ type ArgsT = Exclude<
undefined | ((...args: unknown[]) => unknown)
>

function resolveListenOverrides(args: ParsedArgs<ArgsT>) {
function resolveListenOverrides(args: ParsedArgs<ArgsT>, publicURL?: string) {
// _PORT is used by `@nuxt/test-utils` to launch the dev server on a specific port
if (process.env._PORT) {
return {
Expand Down Expand Up @@ -195,6 +244,8 @@ function resolveListenOverrides(args: ParsedArgs<ArgsT>) {

return {
...options,
publicURL,
showURL: !args.portless,
// if the https flag is not present, https.xxx arguments are ignored.
// override if https is enabled in devServer config.
_https: args.https,
Expand All @@ -212,3 +263,7 @@ function isBunForkSupported() {
const bunVersion: string = (globalThis as any).Bun.version
return satisfies(bunVersion, '>=1.2')
}

function getPortFromAddress(address: string) {
return Number(new URL(address).port)
}
116 changes: 116 additions & 0 deletions packages/nuxi/src/dev/portless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { spawnSync } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { basename, join } from 'node:path'
import process from 'node:process'

import { x } from 'tinyexec'

const DEFAULT_PORTLESS_NAME = 'nuxt-app'

export async function ensurePortlessAvailable(cwd: string) {
try {
await runPortless(cwd, ['--version'])
}
catch (error) {
if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {
throw new Error('Portless is required for `--portless`. Install it from https://portless.sh')
}

throw createPortlessError('check portless availability', error)
}
}

export async function resolvePortlessURL(cwd: string, name: string) {
try {
await runPortless(cwd, ['proxy', 'start'])
const result = await runPortless(cwd, ['get', '--no-worktree', name])
return result.stdout.trim()
}
catch (error) {
throw createPortlessError('resolve the portless URL', error)
}
}

export async function registerPortlessAlias(cwd: string, name: string, port: number) {
try {
await runPortless(cwd, ['alias', name, `${port}`])
}
catch (error) {
throw createPortlessError(`register the portless alias for port ${port}`, error)
}
}

export async function removePortlessAlias(cwd: string, name: string) {
try {
await runPortless(cwd, ['alias', '--remove', name])
}
catch (error) {
throw createPortlessError(`remove the portless alias for ${name}`, error)
}
}

export function registerPortlessExitCleanup(cwd: string, name: string) {
let disposed = false

const cleanup = () => {
if (disposed) {
return
}

disposed = true
process.off('exit', cleanup)
runPortlessSync(cwd, ['alias', '--remove', name])
}

process.on('exit', cleanup)

return () => {
disposed = true
process.off('exit', cleanup)
}
}

function createPortlessError(action: string, error: unknown) {
const message = typeof error === 'object' && error && 'stderr' in error && typeof error.stderr === 'string' && error.stderr.trim()
? error.stderr.trim()
: error instanceof Error && error.message
? error.message
: 'Unknown portless error'

return new Error(`Failed to ${action}: ${message}`)
}

export async function resolvePortlessName(cwd: string) {
const packageName = await readFile(join(cwd, 'package.json'), 'utf8')
.then(contents => JSON.parse(contents))
.then(pkg => typeof pkg.name === 'string' ? pkg.name : undefined)
.catch(() => undefined)
return normalizePortlessName(packageName || basename(cwd))
}

function normalizePortlessName(value: string) {
const normalizedValue = value
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '')

return normalizedValue || DEFAULT_PORTLESS_NAME
}

function runPortless(cwd: string, args: string[]) {
return x('portless', args, {
throwOnError: true,
nodeOptions: {
cwd,
stdio: 'pipe',
},
})
}

function runPortlessSync(cwd: string, args: string[]) {
spawnSync('portless', args, {
cwd,
stdio: 'ignore',
})
}
Loading
Loading