Commit de0b43b9 authored by Jimmy Lai's avatar Jimmy Lai

init

parent 355694cb
......@@ -63,3 +63,6 @@ test-timings.json
# Storybook
*storybook.log
# Claude
.claude/settings.local.json
\ No newline at end of file
......@@ -199,6 +199,7 @@
"@types/express-serve-static-core": "4.17.33",
"@types/fresh": "0.5.0",
"@types/glob": "7.1.1",
"@types/ink-spinner": "3.0.5",
"@types/jsonwebtoken": "9.0.0",
"@types/lodash": "4.14.198",
"@types/lodash.curry": "4.1.6",
......@@ -271,6 +272,8 @@
"icss-utils": "5.1.0",
"ignore-loader": "0.1.2",
"image-size": "1.2.1",
"ink": "6.6.0",
"ink-spinner": "5.0.0",
"ipaddr.js": "2.2.0",
"is-docker": "2.0.0",
"is-wsl": "2.2.0",
......@@ -307,6 +310,7 @@
"punycode": "2.1.1",
"querystring-es3": "0.2.1",
"raw-body": "2.4.1",
"react-devtools-core": "7.0.1",
"react-refresh": "0.12.0",
"recast": "0.23.11",
"regenerator-runtime": "0.13.4",
......
......@@ -297,6 +297,10 @@ program
'--experimental-next-config-strip-types',
'Use Node.js native TypeScript resolution for next.config.(ts|mts)'
)
.option(
'--experimental-tui',
'Enables an experimental terminal UI with per-session log isolation.'
)
.action(
(directory: string, options: NextDevOptions, { _optionValueSources }) => {
if (options.experimentalNextConfigStripTypes) {
......
......@@ -81,7 +81,37 @@ let loadingLogTimer: NodeJS.Timeout | null = null
let traceSpan: Span | null = null
let logging = true
/**
* Send compilation state to parent process TUI if enabled
*/
function sendCompilationStateToTui(state: OutputState) {
if (!process.env.__NEXT_TUI_ENABLED || !process.send) {
return
}
if (state.bootstrap) {
return
}
const payload = state.loading
? {
loading: true,
trigger: state.trigger ? formatTrigger(state.trigger) : undefined,
url: state.url,
}
: {
loading: false,
totalModulesCount: state.totalModulesCount,
errors: state.errors,
warnings: state.warnings,
}
process.send({ tuiMessage: { type: 'compilation', payload } })
}
store.subscribe((state) => {
// Send compilation state to TUI
sendCompilationStateToTui(state)
// Update persisted logging state
if ('logging' in state) {
logging = state.logging
......@@ -96,6 +126,10 @@ store.subscribe((state) => {
return
}
// Skip console logging when TUI is enabled (compilation state sent via IPC)
// but still run all state management logic below
const shouldLog = !process.env.__NEXT_TUI_ENABLED
if (state.bootstrap) {
return
}
......@@ -108,7 +142,7 @@ store.subscribe((state) => {
traceSpan = trace('compile-path', undefined, {
trigger: trigger,
})
if (!loadingLogTimer) {
if (!loadingLogTimer && shouldLog) {
// Only log compiling if compiled is not finished quickly
loadingLogTimer = setTimeout(() => {
if (
......@@ -132,7 +166,9 @@ store.subscribe((state) => {
if (state.errors) {
// Log compilation errors
Log.error(state.errors[0])
if (shouldLog) {
Log.error(state.errors[0])
}
startTime = 0
// Ensure traces are flushed after each compile in development mode
......@@ -157,7 +193,9 @@ store.subscribe((state) => {
}
if (state.warnings) {
Log.warn(state.warnings.join('\n\n'))
if (shouldLog) {
Log.warn(state.warnings.join('\n\n'))
}
// Ensure traces are flushed after each compile in development mode
flushAllTraces()
teardownTraceSubscriber()
......@@ -165,9 +203,11 @@ store.subscribe((state) => {
}
if (state.typeChecking) {
Log.info(
`bundled ${trigger}${timeMessage}${modulesMessage}, type checking...`
)
if (shouldLog) {
Log.info(
`bundled ${trigger}${timeMessage}${modulesMessage}, type checking...`
)
}
return
}
......
......@@ -44,6 +44,7 @@ import {
finalizeBundlerFromConfig,
parseBundlerArgs,
} from '../lib/bundler'
import type { TuiInstance } from 'next/dist/compiled/tui/index.mjs'
export type NextDevOptions = {
disableSourceMaps: boolean
......@@ -60,12 +61,14 @@ export type NextDevOptions = {
experimentalHttpsCa?: string
experimentalUploadTrace?: string
experimentalNextConfigStripTypes?: boolean
experimentalTui?: boolean
}
type PortSource = 'cli' | 'default' | 'env'
let dir: string
let child: undefined | ChildProcess
let tuiInstance: TuiInstance | undefined
// The config in next-dev is only used to access config.distDir for telemetry and trace.
let config: NextConfigComplete
let bundler: Bundler
......@@ -86,6 +89,12 @@ const handleSessionStop = async (signal: NodeJS.Signals | number | null) => {
if (sessionStopHandled) return
sessionStopHandled = true
// Cleanup TUI if it was started
if (tuiInstance) {
tuiInstance.unmount()
tuiInstance = undefined
}
// Capture the child's exit code if it has already exited and caused the
// session stop (via the 'exit' event), otherwise assume success (0).
const exitCode = child?.exitCode || 0
......@@ -300,8 +309,11 @@ const nextDev = async (
nodeOptions.inspect = formatDebugAddress(address)
}
// When TUI is enabled, use pipes for stdio so we can capture output
const tuiEnabled = options.experimentalTui && process.stdout.isTTY
child = fork(startServerPath, {
stdio: 'inherit',
stdio: tuiEnabled ? ['pipe', 'pipe', 'pipe', 'ipc'] : 'inherit',
env: {
...defaultEnv,
...(bundler === Bundler.Turbopack
......@@ -318,10 +330,12 @@ const nextDev = async (
// https://github.com/nodejs/node/issues/29949
WATCHPACK_WATCHER_LIMIT:
os.platform() === 'darwin' ? '20' : undefined,
// Tell child process that TUI is enabled
__NEXT_TUI_ENABLED: tuiEnabled ? '1' : undefined,
},
})
child.on('message', (msg: any) => {
child.on('message', async (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) {
child?.send({ nextWorkerOptions: startServerOptions })
......@@ -332,6 +346,20 @@ const nextDev = async (
port = parseInt(msg.port, 10)
}
// Start TUI after server is ready
if (tuiEnabled && child) {
const protocol = startServerOptions.selfSignedCertificate
? 'https'
: 'http'
const serverUrl = `${protocol}://localhost:${port}`
const distDir = path.join(dir, '.next')
// Dynamically import TUI (ESM bundle with ink)
import('next/dist/compiled/tui/index.mjs').then((tui) => {
tuiInstance = tui.startTui(child!, serverUrl, distDir)
})
}
resolved = true
resolve()
}
......
import * as React from 'react'
import { Box, Text } from 'ink'
import Spinner from 'ink-spinner'
import type { CompilationState } from '../types'
interface CompilationStatusProps {
compilationState: CompilationState | null
isReady: boolean
readyTime?: string
}
export function CompilationStatus({
compilationState,
isReady,
readyTime,
}: CompilationStatusProps) {
if (!isReady) {
return (
<Box gap={1}>
<Text color="yellow">
<Spinner type="dots" />
</Text>
<Text dimColor>starting</Text>
</Box>
)
}
if (compilationState?.loading) {
const trigger = compilationState.trigger
return (
<Box gap={1}>
<Text color="cyan">
<Spinner type="dots" />
</Text>
<Text dimColor>compiling{trigger ? ` ${trigger}` : ''}</Text>
</Box>
)
}
if (compilationState?.errors?.length) {
return (
<Text color="red" bold>
{compilationState.errors.length} error
{compilationState.errors.length > 1 ? 's' : ''}
</Text>
)
}
return (
<Box gap={1}>
<Text color="green">ready</Text>
{readyTime && <Text dimColor>in {readyTime}</Text>}
</Box>
)
}
This diff is collapsed.
import * as fs from 'fs'
import * as path from 'path'
let logFilePath: string | null = null
let logFileStream: fs.WriteStream | null = null
export function initializeFileLogger(distDir: string): string {
logFilePath = path.join(distDir, 'tui.log')
// Ensure .next directory exists
fs.mkdirSync(distDir, { recursive: true })
// Clear existing file
fs.writeFileSync(logFilePath, '')
// Open write stream
logFileStream = fs.createWriteStream(logFilePath, { flags: 'a' })
return logFilePath
}
export function writeToFileLog(
level: string,
message: string,
sessionId?: string
): void {
if (!logFileStream) return
const timestamp = new Date().toISOString()
const sessionPrefix = sessionId ? `[${sessionId.slice(0, 8)}]` : '[global]'
const levelStr = level.toUpperCase().padEnd(7)
const logLine = `[${timestamp}] ${sessionPrefix} ${levelStr} ${message}\n`
logFileStream.write(logLine)
}
export function closeFileLogger(): void {
if (logFileStream) {
logFileStream.end()
logFileStream = null
}
}
This diff is collapsed.
import type { ChildProcess } from 'child_process'
export interface TuiLogEntry {
timestamp: number
level: 'info' | 'warn' | 'error' | 'wait' | 'event' | 'trace' | 'ready'
message: string
/** Additional lines that belong to this log entry */
extraLines?: string[]
/** Structured data for requests/fetches (avoids string parsing) */
structured?: StructuredLogData
/** Source of the log: 'system' for Next.js internals, 'userland' for user code */
source?: 'system' | 'userland' | 'browser'
}
export interface FetchMetricData {
method: string
url: string
status: number
totalTime: number
cacheStatus?: string
cacheReason?: string
cacheWarning?: string
}
export type StructuredLogData =
| {
type: 'request'
method: string
url: string
status: number
totalTime: number
/** 'load' for initial page load, 'nav' for client navigation (RSC), 'action' for server action */
requestType?: 'load' | 'nav' | 'action'
/** The action ID if this is a server action request */
actionId?: string | null
/** The function name if this is a server action (from manifest) */
actionName?: string
/** The file where the action is defined (from manifest) */
actionFile?: string
timings?: Array<{ label: string; time: number }>
fetchMetrics?: FetchMetricData[]
}
| {
type: 'fetch'
method: string
url: string
status: number
totalTime: number
cacheStatus?: string
cacheReason?: string
cacheWarning?: string
}
| {
type: 'cache-info'
cacheStatus: string
cacheReason: string
}
| {
type: 'warning'
message: string
}
| {
type: 'console'
/** 'browser' or 'server' */
source: 'browser' | 'server'
/** console method: log, warn, error, etc */
method: string
/** The log message */
message: string
/** Source-mapped location like "app/page.tsx:10:5" (browser logs) */
location?: string
/** Source-mapped stack trace lines (browser logs) */
stack?: string[]
/** Raw stack trace string (server logs) - parsed lazily in TUI */
rawStack?: string
}
export interface CompilationState {
loading: boolean
trigger?: string
url?: string
errors?: string[]
warnings?: string[]
totalModulesCount?: number
}
export type LogFilter = 'all' | 'errors' | 'warnings' | 'requests' | 'console'
export interface TuiState {
logs: TuiLogEntry[]
serverUrl: string
isReady: boolean
logFilter: LogFilter
compilationState: CompilationState
}
// IPC message types from child to parent
export type TuiIpcMessage =
| {
type: 'log'
payload: { level: string; message: string }
}
| { type: 'compilation'; payload: CompilationState }
| {
type: 'structured-log'
payload: StructuredLogData
}
export interface TuiProps {
child: ChildProcess
serverUrl: string
distDir: string
}
......@@ -420,6 +420,52 @@ async function handleDefaultConsole(
isServerLog: boolean
) {
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
// Get source-mapped stack for TUI
let location: string | undefined
let stackLines: string[] | undefined
if (entry.consoleMethodStack) {
const mapped = await getSourceMappedStackFrames(
entry.consoleMethodStack,
ctx,
distDir
)
location = getConsoleLocation(mapped) ?? undefined
if (
mapped.kind === 'mapped-stack' ||
mapped.kind === 'stack' ||
mapped.kind === 'with-frame-code'
) {
stackLines = mapped.stack.split('\n').filter((line) => line.trim())
}
}
// Send to TUI if enabled
if (process.env.__NEXT_TUI_ENABLED && process.send) {
const message = cleanConsoleArgsForFileLogging(consoleArgs)
process.send({
tuiMessage: {
type: 'structured-log',
payload: {
type: 'console',
source: isServerLog ? 'server' : 'browser',
method: entry.method,
message,
location,
stack: stackLines,
},
},
})
// Still log to file but skip console output
const fileLogger = getFileLogger()
if (isServerLog) {
fileLogger.logServer(entry.method.toUpperCase(), message)
} else {
fileLogger.logBrowser(entry.method.toUpperCase(), message)
}
return
}
const withStackEntry = await withLocation(
{
original: consoleArgs,
......@@ -664,3 +710,21 @@ export async function handleClientFileLogs(
fileLogger.logBrowser(log.level, log.message)
}
}
// Server log handler for TUI - processes with source mapping
// This is set by the hot-reloader when it has the mapping context
let serverLogHandler:
| ((entry: {
method: string
message: string
rawStack?: string
}) => Promise<void>)
| null = null
export function setServerLogHandler(handler: typeof serverLogHandler): void {
serverLogHandler = handler
}
export function getServerLogHandler(): typeof serverLogHandler {
return serverLogHandler
}
......@@ -101,7 +101,10 @@ import { getSupportedBrowsers, printBuildErrors } from '../../build/utils'
import {
receiveBrowserLogsTurbopack,
handleClientFileLogs,
setServerLogHandler,
handleLog,
} from './browser-logs/receive-logs'
import type { MappingContext } from './browser-logs/source-map'
import { normalizePath } from '../../lib/normalize-path'
import {
devToolsConfigMiddleware,
......@@ -301,6 +304,35 @@ export async function createHotReloaderTurbopack(
})
const entrypointsSubscription = project.entrypointsSubscribe()
// Set up server log handler for TUI with source mapping
if (process.env.__NEXT_TUI_ENABLED) {
const serverLogContext: MappingContext = {
bundler: 'turbopack',
project,
projectPath: normalizePath(relative(rootPath, projectPath) || '.'),
isServer: true,
isEdgeServer: false,
isAppDirectory: true,
}
setServerLogHandler(async (entry) => {
// Create a console entry in the format handleLog expects
const consoleEntry = {
kind: 'console' as const,
method: entry.method as any,
consoleMethodStack: entry.rawStack || null,
args: [{ kind: 'arg' as const, data: JSON.stringify(entry.message) }],
}
await handleLog(
[consoleEntry],
serverLogContext,
distDir,
true // config
)
})
}
const currentWrittenEntrypoints: Map<EntryKey, WrittenEndpoint> = new Map()
const currentEntrypoints: Entrypoints = {
global: {
......
......@@ -14,6 +14,68 @@ import type { FetchMetric } from '../base-http'
import type { NodeNextRequest, NodeNextResponse } from '../base-http/node'
import type { LoggingConfig } from '../config-shared'
import { getRequestMeta } from '../request-meta'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta'
import { traceGlobals } from '../../trace/shared'
import { join } from 'path'
import { readFileSync } from 'fs'
// Cache the manifest to avoid reading it on every request
let actionManifestCache: {
node: Record<string, { filename: string; exportedName: string }>
edge: Record<string, { filename: string; exportedName: string }>
} | null = null
let actionManifestMtime: number = 0
interface ActionInfo {
name: string
file?: string
}
function getActionInfo(actionId: string | null): ActionInfo | undefined {
if (!actionId) return undefined
const distDir = traceGlobals.get('distDir')
if (!distDir) return undefined
try {
const manifestPath = join(
distDir,
'server',
'server-reference-manifest.json'
)
const stat = (require('fs') as typeof import('fs')).statSync(manifestPath)
// Reload manifest if it changed
if (!actionManifestCache || stat.mtimeMs !== actionManifestMtime) {
actionManifestCache = JSON.parse(readFileSync(manifestPath, 'utf-8'))
actionManifestMtime = stat.mtimeMs
}
const entry =
actionManifestCache?.node?.[actionId] ||
actionManifestCache?.edge?.[actionId]
if (entry) {
const exportedName = entry.exportedName
// Inline actions have names like $$RSC_SERVER_ACTION_0
const name = exportedName.startsWith('$$RSC_SERVER_ACTION_')
? 'inline action'
: exportedName
// Clean up the filename (remove leading ./ or app/ prefix for brevity)
let file = entry.filename
if (file) {
file = file.replace(/^\.\//, '').replace(/^app\//, '')
}
return { name, file }
}
} catch {
// Manifest not available yet or error reading
}
return undefined
}
/**
* Returns true if the incoming request should be ignored for logging.
......@@ -50,6 +112,22 @@ export function logRequests(
devRequestTimingInternalsEnd: bigint | undefined,
devGenerateStaticParamsDuration: bigint | undefined
): void {
// For TUI: send structured data with fetch metrics bundled
if (process.env.__NEXT_TUI_ENABLED && process.send) {
sendStructuredRequestLog(
request,
response.statusCode,
requestStartTime,
requestEndTime,
devRequestTimingMiddlewareStart,
devRequestTimingMiddlewareEnd,
devRequestTimingInternalsEnd,
devGenerateStaticParamsDuration,
loggingConfig
)
return // Skip regular logging for TUI
}
if (!ignoreLoggingIncomingRequests(request, loggingConfig)) {
logIncomingRequests(
request,
......@@ -70,6 +148,129 @@ export function logRequests(
}
}
// Send a complete request log with all fetch metrics to TUI
function sendStructuredRequestLog(
request: NodeNextRequest,
statusCode: number,
requestStartTime: bigint,
requestEndTime: bigint,
devRequestTimingMiddlewareStart: bigint | undefined,
devRequestTimingMiddlewareEnd: bigint | undefined,
devRequestTimingInternalsEnd: bigint | undefined,
devGenerateStaticParamsDuration: bigint | undefined,
loggingConfig: LoggingConfig
): void {
const isRSC = getRequestMeta(request, 'isRSCRequest')
const { isFetchAction, actionId } = getServerActionRequestMetadata(request)
const url = isRSC ? stripNextRscUnionQuery(request.url) : request.url
const totalRequestTime = requestEndTime - requestStartTime
// Determine request type: 'action' for server actions, 'nav' for RSC navigations, 'load' for initial loads
let requestType: 'action' | 'nav' | 'load'
if (isFetchAction) {
requestType = 'action'
} else if (isRSC) {
requestType = 'nav'
} else {
requestType = 'load'
}
const timings: Array<{ label: string; time: number }> = []
let middlewareTime: bigint | undefined
if (devRequestTimingMiddlewareStart && devRequestTimingMiddlewareEnd) {
middlewareTime =
devRequestTimingMiddlewareEnd - devRequestTimingMiddlewareStart
timings.push([
'proxy.ts',
Number(middlewareTime / BigInt(1_000_000)),
] as any)
}
if (devRequestTimingInternalsEnd) {
let frameworkTime = devRequestTimingInternalsEnd - requestStartTime
if (middlewareTime) {
frameworkTime -= middlewareTime
}
timings.unshift({
label: 'compile',
time: Number(frameworkTime / BigInt(1_000_000)),
})
if (devGenerateStaticParamsDuration) {
timings.push({
label: 'generate-params',
time: Number(devGenerateStaticParamsDuration / BigInt(1_000_000)),
})
}
timings.push({
label: 'render',
time: Number(
(requestEndTime - devRequestTimingInternalsEnd) / BigInt(1_000_000)
),
})
}
// Fix the proxy.ts timing entry format
const fixedTimings = timings.map((t) =>
Array.isArray(t) ? { label: t[0], time: t[1] } : t
)
// Collect fetch metrics
const fetchMetrics: Array<{
method: string
url: string
status: number
totalTime: number
cacheStatus?: string
cacheReason?: string
cacheWarning?: string
}> = []
if (request.fetchMetrics && loggingConfig?.fetches) {
for (const metric of request.fetchMetrics) {
if (
metric.cacheStatus === 'hmr' &&
!loggingConfig.fetches?.hmrRefreshes
) {
continue
}
fetchMetrics.push({
method: metric.method,
url: metric.url,
status: metric.status,
totalTime: Math.round(metric.end - metric.start),
cacheStatus: metric.cacheStatus,
cacheReason: metric.cacheReason,
cacheWarning: metric.cacheWarning,
})
}
}
// Look up action info from manifest if this is an action
const actionInfo = isFetchAction ? getActionInfo(actionId) : undefined
process.send?.({
tuiMessage: {
type: 'structured-log',
payload: {
type: 'request',
method: request.method,
url,
status: statusCode,
totalTime: Number(totalRequestTime / BigInt(1_000_000)),
requestType,
actionId: isFetchAction ? actionId : undefined,
actionName: actionInfo?.name,
actionFile: actionInfo?.file,
timings: fixedTimings,
fetchMetrics: fetchMetrics.length > 0 ? fetchMetrics : undefined,
},
},
})
}
function logIncomingRequests(
request: NodeNextRequest,
requestStartTime: bigint,
......@@ -184,6 +385,10 @@ function logFetchMetric(
}
function writeLine(text: string, indentationLevel = 0): void {
// Skip writing to stdout when TUI is enabled (use IPC instead)
if (process.env.__NEXT_TUI_ENABLED) {
return
}
process.stdout.write(` ${'│ '.repeat(indentationLevel)}${text}\n`)
}
......
import { consoleAsyncStorage } from '../app-render/console-async-storage.external'
import { getFileLogger } from '../dev/browser-logs/file-logger'
import { formatConsoleArgs } from '../../client/lib/console'
import { getServerLogHandler } from '../dev/browser-logs/receive-logs'
type InterceptableConsoleMethod =
| 'error'
......@@ -35,14 +36,30 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
// to decide if this log is ignorable for reporting in our file logger.
return originalMethod.apply(this, args)
} else {
const ret = originalMethod.apply(this, args)
const fileLogger = getFileLogger()
const message = formatConsoleArgs(args)
// Strip ANSI escape codes for file logging
// eslint-disable-next-line no-control-regex
const ansiEscapeRegex = new RegExp('\u001b\\[[0-9;]*m', 'g')
const cleanMessage = message.replace(ansiEscapeRegex, '')
// Send to TUI if enabled - use handler for source mapping
if (process.env.__NEXT_TUI_ENABLED) {
const handler = getServerLogHandler()
if (handler) {
// Capture raw stack for source mapping
const rawStack = new Error().stack
handler({
method: methodName,
message: cleanMessage,
rawStack,
})
// File logging is handled by the handler
return undefined
}
}
const ret = originalMethod.apply(this, args)
const fileLogger = getFileLogger()
fileLogger.logServer(methodName.toUpperCase(), cleanMessage)
return ret
}
......
......@@ -2353,6 +2353,7 @@ export async function next_compile(task, opts) {
await task.parallel(
[
'cli',
'next_tui',
'copy_bundle_analyzer_ui',
'bin',
'server',
......@@ -2410,11 +2411,22 @@ export async function bin(task, opts) {
export async function cli(task, opts) {
await task
.source('src/cli/**/*.+(js|ts|tsx)')
.source('src/cli/**/*.+(js|ts|tsx)', {
ignore: ['src/cli/tui/**/*'],
})
.swc('server', { dev: opts.dev })
.target('dist/cli')
}
// TUI is bundled with rspack including ink and react for full isolation
export async function next_tui(task, opts) {
await task.source('src/cli/tui').webpack({
watch: opts.dev,
config: require('./tui.webpack-config')(),
name: 'bundle-tui',
})
}
export async function lib(task, opts) {
await task
.source('src/lib/**/!(*.test).+(js|ts|tsx|json|jsonc)')
......
// eslint-disable-next-line import/no-extraneous-dependencies
const webpack = require('@rspack/core')
const path = require('path')
/**
* @returns {webpack.Configuration}
*/
module.exports = () => {
return {
entry: {
index: path.join(__dirname, 'src/cli/tui/index.tsx'),
},
target: 'node',
mode: 'production',
output: {
path: path.join(__dirname, 'dist/compiled/tui'),
filename: '[name].mjs',
library: {
type: 'module',
},
chunkFormat: 'module',
module: true,
},
experiments: {
outputModule: true,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
alias: {
// Force production builds of React to avoid development-only initialization issues
'react/jsx-runtime': require.resolve('react/jsx-runtime'),
'react/jsx-dev-runtime': require.resolve('react/jsx-runtime'),
},
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
runtime: 'automatic',
development: false,
},
},
},
},
},
},
],
},
plugins: [
// Define NODE_ENV to ensure production builds of React packages are used
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
],
// Bundle everything including React for full isolation
externals: [],
optimization: {
minimize: false,
splitChunks: false,
concatenateModules: false,
},
}
}
......@@ -673,6 +673,24 @@ declare module 'next/dist/compiled/ora' {
import m from 'ora'
export = m
}
// TUI module type declaration (bundled with ink as ESM)
declare module 'next/dist/compiled/tui/index.mjs' {
import type { ChildProcess } from 'child_process'
export interface TuiInstance {
unmount: () => void
waitUntilExit: () => Promise<void>
}
export function startTui(
child: ChildProcess,
serverUrl: string,
distDir: string
): TuiInstance
}
// ink types for TUI (ESM module, re-export from actual package types)
declare module 'ink' {
export * from 'ink/build/index'
}
declare module 'next/dist/compiled/path-to-regexp' {
import m from 'path-to-regexp'
export = m
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment