diff --git a/node_modules/next/dist/cli/next-dev.js b/node_modules/next/dist/cli/next-dev.js index 8457acd..a5cdfdb 100644 --- a/node_modules/next/dist/cli/next-dev.js +++ b/node_modules/next/dist/cli/next-dev.js @@ -277,27 +277,27 @@ const nextDev = async (options, portSource, directory)=>{ const totalMem = _os.default.totalmem(); const totalMemInMB = Math.floor(totalMem / 1024 / 1024); maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString(); - nodeOptions['max-old-space-size'] = maxOldSpaceSize; + nodeOptions.set('max-old-space-size', maxOldSpaceSize); // Ensure the max_old_space_size is not also set. - delete nodeOptions['max_old_space_size']; + nodeOptions.delete('max_old_space_size'); } if (options.disableSourceMaps) { - delete nodeOptions['enable-source-maps']; + nodeOptions.delete('enable-source-maps'); } else { - nodeOptions['enable-source-maps'] = true; + nodeOptions.set('enable-source-maps', true); } const nodeDebugType = (0, _utils.getNodeDebugType)(nodeOptions); - const originalAddress = nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType]; - delete nodeOptions.inspect; - delete nodeOptions['inspect-brk']; - delete nodeOptions['inspect_brk']; + const originalAddress = nodeDebugType === undefined ? undefined : nodeOptions.get(nodeDebugType); + nodeOptions.delete('inspect'); + nodeOptions.delete('inspect-brk'); + nodeOptions.delete('inspect_brk'); if (nodeDebugType !== undefined) { const address = (0, _utils.getParsedDebugAddress)(originalAddress); address.port = address.port === 0 ? 0 : address.port + 1; - nodeOptions[nodeDebugType] = (0, _utils.formatDebugAddress)(address); + nodeOptions.set(nodeDebugType, (0, _utils.formatDebugAddress)(address)); } else if (options.inspect) { const address = options.inspect === true ? (0, _utils.getParsedDebugAddress)(true) : options.inspect; - nodeOptions.inspect = (0, _utils.formatDebugAddress)(address); + nodeOptions.set('inspect', (0, _utils.formatDebugAddress)(address)); } const { nodeOptions: formattedNodeOptions, execArgv } = (0, _utils.formatNodeOptions)(nodeOptions); child = (0, _child_process.fork)(startServerPath, { diff --git a/node_modules/next/dist/cli/next-dev.js.map b/node_modules/next/dist/cli/next-dev.js.map index 4fdd724..0ecd681 100644 --- a/node_modules/next/dist/cli/next-dev.js.map +++ b/node_modules/next/dist/cli/next-dev.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/cli/next-dev.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport '../server/lib/cpu-profile'\nimport { saveCpuProfile } from '../server/lib/cpu-profile'\nimport type { StartServerOptions } from '../server/lib/start-server'\nimport {\n RESTART_EXIT_CODE,\n getNodeDebugType,\n getParsedDebugAddress,\n getMaxOldSpaceSize,\n printAndExit,\n formatNodeOptions,\n formatDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\nimport * as Log from '../build/output/log'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport { ensureProfilesDir } from '../lib/profiles-dir'\nimport path from 'path'\nimport { traceGlobals } from '../trace/shared'\nimport { Telemetry } from '../telemetry/storage'\nimport { findPagesDir } from '../lib/find-pages-dir'\nimport { fileExists, FileType } from '../lib/file-exists'\nimport { getNpxCommand } from '../lib/helpers/get-npx-command'\nimport { createSelfSignedCertificate } from '../lib/mkcert'\nimport type { SelfSignedCertificate } from '../lib/mkcert'\nimport uploadTrace from '../trace/upload-trace'\nimport { initialEnv } from '@next/env'\nimport { fork } from 'child_process'\nimport type { ChildProcess } from 'child_process'\nimport {\n getReservedPortExplanation,\n isPortIsReserved,\n} from '../lib/helpers/get-reserved-port'\nimport { getCacheDirectory } from '../lib/helpers/get-cache-directory'\nimport { getGitBranch } from '../lib/helpers/git'\nimport os from 'os'\nimport fs from 'node:fs'\nimport { once } from 'node:events'\nimport { clearTimeout } from 'timers'\nimport { trace, initializeTraceState, exportTraceState } from '../trace'\nimport { traceId } from '../trace/shared'\nimport { Bundler, parseBundlerArgs } from '../lib/bundler'\n\nexport type NextDevOptions = {\n disableSourceMaps: boolean\n // Commander is not putting `--inspect` through the arg parser\n inspect?: DebugAddress | true\n turbo?: boolean\n turbopack?: boolean\n webpack?: boolean\n port: number\n hostname?: string\n experimentalHttps?: boolean\n experimentalHttpsKey?: string\n experimentalHttpsCert?: string\n experimentalHttpsCa?: string\n experimentalUploadTrace?: string\n experimentalNextConfigStripTypes?: boolean\n experimentalCpuProf?: boolean\n serverFastRefresh?: boolean\n internalTrace?: string | boolean\n}\n\ntype PortSource = 'cli' | 'default' | 'env'\n\nlet dir: string\nlet child: undefined | ChildProcess\n// distDir is received from the child process via IPC, used for telemetry and trace.\nlet distDir: string | undefined\nlet isTurbopack: boolean\nlet traceUploadUrl: string\nlet sessionStopHandled = false\nlet devSpanAttrs: { 'rage-restart': boolean; 'missing-next-dir': boolean } = {\n 'rage-restart': false,\n 'missing-next-dir': false,\n}\nconst sessionStarted = Date.now()\nconst sessionSpan = trace('next-dev')\n\n// If the user restarts the dev server within this window we count it as a \"rage restart\".\nconst RAGE_RESTART_THRESHOLD_MS = 90_000\n\n// Shape of a single project entry in the dev-state.json file.\n// All fields are optional so older entries without gitBranch are still valid.\ntype DevStateEntry = {\n stopTime?: number\n distDirPath?: string\n gitBranch?: string\n}\n\n// Single shared file for all projects — keyed by project directory path.\nconst DEV_STATE_FILE = path.join(\n getCacheDirectory('nextjs-nodejs'),\n 'dev-state.json'\n)\n\n// How long should we wait for the child to cleanly exit after sending\n// SIGINT/SIGTERM to the child process before sending SIGKILL?\nconst CHILD_EXIT_TIMEOUT_MS = parseInt(\n process.env.NEXT_EXIT_TIMEOUT_MS ?? '100',\n 10\n)\n\nconst handleSessionStop = async (signal: NodeJS.Signals | number | null) => {\n if (signal != null && child?.pid) child.kill(signal)\n if (sessionStopHandled) return\n sessionStopHandled = true\n\n // Capture the child's exit code if it has already exited and caused the\n // session stop (via the 'exit' event), otherwise assume success (0).\n const exitCode = child?.exitCode || 0\n\n if (\n signal != null &&\n child?.pid &&\n child.exitCode === null &&\n child.signalCode === null\n ) {\n let exitTimeout = setTimeout(() => {\n child?.kill('SIGKILL')\n }, CHILD_EXIT_TIMEOUT_MS)\n await once(child, 'exit').catch(() => {})\n clearTimeout(exitTimeout)\n }\n\n sessionSpan.stop()\n\n try {\n const { eventCliSessionStopped } =\n require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped')\n\n let pagesDir: boolean = !!traceGlobals.get('pagesDir')\n let appDir: boolean = !!traceGlobals.get('appDir')\n\n if (\n typeof traceGlobals.get('pagesDir') === 'undefined' ||\n typeof traceGlobals.get('appDir') === 'undefined'\n ) {\n const pagesResult = findPagesDir(dir)\n appDir = !!pagesResult.appDir\n pagesDir = !!pagesResult.pagesDir\n }\n\n const telemetry =\n (traceGlobals.get('telemetry') as InstanceType<\n typeof import('../telemetry/storage').Telemetry\n >) ||\n new Telemetry({\n distDir: path.join(dir, distDir || '.next'),\n })\n\n telemetry.record(\n eventCliSessionStopped({\n cliCommand: 'dev',\n turboFlag: isTurbopack,\n durationMilliseconds: Date.now() - sessionStarted,\n pagesDir,\n appDir,\n }),\n true\n )\n telemetry.flushDetached('dev', dir)\n } catch (_) {\n // errors here aren't actionable so don't add\n // noise to the output\n }\n\n if (traceUploadUrl && distDir) {\n uploadTrace({\n traceUploadUrl,\n mode: 'dev',\n projectDir: dir,\n distDir,\n isTurboSession: isTurbopack,\n })\n\n writeDevState()\n }\n\n // Save CPU profile if it was enabled (before exiting)\n saveCpuProfile()\n\n // ensure we re-enable the terminal cursor before exiting\n // the program, or the cursor could remain hidden\n process.stdout.write('\\x1B[?25h')\n process.stdout.write('\\n')\n process.exit(exitCode)\n}\n\nprocess.on('SIGINT', () => handleSessionStop('SIGINT'))\nprocess.on('SIGTERM', () => handleSessionStop('SIGTERM'))\n\n// exit event must be synchronous\nprocess.on('exit', () => {\n child?.kill('SIGKILL')\n // Catch aggressive kills (e.g. OOM, unhandled exception) that bypass handleSessionStop.\n // SIGKILL of the parent cannot be caught; for all other exits this ensures state is written.\n if (!sessionStopHandled) {\n writeDevState()\n }\n})\n\nconst nextDev = async (\n options: NextDevOptions,\n portSource: PortSource,\n directory?: string\n) => {\n // Note: parseBundlerArgs can only decide on Turbopack or webpack.\n // Rspack can be configured via next.config.js but next.config.js is not loaded in the main process, only in the child process.\n isTurbopack = parseBundlerArgs(options) === Bundler.Turbopack\n\n dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || directory)\n\n // Check if pages dir exists and warn if not\n if (!(await fileExists(dir, FileType.Directory))) {\n printAndExit(`> No such directory exists as the project root: ${dir}`)\n }\n\n if (options.experimentalCpuProf) {\n Log.info(\n `CPU profiling enabled. Profile will be saved to .next-profiles/ on exit (Ctrl+C).`\n )\n }\n\n async function preflight(skipOnReboot: boolean) {\n const { getPackageVersion, getDependencies } = (await Promise.resolve(\n require('../lib/get-package-version') as typeof import('../lib/get-package-version')\n )) as typeof import('../lib/get-package-version')\n\n const [sassVersion, nodeSassVersion] = await Promise.all([\n getPackageVersion({ cwd: dir, name: 'sass' }),\n getPackageVersion({ cwd: dir, name: 'node-sass' }),\n ])\n if (sassVersion && nodeSassVersion) {\n Log.warn(\n 'Your project has both `sass` and `node-sass` installed as dependencies, but should only use one or the other. ' +\n 'Please remove the `node-sass` dependency from your project. ' +\n ' Read more: https://nextjs.org/docs/messages/duplicate-sass'\n )\n }\n\n if (!skipOnReboot) {\n const { dependencies, devDependencies } = await getDependencies({\n cwd: dir,\n })\n\n // Warn if @next/font is installed as a dependency. Ignore `workspace:*` to not warn in the Next.js monorepo.\n if (\n dependencies['@next/font'] ||\n (devDependencies['@next/font'] &&\n devDependencies['@next/font'] !== 'workspace:*')\n ) {\n const command = getNpxCommand(dir)\n Log.warn(\n 'Your project has `@next/font` installed as a dependency, please use the built-in `next/font` instead. ' +\n 'The `@next/font` package will be removed in Next.js 14. ' +\n `You can migrate by running \\`${command} @next/codemod@latest built-in-next-font .\\`. Read more: https://nextjs.org/docs/messages/built-in-next-font`\n )\n }\n }\n }\n\n let port = options.port\n\n if (isPortIsReserved(port)) {\n printAndExit(getReservedPortExplanation(port), 1)\n }\n\n // If neither --port nor PORT were specified, it's okay to retry new ports.\n const allowRetry = portSource === 'default'\n\n // We do not set a default host value here to prevent breaking\n // some set-ups that rely on listening on other interfaces\n const host = options.hostname\n\n if (\n options.experimentalUploadTrace &&\n !process.env.NEXT_TRACE_UPLOAD_DISABLED\n ) {\n traceUploadUrl = options.experimentalUploadTrace\n }\n\n if (traceUploadUrl) {\n let isRageRestart = false\n let distDirCleared = false\n try {\n if (fs.existsSync(DEV_STATE_FILE)) {\n const allState = JSON.parse(\n fs.readFileSync(DEV_STATE_FILE, 'utf8')\n ) as Record\n const state = allState[dir]\n if (\n state?.stopTime &&\n Date.now() - state.stopTime < RAGE_RESTART_THRESHOLD_MS\n ) {\n // Only flag as a rage restart if the git branch hasn't changed. If\n // either the stored or current branch is unknown, skip the comparison\n // and fall back to time-only detection.\n const storedBranch = state.gitBranch\n const currentBranch = getGitBranch(dir)\n const branchChanged =\n storedBranch && currentBranch && storedBranch !== currentBranch\n if (!branchChanged) {\n isRageRestart = true\n }\n }\n if (state?.distDirPath && !fs.existsSync(state.distDirPath)) {\n distDirCleared = true\n }\n }\n } catch {\n // Corrupt file — leave both flags false\n }\n devSpanAttrs = {\n 'rage-restart': isRageRestart,\n 'missing-next-dir': distDirCleared,\n }\n }\n\n const enabledFeatures = Object.fromEntries(\n Object.entries({\n serverFastRefreshDisabled: options.serverFastRefresh === false,\n experimentalCpuProf: options.experimentalCpuProf,\n }).filter(([_, value]) => value)\n )\n\n for (const [key, value] of Object.entries(enabledFeatures)) {\n sessionSpan.setAttribute(`feature.${key}`, value)\n }\n\n initializeTraceState({\n ...exportTraceState(),\n defaultParentSpanId: sessionSpan.getId(),\n })\n\n const devServerOptions: StartServerOptions = {\n dir,\n port,\n allowRetry,\n isDev: true,\n hostname: host,\n serverFastRefresh: options.serverFastRefresh,\n }\n\n const startServerPath = require.resolve('../server/lib/start-server')\n\n async function startServer(startServerOptions: StartServerOptions) {\n return new Promise((resolve) => {\n let resolved = false\n const defaultEnv = (initialEnv || process.env) as typeof process.env\n\n const nodeOptions = getParsedNodeOptions()\n\n let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()\n if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {\n const totalMem = os.totalmem()\n const totalMemInMB = Math.floor(totalMem / 1024 / 1024)\n maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString()\n\n nodeOptions['max-old-space-size'] = maxOldSpaceSize\n\n // Ensure the max_old_space_size is not also set.\n delete nodeOptions['max_old_space_size']\n }\n\n if (options.disableSourceMaps) {\n delete nodeOptions['enable-source-maps']\n } else {\n nodeOptions['enable-source-maps'] = true\n }\n\n const nodeDebugType = getNodeDebugType(nodeOptions)\n const originalAddress =\n nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType]\n delete nodeOptions.inspect\n delete nodeOptions['inspect-brk']\n delete nodeOptions['inspect_brk']\n if (nodeDebugType !== undefined) {\n const address = getParsedDebugAddress(originalAddress)\n address.port = address.port === 0 ? 0 : address.port + 1\n nodeOptions[nodeDebugType] = formatDebugAddress(address)\n } else if (options.inspect) {\n const address: DebugAddress =\n options.inspect === true\n ? getParsedDebugAddress(true)\n : options.inspect\n nodeOptions.inspect = formatDebugAddress(address)\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n child = fork(startServerPath, {\n stdio: 'inherit',\n execArgv,\n env: {\n ...defaultEnv,\n ...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),\n __NEXT_DEV_SERVER: '1',\n NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,\n NEXT_PRIVATE_WORKER: '1',\n NEXT_PRIVATE_TRACE_ID: traceId,\n NEXT_PRIVATE_ENABLED_FEATURES: JSON.stringify(enabledFeatures),\n NEXT_PRIVATE_DEV_SPAN_ATTRS: JSON.stringify(devSpanAttrs),\n NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate\n ? startServerOptions.selfSignedCertificate.rootCA\n : defaultEnv.NODE_EXTRA_CA_CERTS,\n NODE_OPTIONS: formattedNodeOptions,\n // There is a node.js bug on MacOS which causes closing file watchers to be really slow.\n // This limits the number of watchers x mitigate the issue.\n // https://github.com/nodejs/node/issues/29949\n WATCHPACK_WATCHER_LIMIT:\n os.platform() === 'darwin' ? '20' : undefined,\n // Enable CPU profiling if requested\n ...(options.experimentalCpuProf\n ? {\n NEXT_CPU_PROF: '1',\n NEXT_CPU_PROF_DIR: ensureProfilesDir(dir),\n __NEXT_PRIVATE_CPU_PROFILE: 'dev-server',\n }\n : undefined),\n ...(process.env.NEXT_TURBOPACK_TRACING\n ? { NEXT_TURBOPACK_TRACING: process.env.NEXT_TURBOPACK_TRACING }\n : undefined),\n },\n })\n\n child.on('message', (msg: any) => {\n if (msg && typeof msg === 'object') {\n if (msg.nextWorkerReady) {\n child?.send({ nextWorkerOptions: startServerOptions })\n } else if (msg.nextServerReady && !resolved) {\n if (msg.port) {\n // Store the used port in case a random one was selected, so that\n // it can be re-used on automatic dev server restarts.\n port = parseInt(msg.port, 10)\n }\n if (msg.distDir) {\n // Store the distDir from the child process for telemetry and trace uploads.\n distDir = msg.distDir\n }\n\n resolved = true\n resolve()\n }\n }\n })\n\n child.on('exit', async (code, signal) => {\n if (sessionStopHandled || signal) {\n return\n }\n if (code === RESTART_EXIT_CODE) {\n // Starting the dev server will overwrite the `.next/trace` file, so we\n // must upload the existing contents before restarting the server to\n // preserve the metrics.\n if (traceUploadUrl && distDir) {\n uploadTrace({\n traceUploadUrl,\n mode: 'dev',\n projectDir: dir,\n distDir,\n isTurboSession: isTurbopack,\n sync: true,\n })\n }\n\n // Reset the start time so \"Ready in X\" reflects the restart\n // duration, not time since the original process started.\n process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()\n\n return startServer({ ...startServerOptions, port })\n }\n // Call handler (e.g. upload telemetry). Don't try to send a signal to\n // the child, as it has already exited.\n await handleSessionStop(/* signal */ null)\n })\n })\n }\n\n const runDevServer = async (reboot: boolean) => {\n try {\n if (!!options.experimentalHttps) {\n Log.warn(\n 'Self-signed certificates are currently an experimental feature, use with caution.'\n )\n\n let certificate: SelfSignedCertificate | undefined\n\n const key = options.experimentalHttpsKey\n const cert = options.experimentalHttpsCert\n const rootCA = options.experimentalHttpsCa\n\n if (key && cert) {\n certificate = {\n key: path.resolve(key),\n cert: path.resolve(cert),\n rootCA: rootCA ? path.resolve(rootCA) : undefined,\n }\n } else {\n certificate = await createSelfSignedCertificate(host)\n }\n\n await startServer({\n ...devServerOptions,\n selfSignedCertificate: certificate,\n })\n } else {\n await startServer(devServerOptions)\n }\n\n await preflight(reboot)\n } catch (err) {\n console.error(err)\n process.exit(1)\n }\n }\n\n await runDevServer(false)\n}\n\nfunction writeDevState(): void {\n if (!traceUploadUrl || !dir) return\n try {\n fs.mkdirSync(path.dirname(DEV_STATE_FILE), { recursive: true })\n\n let state: Record = {}\n try {\n state = JSON.parse(fs.readFileSync(DEV_STATE_FILE, 'utf8'))\n } catch {\n // File missing or corrupt — start with empty state\n }\n\n // Eagerly remove entries that are stale (older than threshold) or invalid\n // (future timestamps from clock skew or corruption).\n const now = Date.now()\n const cutoff = now - RAGE_RESTART_THRESHOLD_MS\n for (const key of Object.keys(state)) {\n const t = state[key]?.stopTime\n if (!t || t < cutoff || t > now) {\n delete state[key]\n }\n }\n\n // Update current project\n const gitBranch = getGitBranch(dir)\n state[dir] = {\n stopTime: Date.now(),\n distDirPath: path.join(dir, distDir ?? '.next'),\n ...(gitBranch ? { gitBranch } : {}),\n }\n\n const { sync: writeFileAtomicSync } =\n require('next/dist/compiled/write-file-atomic') as typeof import('next/dist/compiled/write-file-atomic')\n writeFileAtomicSync(DEV_STATE_FILE, JSON.stringify(state))\n } catch {\n // Best effort — don't interfere with shutdown\n }\n}\n\nexport { nextDev }\n"],"names":["nextDev","dir","child","distDir","isTurbopack","traceUploadUrl","sessionStopHandled","devSpanAttrs","sessionStarted","Date","now","sessionSpan","trace","RAGE_RESTART_THRESHOLD_MS","DEV_STATE_FILE","path","join","getCacheDirectory","CHILD_EXIT_TIMEOUT_MS","parseInt","process","env","NEXT_EXIT_TIMEOUT_MS","handleSessionStop","signal","pid","kill","exitCode","signalCode","exitTimeout","setTimeout","once","catch","clearTimeout","stop","eventCliSessionStopped","require","pagesDir","traceGlobals","get","appDir","pagesResult","findPagesDir","telemetry","Telemetry","record","cliCommand","turboFlag","durationMilliseconds","flushDetached","_","uploadTrace","mode","projectDir","isTurboSession","writeDevState","saveCpuProfile","stdout","write","exit","on","options","portSource","directory","parseBundlerArgs","Bundler","Turbopack","getProjectDir","NEXT_PRIVATE_DEV_DIR","fileExists","FileType","Directory","printAndExit","experimentalCpuProf","Log","info","preflight","skipOnReboot","getPackageVersion","getDependencies","Promise","resolve","sassVersion","nodeSassVersion","all","cwd","name","warn","dependencies","devDependencies","command","getNpxCommand","port","isPortIsReserved","getReservedPortExplanation","allowRetry","host","hostname","experimentalUploadTrace","NEXT_TRACE_UPLOAD_DISABLED","isRageRestart","distDirCleared","fs","existsSync","allState","JSON","parse","readFileSync","state","stopTime","storedBranch","gitBranch","currentBranch","getGitBranch","branchChanged","distDirPath","enabledFeatures","Object","fromEntries","entries","serverFastRefreshDisabled","serverFastRefresh","filter","value","key","setAttribute","initializeTraceState","exportTraceState","defaultParentSpanId","getId","devServerOptions","isDev","startServerPath","startServer","startServerOptions","resolved","defaultEnv","initialEnv","nodeOptions","getParsedNodeOptions","maxOldSpaceSize","getMaxOldSpaceSize","NEXT_DISABLE_MEM_OVERRIDE","totalMem","os","totalmem","totalMemInMB","Math","floor","toString","disableSourceMaps","nodeDebugType","getNodeDebugType","originalAddress","undefined","inspect","address","getParsedDebugAddress","formatDebugAddress","formattedNodeOptions","execArgv","formatNodeOptions","fork","stdio","TURBOPACK","__NEXT_DEV_SERVER","NEXT_PRIVATE_START_TIME","NEXT_PRIVATE_WORKER","NEXT_PRIVATE_TRACE_ID","traceId","NEXT_PRIVATE_ENABLED_FEATURES","stringify","NEXT_PRIVATE_DEV_SPAN_ATTRS","NODE_EXTRA_CA_CERTS","selfSignedCertificate","rootCA","NODE_OPTIONS","WATCHPACK_WATCHER_LIMIT","platform","NEXT_CPU_PROF","NEXT_CPU_PROF_DIR","ensureProfilesDir","__NEXT_PRIVATE_CPU_PROFILE","NEXT_TURBOPACK_TRACING","msg","nextWorkerReady","send","nextWorkerOptions","nextServerReady","code","RESTART_EXIT_CODE","sync","runDevServer","reboot","experimentalHttps","certificate","experimentalHttpsKey","cert","experimentalHttpsCert","experimentalHttpsCa","createSelfSignedCertificate","err","console","error","mkdirSync","dirname","recursive","cutoff","keys","t","writeFileAtomicSync"],"mappings":";;;;;+BAkjBSA;;;eAAAA;;;4BAhjBF;uBAaA;6DACc;+BACS;6BACI;6DACjB;wBACY;yBACH;8BACG;4BACQ;+BACP;wBACc;oEAEpB;qBACG;+BACN;iCAKd;mCAC2B;qBACL;2DACd;+DACA;4BACM;wBACQ;uBACiC;yBAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwB1C,IAAIC;AACJ,IAAIC;AACJ,oFAAoF;AACpF,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AACJ,IAAIC,qBAAqB;AACzB,IAAIC,eAAyE;IAC3E,gBAAgB;IAChB,oBAAoB;AACtB;AACA,MAAMC,iBAAiBC,KAAKC,GAAG;AAC/B,MAAMC,cAAcC,IAAAA,YAAK,EAAC;AAE1B,0FAA0F;AAC1F,MAAMC,4BAA4B;AAUlC,yEAAyE;AACzE,MAAMC,iBAAiBC,aAAI,CAACC,IAAI,CAC9BC,IAAAA,oCAAiB,EAAC,kBAClB;AAGF,sEAAsE;AACtE,8DAA8D;AAC9D,MAAMC,wBAAwBC,SAC5BC,QAAQC,GAAG,CAACC,oBAAoB,IAAI,OACpC;AAGF,MAAMC,oBAAoB,OAAOC;IAC/B,IAAIA,UAAU,SAAQtB,yBAAAA,MAAOuB,GAAG,GAAEvB,MAAMwB,IAAI,CAACF;IAC7C,IAAIlB,oBAAoB;IACxBA,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kE,SAAS,CAAC/D;IACrD,EAAE,OAAM;IACN,8CAA8C;IAChD;AACF","ignoreList":[0]} \ No newline at end of file +{"version":3,"sources":["../../src/cli/next-dev.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport '../server/lib/cpu-profile'\nimport { saveCpuProfile } from '../server/lib/cpu-profile'\nimport type { StartServerOptions } from '../server/lib/start-server'\nimport {\n RESTART_EXIT_CODE,\n getNodeDebugType,\n getParsedDebugAddress,\n getMaxOldSpaceSize,\n printAndExit,\n formatNodeOptions,\n formatDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\nimport * as Log from '../build/output/log'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport { ensureProfilesDir } from '../lib/profiles-dir'\nimport path from 'path'\nimport { traceGlobals } from '../trace/shared'\nimport { Telemetry } from '../telemetry/storage'\nimport { findPagesDir } from '../lib/find-pages-dir'\nimport { fileExists, FileType } from '../lib/file-exists'\nimport { getNpxCommand } from '../lib/helpers/get-npx-command'\nimport { createSelfSignedCertificate } from '../lib/mkcert'\nimport type { SelfSignedCertificate } from '../lib/mkcert'\nimport uploadTrace from '../trace/upload-trace'\nimport { initialEnv } from '@next/env'\nimport { fork } from 'child_process'\nimport type { ChildProcess } from 'child_process'\nimport {\n getReservedPortExplanation,\n isPortIsReserved,\n} from '../lib/helpers/get-reserved-port'\nimport { getCacheDirectory } from '../lib/helpers/get-cache-directory'\nimport { getGitBranch } from '../lib/helpers/git'\nimport os from 'os'\nimport fs from 'node:fs'\nimport { once } from 'node:events'\nimport { clearTimeout } from 'timers'\nimport { trace, initializeTraceState, exportTraceState } from '../trace'\nimport { traceId } from '../trace/shared'\nimport { Bundler, parseBundlerArgs } from '../lib/bundler'\n\nexport type NextDevOptions = {\n disableSourceMaps: boolean\n // Commander is not putting `--inspect` through the arg parser\n inspect?: DebugAddress | true\n turbo?: boolean\n turbopack?: boolean\n webpack?: boolean\n port: number\n hostname?: string\n experimentalHttps?: boolean\n experimentalHttpsKey?: string\n experimentalHttpsCert?: string\n experimentalHttpsCa?: string\n experimentalUploadTrace?: string\n experimentalNextConfigStripTypes?: boolean\n experimentalCpuProf?: boolean\n serverFastRefresh?: boolean\n internalTrace?: string | boolean\n}\n\ntype PortSource = 'cli' | 'default' | 'env'\n\nlet dir: string\nlet child: undefined | ChildProcess\n// distDir is received from the child process via IPC, used for telemetry and trace.\nlet distDir: string | undefined\nlet isTurbopack: boolean\nlet traceUploadUrl: string\nlet sessionStopHandled = false\nlet devSpanAttrs: { 'rage-restart': boolean; 'missing-next-dir': boolean } = {\n 'rage-restart': false,\n 'missing-next-dir': false,\n}\nconst sessionStarted = Date.now()\nconst sessionSpan = trace('next-dev')\n\n// If the user restarts the dev server within this window we count it as a \"rage restart\".\nconst RAGE_RESTART_THRESHOLD_MS = 90_000\n\n// Shape of a single project entry in the dev-state.json file.\n// All fields are optional so older entries without gitBranch are still valid.\ntype DevStateEntry = {\n stopTime?: number\n distDirPath?: string\n gitBranch?: string\n}\n\n// Single shared file for all projects — keyed by project directory path.\nconst DEV_STATE_FILE = path.join(\n getCacheDirectory('nextjs-nodejs'),\n 'dev-state.json'\n)\n\n// How long should we wait for the child to cleanly exit after sending\n// SIGINT/SIGTERM to the child process before sending SIGKILL?\nconst CHILD_EXIT_TIMEOUT_MS = parseInt(\n process.env.NEXT_EXIT_TIMEOUT_MS ?? '100',\n 10\n)\n\nconst handleSessionStop = async (signal: NodeJS.Signals | number | null) => {\n if (signal != null && child?.pid) child.kill(signal)\n if (sessionStopHandled) return\n sessionStopHandled = true\n\n // Capture the child's exit code if it has already exited and caused the\n // session stop (via the 'exit' event), otherwise assume success (0).\n const exitCode = child?.exitCode || 0\n\n if (\n signal != null &&\n child?.pid &&\n child.exitCode === null &&\n child.signalCode === null\n ) {\n let exitTimeout = setTimeout(() => {\n child?.kill('SIGKILL')\n }, CHILD_EXIT_TIMEOUT_MS)\n await once(child, 'exit').catch(() => {})\n clearTimeout(exitTimeout)\n }\n\n sessionSpan.stop()\n\n try {\n const { eventCliSessionStopped } =\n require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped')\n\n let pagesDir: boolean = !!traceGlobals.get('pagesDir')\n let appDir: boolean = !!traceGlobals.get('appDir')\n\n if (\n typeof traceGlobals.get('pagesDir') === 'undefined' ||\n typeof traceGlobals.get('appDir') === 'undefined'\n ) {\n const pagesResult = findPagesDir(dir)\n appDir = !!pagesResult.appDir\n pagesDir = !!pagesResult.pagesDir\n }\n\n const telemetry =\n (traceGlobals.get('telemetry') as InstanceType<\n typeof import('../telemetry/storage').Telemetry\n >) ||\n new Telemetry({\n distDir: path.join(dir, distDir || '.next'),\n })\n\n telemetry.record(\n eventCliSessionStopped({\n cliCommand: 'dev',\n turboFlag: isTurbopack,\n durationMilliseconds: Date.now() - sessionStarted,\n pagesDir,\n appDir,\n }),\n true\n )\n telemetry.flushDetached('dev', dir)\n } catch (_) {\n // errors here aren't actionable so don't add\n // noise to the output\n }\n\n if (traceUploadUrl && distDir) {\n uploadTrace({\n traceUploadUrl,\n mode: 'dev',\n projectDir: dir,\n distDir,\n isTurboSession: isTurbopack,\n })\n\n writeDevState()\n }\n\n // Save CPU profile if it was enabled (before exiting)\n saveCpuProfile()\n\n // ensure we re-enable the terminal cursor before exiting\n // the program, or the cursor could remain hidden\n process.stdout.write('\\x1B[?25h')\n process.stdout.write('\\n')\n process.exit(exitCode)\n}\n\nprocess.on('SIGINT', () => handleSessionStop('SIGINT'))\nprocess.on('SIGTERM', () => handleSessionStop('SIGTERM'))\n\n// exit event must be synchronous\nprocess.on('exit', () => {\n child?.kill('SIGKILL')\n // Catch aggressive kills (e.g. OOM, unhandled exception) that bypass handleSessionStop.\n // SIGKILL of the parent cannot be caught; for all other exits this ensures state is written.\n if (!sessionStopHandled) {\n writeDevState()\n }\n})\n\nconst nextDev = async (\n options: NextDevOptions,\n portSource: PortSource,\n directory?: string\n) => {\n // Note: parseBundlerArgs can only decide on Turbopack or webpack.\n // Rspack can be configured via next.config.js but next.config.js is not loaded in the main process, only in the child process.\n isTurbopack = parseBundlerArgs(options) === Bundler.Turbopack\n\n dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || directory)\n\n // Check if pages dir exists and warn if not\n if (!(await fileExists(dir, FileType.Directory))) {\n printAndExit(`> No such directory exists as the project root: ${dir}`)\n }\n\n if (options.experimentalCpuProf) {\n Log.info(\n `CPU profiling enabled. Profile will be saved to .next-profiles/ on exit (Ctrl+C).`\n )\n }\n\n async function preflight(skipOnReboot: boolean) {\n const { getPackageVersion, getDependencies } = (await Promise.resolve(\n require('../lib/get-package-version') as typeof import('../lib/get-package-version')\n )) as typeof import('../lib/get-package-version')\n\n const [sassVersion, nodeSassVersion] = await Promise.all([\n getPackageVersion({ cwd: dir, name: 'sass' }),\n getPackageVersion({ cwd: dir, name: 'node-sass' }),\n ])\n if (sassVersion && nodeSassVersion) {\n Log.warn(\n 'Your project has both `sass` and `node-sass` installed as dependencies, but should only use one or the other. ' +\n 'Please remove the `node-sass` dependency from your project. ' +\n ' Read more: https://nextjs.org/docs/messages/duplicate-sass'\n )\n }\n\n if (!skipOnReboot) {\n const { dependencies, devDependencies } = await getDependencies({\n cwd: dir,\n })\n\n // Warn if @next/font is installed as a dependency. Ignore `workspace:*` to not warn in the Next.js monorepo.\n if (\n dependencies['@next/font'] ||\n (devDependencies['@next/font'] &&\n devDependencies['@next/font'] !== 'workspace:*')\n ) {\n const command = getNpxCommand(dir)\n Log.warn(\n 'Your project has `@next/font` installed as a dependency, please use the built-in `next/font` instead. ' +\n 'The `@next/font` package will be removed in Next.js 14. ' +\n `You can migrate by running \\`${command} @next/codemod@latest built-in-next-font .\\`. Read more: https://nextjs.org/docs/messages/built-in-next-font`\n )\n }\n }\n }\n\n let port = options.port\n\n if (isPortIsReserved(port)) {\n printAndExit(getReservedPortExplanation(port), 1)\n }\n\n // If neither --port nor PORT were specified, it's okay to retry new ports.\n const allowRetry = portSource === 'default'\n\n // We do not set a default host value here to prevent breaking\n // some set-ups that rely on listening on other interfaces\n const host = options.hostname\n\n if (\n options.experimentalUploadTrace &&\n !process.env.NEXT_TRACE_UPLOAD_DISABLED\n ) {\n traceUploadUrl = options.experimentalUploadTrace\n }\n\n if (traceUploadUrl) {\n let isRageRestart = false\n let distDirCleared = false\n try {\n if (fs.existsSync(DEV_STATE_FILE)) {\n const allState = JSON.parse(\n fs.readFileSync(DEV_STATE_FILE, 'utf8')\n ) as Record\n const state = allState[dir]\n if (\n state?.stopTime &&\n Date.now() - state.stopTime < RAGE_RESTART_THRESHOLD_MS\n ) {\n // Only flag as a rage restart if the git branch hasn't changed. If\n // either the stored or current branch is unknown, skip the comparison\n // and fall back to time-only detection.\n const storedBranch = state.gitBranch\n const currentBranch = getGitBranch(dir)\n const branchChanged =\n storedBranch && currentBranch && storedBranch !== currentBranch\n if (!branchChanged) {\n isRageRestart = true\n }\n }\n if (state?.distDirPath && !fs.existsSync(state.distDirPath)) {\n distDirCleared = true\n }\n }\n } catch {\n // Corrupt file — leave both flags false\n }\n devSpanAttrs = {\n 'rage-restart': isRageRestart,\n 'missing-next-dir': distDirCleared,\n }\n }\n\n const enabledFeatures = Object.fromEntries(\n Object.entries({\n serverFastRefreshDisabled: options.serverFastRefresh === false,\n experimentalCpuProf: options.experimentalCpuProf,\n }).filter(([_, value]) => value)\n )\n\n for (const [key, value] of Object.entries(enabledFeatures)) {\n sessionSpan.setAttribute(`feature.${key}`, value)\n }\n\n initializeTraceState({\n ...exportTraceState(),\n defaultParentSpanId: sessionSpan.getId(),\n })\n\n const devServerOptions: StartServerOptions = {\n dir,\n port,\n allowRetry,\n isDev: true,\n hostname: host,\n serverFastRefresh: options.serverFastRefresh,\n }\n\n const startServerPath = require.resolve('../server/lib/start-server')\n\n async function startServer(startServerOptions: StartServerOptions) {\n return new Promise((resolve) => {\n let resolved = false\n const defaultEnv = (initialEnv || process.env) as typeof process.env\n\n const nodeOptions = getParsedNodeOptions()\n\n let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()\n if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {\n const totalMem = os.totalmem()\n const totalMemInMB = Math.floor(totalMem / 1024 / 1024)\n maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString()\n\n nodeOptions.set('max-old-space-size', maxOldSpaceSize)\n\n // Ensure the max_old_space_size is not also set.\n nodeOptions.delete('max_old_space_size')\n }\n\n if (options.disableSourceMaps) {\n nodeOptions.delete('enable-source-maps')\n } else {\n nodeOptions.set('enable-source-maps', true)\n }\n\n const nodeDebugType = getNodeDebugType(nodeOptions)\n const originalAddress =\n nodeDebugType === undefined ? undefined : nodeOptions.get(nodeDebugType)\n nodeOptions.delete('inspect')\n nodeOptions.delete('inspect-brk')\n nodeOptions.delete('inspect_brk')\n if (nodeDebugType !== undefined) {\n const address = getParsedDebugAddress(originalAddress)\n address.port = address.port === 0 ? 0 : address.port + 1\n nodeOptions.set(nodeDebugType, formatDebugAddress(address))\n } else if (options.inspect) {\n const address: DebugAddress =\n options.inspect === true\n ? getParsedDebugAddress(true)\n : options.inspect\n nodeOptions.set('inspect', formatDebugAddress(address))\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n child = fork(startServerPath, {\n stdio: 'inherit',\n execArgv,\n env: {\n ...defaultEnv,\n ...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),\n __NEXT_DEV_SERVER: '1',\n NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,\n NEXT_PRIVATE_WORKER: '1',\n NEXT_PRIVATE_TRACE_ID: traceId,\n NEXT_PRIVATE_ENABLED_FEATURES: JSON.stringify(enabledFeatures),\n NEXT_PRIVATE_DEV_SPAN_ATTRS: JSON.stringify(devSpanAttrs),\n NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate\n ? startServerOptions.selfSignedCertificate.rootCA\n : defaultEnv.NODE_EXTRA_CA_CERTS,\n NODE_OPTIONS: formattedNodeOptions,\n // There is a node.js bug on MacOS which causes closing file watchers to be really slow.\n // This limits the number of watchers x mitigate the issue.\n // https://github.com/nodejs/node/issues/29949\n WATCHPACK_WATCHER_LIMIT:\n os.platform() === 'darwin' ? '20' : undefined,\n // Enable CPU profiling if requested\n ...(options.experimentalCpuProf\n ? {\n NEXT_CPU_PROF: '1',\n NEXT_CPU_PROF_DIR: ensureProfilesDir(dir),\n __NEXT_PRIVATE_CPU_PROFILE: 'dev-server',\n }\n : undefined),\n ...(process.env.NEXT_TURBOPACK_TRACING\n ? { NEXT_TURBOPACK_TRACING: process.env.NEXT_TURBOPACK_TRACING }\n : undefined),\n },\n })\n\n child.on('message', (msg: any) => {\n if (msg && typeof msg === 'object') {\n if (msg.nextWorkerReady) {\n child?.send({ nextWorkerOptions: startServerOptions })\n } else if (msg.nextServerReady && !resolved) {\n if (msg.port) {\n // Store the used port in case a random one was selected, so that\n // it can be re-used on automatic dev server restarts.\n port = parseInt(msg.port, 10)\n }\n if (msg.distDir) {\n // Store the distDir from the child process for telemetry and trace uploads.\n distDir = msg.distDir\n }\n\n resolved = true\n resolve()\n }\n }\n })\n\n child.on('exit', async (code, signal) => {\n if (sessionStopHandled || signal) {\n return\n }\n if (code === RESTART_EXIT_CODE) {\n // Starting the dev server will overwrite the `.next/trace` file, so we\n // must upload the existing contents before restarting the server to\n // preserve the metrics.\n if (traceUploadUrl && distDir) {\n uploadTrace({\n traceUploadUrl,\n mode: 'dev',\n projectDir: dir,\n distDir,\n isTurboSession: isTurbopack,\n sync: true,\n })\n }\n\n // Reset the start time so \"Ready in X\" reflects the restart\n // duration, not time since the original process started.\n process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()\n\n return startServer({ ...startServerOptions, port })\n }\n // Call handler (e.g. upload telemetry). Don't try to send a signal to\n // the child, as it has already exited.\n await handleSessionStop(/* signal */ null)\n })\n })\n }\n\n const runDevServer = async (reboot: boolean) => {\n try {\n if (!!options.experimentalHttps) {\n Log.warn(\n 'Self-signed certificates are currently an experimental feature, use with caution.'\n )\n\n let certificate: SelfSignedCertificate | undefined\n\n const key = options.experimentalHttpsKey\n const cert = options.experimentalHttpsCert\n const rootCA = options.experimentalHttpsCa\n\n if (key && cert) {\n certificate = {\n key: path.resolve(key),\n cert: path.resolve(cert),\n rootCA: rootCA ? path.resolve(rootCA) : undefined,\n }\n } else {\n certificate = await createSelfSignedCertificate(host)\n }\n\n await startServer({\n ...devServerOptions,\n selfSignedCertificate: certificate,\n })\n } else {\n await startServer(devServerOptions)\n }\n\n await preflight(reboot)\n } catch (err) {\n console.error(err)\n process.exit(1)\n }\n }\n\n await runDevServer(false)\n}\n\nfunction writeDevState(): void {\n if (!traceUploadUrl || !dir) return\n try {\n fs.mkdirSync(path.dirname(DEV_STATE_FILE), { recursive: true })\n\n let state: Record = {}\n try {\n state = JSON.parse(fs.readFileSync(DEV_STATE_FILE, 'utf8'))\n } catch {\n // File missing or corrupt — start with empty state\n }\n\n // Eagerly remove entries that are stale (older than threshold) or invalid\n // (future timestamps from clock skew or corruption).\n const now = Date.now()\n const cutoff = now - RAGE_RESTART_THRESHOLD_MS\n for (const key of Object.keys(state)) {\n const t = state[key]?.stopTime\n if (!t || t < cutoff || t > now) {\n delete state[key]\n }\n }\n\n // Update current project\n const gitBranch = getGitBranch(dir)\n state[dir] = {\n stopTime: Date.now(),\n distDirPath: path.join(dir, distDir ?? '.next'),\n ...(gitBranch ? { gitBranch } : {}),\n }\n\n const { sync: writeFileAtomicSync } =\n require('next/dist/compiled/write-file-atomic') as typeof import('next/dist/compiled/write-file-atomic')\n writeFileAtomicSync(DEV_STATE_FILE, JSON.stringify(state))\n } catch {\n // Best effort — don't interfere with shutdown\n }\n}\n\nexport { nextDev }\n"],"names":["nextDev","dir","child","distDir","isTurbopack","traceUploadUrl","sessionStopHandled","devSpanAttrs","sessionStarted","Date","now","sessionSpan","trace","RAGE_RESTART_THRESHOLD_MS","DEV_STATE_FILE","path","join","getCacheDirectory","CHILD_EXIT_TIMEOUT_MS","parseInt","process","env","NEXT_EXIT_TIMEOUT_MS","handleSessionStop","signal","pid","kill","exitCode","signalCode","exitTimeout","setTimeout","once","catch","clearTimeout","stop","eventCliSessionStopped","require","pagesDir","traceGlobals","get","appDir","pagesResult","findPagesDir","telemetry","Telemetry","record","cliCommand","turboFlag","durationMilliseconds","flushDetached","_","uploadTrace","mode","projectDir","isTurboSession","writeDevState","saveCpuProfile","stdout","write","exit","on","options","portSource","directory","parseBundlerArgs","Bundler","Turbopack","getProjectDir","NEXT_PRIVATE_DEV_DIR","fileExists","FileType","Directory","printAndExit","experimentalCpuProf","Log","info","preflight","skipOnReboot","getPackageVersion","getDependencies","Promise","resolve","sassVersion","nodeSassVersion","all","cwd","name","warn","dependencies","devDependencies","command","getNpxCommand","port","isPortIsReserved","getReservedPortExplanation","allowRetry","host","hostname","experimentalUploadTrace","NEXT_TRACE_UPLOAD_DISABLED","isRageRestart","distDirCleared","fs","existsSync","allState","JSON","parse","readFileSync","state","stopTime","storedBranch","gitBranch","currentBranch","getGitBranch","branchChanged","distDirPath","enabledFeatures","Object","fromEntries","entries","serverFastRefreshDisabled","serverFastRefresh","filter","value","key","setAttribute","initializeTraceState","exportTraceState","defaultParentSpanId","getId","devServerOptions","isDev","startServerPath","startServer","startServerOptions","resolved","defaultEnv","initialEnv","nodeOptions","getParsedNodeOptions","maxOldSpaceSize","getMaxOldSpaceSize","NEXT_DISABLE_MEM_OVERRIDE","totalMem","os","totalmem","totalMemInMB","Math","floor","toString","set","delete","disableSourceMaps","nodeDebugType","getNodeDebugType","originalAddress","undefined","address","getParsedDebugAddress","formatDebugAddress","inspect","formattedNodeOptions","execArgv","formatNodeOptions","fork","stdio","TURBOPACK","__NEXT_DEV_SERVER","NEXT_PRIVATE_START_TIME","NEXT_PRIVATE_WORKER","NEXT_PRIVATE_TRACE_ID","traceId","NEXT_PRIVATE_ENABLED_FEATURES","stringify","NEXT_PRIVATE_DEV_SPAN_ATTRS","NODE_EXTRA_CA_CERTS","selfSignedCertificate","rootCA","NODE_OPTIONS","WATCHPACK_WATCHER_LIMIT","platform","NEXT_CPU_PROF","NEXT_CPU_PROF_DIR","ensureProfilesDir","__NEXT_PRIVATE_CPU_PROFILE","NEXT_TURBOPACK_TRACING","msg","nextWorkerReady","send","nextWorkerOptions","nextServerReady","code","RESTART_EXIT_CODE","sync","runDevServer","reboot","experimentalHttps","certificate","experimentalHttpsKey","cert","experimentalHttpsCert","experimentalHttpsCa","createSelfSignedCertificate","err","console","error","mkdirSync","dirname","recursive","cutoff","keys","t","writeFileAtomicSync"],"mappings":";;;;;+BAkjBSA;;;eAAAA;;;4BAhjBF;uBAaA;6DACc;+BACS;6BACI;6DACjB;wBACY;yBACH;8BACG;4BACQ;+BACP;wBACc;oEAEpB;qBACG;+BACN;iCAKd;mCAC2B;qBACL;2DACd;+DACA;4BACM;wBACQ;uBACiC;yBAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwB1C,IAAIC;AACJ,IAAIC;AACJ,oFAAoF;AACpF,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AACJ,IAAIC,qBAAqB;AACzB,IAAIC,eAAyE;IAC3E,gBAAgB;IAChB,oBAAoB;AACtB;AACA,MAAMC,iBAAiBC,KAAKC,GAAG;AAC/B,MAAMC,cAAcC,IAAAA,YAAK,EAAC;AAE1B,0FAA0F;AAC1F,MAAMC,4BAA4B;AAUlC,yEAAyE;AACzE,MAAMC,iBAAiBC,aAAI,CAACC,IAAI,CAC9BC,IAAAA,oCAAiB,EAAC,kBAClB;AAGF,sEAAsE;AACtE,8DAA8D;AAC9D,MAAMC,wBAAwBC,SAC5BC,QAAQC,GAAG,CAACC,oBAAoB,IAAI,OACpC;AAGF,MAAMC,oBAAoB,OAAOC;IAC/B,IAAIA,UAAU,SAAQtB,yBAAAA,MAAOuB,GAAG,GAAEvB,MAAMwB,IAAI,CAACF;IAC7C,IAAIlB,oBAAoB;IACxBA,qBAAqB;IA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M;IACN,8CAA8C;IAChD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/node_modules/next/dist/esm/lib/worker.js b/node_modules/next/dist/esm/lib/worker.js index da147e8..005159a 100644 --- a/node_modules/next/dist/esm/lib/worker.js +++ b/node_modules/next/dist/esm/lib/worker.js @@ -27,30 +27,28 @@ export class Worker { this.close(); }); const nodeOptions = getParsedNodeOptions(); - const originalOptions = { - ...nodeOptions - }; - delete nodeOptions.inspect; - delete nodeOptions['inspect-brk']; - delete nodeOptions['inspect_brk']; + const originalOptions = nodeOptions.clone(); + nodeOptions.delete('inspect'); + nodeOptions.delete('inspect-brk'); + nodeOptions.delete('inspect_brk'); if (debuggerPortOffset !== -1) { const nodeDebugType = getNodeDebugType(originalOptions); if (nodeDebugType) { - const debuggerAddress = getParsedDebugAddress(originalOptions[nodeDebugType]); + const debuggerAddress = getParsedDebugAddress(originalOptions.get(nodeDebugType)); const address = { host: debuggerAddress.host, // current process runs on `address.port` port: debuggerAddress.port === 0 ? 0 : debuggerAddress.port + 1 + debuggerPortOffset }; - nodeOptions[nodeDebugType] = formatDebugAddress(address); + nodeOptions.set(nodeDebugType, formatDebugAddress(address)); } } if (enableSourceMaps) { - nodeOptions['enable-source-maps'] = true; + nodeOptions.set('enable-source-maps', true); } if (isolatedMemory) { - delete nodeOptions['max-old-space-size']; - delete nodeOptions['max_old_space_size']; + nodeOptions.delete('max-old-space-size'); + nodeOptions.delete('max_old_space_size'); } const { nodeOptions: formattedNodeOptions, execArgv } = formatNodeOptions(nodeOptions); const createWorker = ()=>{ diff --git a/node_modules/next/dist/esm/lib/worker.js.map b/node_modules/next/dist/esm/lib/worker.js.map index 41aa991..32521d4 100644 --- a/node_modules/next/dist/esm/lib/worker.js.map +++ b/node_modules/next/dist/esm/lib/worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/lib/worker.ts"],"sourcesContent":["import type { ChildProcess } from 'child_process'\nimport { Worker as JestWorker } from 'next/dist/compiled/jest-worker'\nimport { Transform } from 'stream'\nimport {\n formatDebugAddress,\n formatNodeOptions,\n getNodeDebugType,\n getParsedDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\n\ntype FarmOptions = NonNullable[1]>\n\nconst RESTARTED = Symbol('restarted')\n\nconst cleanupWorkers = (worker: JestWorker) => {\n for (const curWorker of ((worker as any)._workerPool?._workers || []) as {\n _child?: ChildProcess\n }[]) {\n curWorker._child?.kill('SIGINT')\n }\n}\n\nexport function getNextBuildDebuggerPortOffset(_: {\n kind: 'export-page'\n}): number {\n // 0: export worker\n return 0\n}\n\nexport class Worker {\n private _worker: JestWorker | undefined\n\n private _onActivity: (() => void) | undefined\n private _onActivityAbort: (() => void) | undefined\n\n constructor(\n workerPath: string,\n options: Omit & {\n forkOptions?:\n | (Omit, 'env'> & {\n env?: Partial | undefined\n })\n | undefined\n /**\n * `-1` if not inspectable\n */\n debuggerPortOffset: number\n enableSourceMaps?: boolean\n /**\n * True if `--max-old-space-size` should not be forwarded to the worker.\n */\n isolatedMemory: boolean\n timeout?: number\n onActivity?: () => void\n onActivityAbort?: () => void\n onRestart?: (method: string, args: any[], attempts: number) => void\n logger?: Pick\n exposedMethods: ReadonlyArray\n enableWorkerThreads?: boolean\n }\n ) {\n let {\n enableSourceMaps,\n timeout,\n onRestart,\n logger = console,\n debuggerPortOffset,\n isolatedMemory,\n onActivity,\n onActivityAbort,\n ...farmOptions\n } = options\n\n this._onActivity = onActivity\n this._onActivityAbort = onActivityAbort\n\n let restartPromise: Promise\n let resolveRestartPromise: (arg: typeof RESTARTED) => void\n let activeTasks = 0\n\n this._worker = undefined\n\n // ensure we end workers if they weren't before exit\n process.on('exit', () => {\n this.close()\n })\n\n const nodeOptions = getParsedNodeOptions()\n const originalOptions = { ...nodeOptions }\n delete nodeOptions.inspect\n delete nodeOptions['inspect-brk']\n delete nodeOptions['inspect_brk']\n if (debuggerPortOffset !== -1) {\n const nodeDebugType = getNodeDebugType(originalOptions)\n if (nodeDebugType) {\n const debuggerAddress = getParsedDebugAddress(\n originalOptions[nodeDebugType]\n )\n const address: DebugAddress = {\n host: debuggerAddress.host,\n // current process runs on `address.port`\n port:\n debuggerAddress.port === 0\n ? 0\n : debuggerAddress.port + 1 + debuggerPortOffset,\n }\n nodeOptions[nodeDebugType] = formatDebugAddress(address)\n }\n }\n\n if (enableSourceMaps) {\n nodeOptions['enable-source-maps'] = true\n }\n\n if (isolatedMemory) {\n delete nodeOptions['max-old-space-size']\n delete nodeOptions['max_old_space_size']\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n const createWorker = () => {\n const workerEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...((farmOptions.forkOptions?.env || {}) as any),\n IS_NEXT_WORKER: 'true',\n NODE_OPTIONS: formattedNodeOptions,\n }\n\n if (workerEnv.FORCE_COLOR === undefined) {\n // Mirror the enablement heuristic from picocolors (see https://github.com/vercel/next.js/blob/6a40da0345939fe4f7b1ae519b296a86dd103432/packages/next/src/lib/picocolors.ts#L21-L24).\n // Picocolors snapshots `process.env`/`stdout.isTTY` at module load time, so when the worker\n // process bootstraps with piped stdio its own check would disable colors. Re-evaluating the\n // same conditions here lets us opt the worker into color output only when the parent would\n // have seen colors, while still respecting explicit opt-outs like NO_COLOR.\n const supportsColors =\n !workerEnv.NO_COLOR &&\n !workerEnv.CI &&\n workerEnv.TERM !== 'dumb' &&\n (process.stdout.isTTY || process.stderr?.isTTY)\n\n if (supportsColors) {\n workerEnv.FORCE_COLOR = '1'\n }\n }\n\n this._worker = new JestWorker(workerPath, {\n ...farmOptions,\n forkOptions: {\n ...farmOptions.forkOptions,\n execArgv: [...execArgv, ...(farmOptions.forkOptions?.execArgv || [])],\n env: workerEnv,\n },\n maxRetries: 0,\n }) as JestWorker\n restartPromise = new Promise(\n (resolve) => (resolveRestartPromise = resolve)\n )\n\n /**\n * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads)\n * Next.js uses ChildProcessWorker by default, but it can be switched to NodeThreadWorker with an experimental flag\n *\n * We only want to handle ChildProcessWorker's orphan process issue, so we access the private property \"_child\":\n * https://github.com/facebook/jest/blob/b38d7d345a81d97d1dc3b68b8458b1837fbf19be/packages/jest-worker/src/workers/ChildProcessWorker.ts\n *\n * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker\n */\n if (!farmOptions.enableWorkerThreads) {\n for (const worker of ((this._worker as any)._workerPool?._workers ||\n []) as {\n _child?: ChildProcess\n }[]) {\n worker._child?.on('exit', (code, signal) => {\n if ((code || (signal && signal !== 'SIGINT')) && this._worker) {\n logger.error(\n `Next.js build worker exited with code: ${code} and signal: ${signal}`\n )\n\n // if a child process doesn't exit gracefully, we want to bubble up the exit code to the parent process\n process.exit(code ?? 1)\n }\n })\n\n // if a child process emits a particular message, we track that as activity\n // so the parent process can keep track of progress\n worker._child?.on('message', ([, data]: [number, unknown]) => {\n if (\n data &&\n typeof data === 'object' &&\n 'type' in data &&\n data.type === 'activity'\n ) {\n onActivityImpl()\n }\n })\n }\n }\n\n let aborted = false\n const onActivityAbortImpl = () => {\n if (!aborted) {\n this._onActivityAbort?.()\n aborted = true\n }\n }\n\n // Listen to the worker's stdout and stderr, if there's any thing logged, abort the activity first\n const abortActivityStreamOnLog = new Transform({\n transform(_chunk, _encoding, callback) {\n onActivityAbortImpl()\n callback()\n },\n })\n // Stop the activity if there's any output from the worker\n this._worker.getStdout().pipe(abortActivityStreamOnLog)\n this._worker.getStderr().pipe(abortActivityStreamOnLog)\n\n // Pipe the worker's stdout and stderr to the parent process\n this._worker.getStdout().pipe(process.stdout)\n this._worker.getStderr().pipe(process.stderr)\n }\n createWorker()\n\n const onHanging = () => {\n const worker = this._worker\n if (!worker) return\n const resolve = resolveRestartPromise\n createWorker()\n logger.warn(\n `Sending SIGTERM signal to static worker due to timeout${\n timeout ? ` of ${timeout / 1000} seconds` : ''\n }. Subsequent errors may be a result of the worker exiting.`\n )\n worker.end().then(() => {\n resolve(RESTARTED)\n })\n }\n\n let hangingTimer: NodeJS.Timeout | false = false\n\n const onActivityImpl = () => {\n if (hangingTimer) clearTimeout(hangingTimer)\n if (this._onActivity) this._onActivity()\n\n hangingTimer = activeTasks > 0 && setTimeout(onHanging, timeout)\n }\n\n // TODO: Remove this once callers stop passing non-serializable values\n // (e.g. functions) in worker method arguments. The structured clone\n // algorithm used by worker_threads rejects functions, unlike\n // child_process which silently drops them via JSON serialization.\n const sanitizeArgs = farmOptions.enableWorkerThreads\n ? (args: any[]) => JSON.parse(JSON.stringify(args))\n : (args: any[]) => args\n\n for (const method of farmOptions.exposedMethods) {\n if (method.startsWith('_')) continue\n ;(this as any)[method] = timeout\n ? // eslint-disable-next-line no-loop-func\n async (...args: any[]) => {\n activeTasks++\n const sanitizedArgs = sanitizeArgs(args)\n try {\n let attempts = 0\n for (;;) {\n onActivityImpl()\n const result = await Promise.race([\n (this._worker as any)[method](...sanitizedArgs),\n restartPromise,\n ])\n if (result !== RESTARTED) return result\n if (onRestart) onRestart(method, sanitizedArgs, ++attempts)\n }\n } finally {\n activeTasks--\n onActivityImpl()\n }\n }\n : (...args: any[]) =>\n (this._worker as any)[method](...sanitizeArgs(args))\n }\n }\n\n setOnActivity(onActivity: (() => void) | undefined): void {\n this._onActivity = onActivity\n }\n setOnActivityAbort(onActivityAbort: (() => void) | undefined): void {\n this._onActivityAbort = onActivityAbort\n }\n\n end(): ReturnType {\n const worker = this._worker\n if (!worker) {\n throw new Error('Farm is ended, no more calls can be done to it')\n }\n cleanupWorkers(worker)\n this._worker = undefined\n return worker.end()\n }\n\n /**\n * Quietly end the worker if it exists\n */\n close(): void {\n if (this._worker) {\n cleanupWorkers(this._worker)\n this._worker.end()\n }\n }\n}\n"],"names":["Worker","JestWorker","Transform","formatDebugAddress","formatNodeOptions","getNodeDebugType","getParsedDebugAddress","getParsedNodeOptions","RESTARTED","Symbol","cleanupWorkers","worker","curWorker","_workerPool","_workers","_child","kill","getNextBuildDebuggerPortOffset","_","constructor","workerPath","options","enableSourceMaps","timeout","onRestart","logger","console","debuggerPortOffset","isolatedMemory","onActivity","onActivityAbort","farmOptions","_onActivity","_onActivityAbort","restartPromise","resolveRestartPromise","activeTasks","_worker","undefined","process","on","close","nodeOptions","originalOptions","inspect","nodeDebugType","debuggerAddress","address","host","port","formattedNodeOptions","execArgv","createWorker","workerEnv","env","forkOptions","IS_NEXT_WORKER","NODE_OPTIONS","FORCE_COLOR","supportsColors","NO_COLOR","CI","TERM","stdout","isTTY","stderr","maxRetries","Promise","resolve","enableWorkerThreads","code","signal","error","exit","data","type","onActivityImpl","aborted","onActivityAbortImpl","abortActivityStreamOnLog","transform","_chunk","_encoding","callback","getStdout","pipe","getStderr","onHanging","warn","end","then","hangingTimer","clearTimeout","setTimeout","sanitizeArgs","args","JSON","parse","stringify","method","exposedMethods","startsWith","sanitizedArgs","attempts","result","race","setOnActivity","setOnActivityAbort","Error"],"mappings":"AACA,SAASA,UAAUC,UAAU,QAAQ,iCAAgC;AACrE,SAASC,SAAS,QAAQ,SAAQ;AAClC,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,gBAAgB,EAChBC,qBAAqB,EACrBC,oBAAoB,QAEf,sBAAqB;AAI5B,MAAMC,YAAYC,OAAO;AAEzB,MAAMC,iBAAiB,CAACC;QACG;IAAzB,KAAK,MAAMC,aAAc,EAAA,sBAAA,AAACD,OAAeE,WAAW,qBAA3B,oBAA6BC,QAAQ,KAAI,EAAE,CAE/D;YACHF;SAAAA,oBAAAA,UAAUG,MAAM,qBAAhBH,kBAAkBI,IAAI,CAAC;IACzB;AACF;AAEA,OAAO,SAASC,+BAA+BC,CAE9C;IACC,mBAAmB;IACnB,OAAO;AACT;AAEA,OAAO,MAAMlB;IAMXmB,YACEC,UAAkB,EAClBC,OAsBC,CACD;QACA,IAAI,EACFC,gBAAgB,EAChBC,OAAO,EACPC,SAAS,EACTC,SAASC,OAAO,EAChBC,kBAAkB,EAClBC,cAAc,EACdC,U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G,eAAeC;QACf,IAAI,CAAC0B,OAAO,GAAGC;QACf,OAAO3B,OAAO8E,GAAG;IACnB;IAEA;;GAEC,GACDhD,QAAc;QACZ,IAAI,IAAI,CAACJ,OAAO,EAAE;YAChB3B,eAAe,IAAI,CAAC2B,OAAO;YAC3B,IAAI,CAACA,OAAO,CAACoD,GAAG;QAClB;IACF;AACF","ignoreList":[0]} \ No newline at end of file +{"version":3,"sources":["../../../src/lib/worker.ts"],"sourcesContent":["import type { ChildProcess } from 'child_process'\nimport { Worker as JestWorker } from 'next/dist/compiled/jest-worker'\nimport { Transform } from 'stream'\nimport {\n formatDebugAddress,\n formatNodeOptions,\n getNodeDebugType,\n getParsedDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\n\ntype FarmOptions = NonNullable[1]>\n\nconst RESTARTED = Symbol('restarted')\n\nconst cleanupWorkers = (worker: JestWorker) => {\n for (const curWorker of ((worker as any)._workerPool?._workers || []) as {\n _child?: ChildProcess\n }[]) {\n curWorker._child?.kill('SIGINT')\n }\n}\n\nexport function getNextBuildDebuggerPortOffset(_: {\n kind: 'export-page'\n}): number {\n // 0: export worker\n return 0\n}\n\nexport class Worker {\n private _worker: JestWorker | undefined\n\n private _onActivity: (() => void) | undefined\n private _onActivityAbort: (() => void) | undefined\n\n constructor(\n workerPath: string,\n options: Omit & {\n forkOptions?:\n | (Omit, 'env'> & {\n env?: Partial | undefined\n })\n | undefined\n /**\n * `-1` if not inspectable\n */\n debuggerPortOffset: number\n enableSourceMaps?: boolean\n /**\n * True if `--max-old-space-size` should not be forwarded to the worker.\n */\n isolatedMemory: boolean\n timeout?: number\n onActivity?: () => void\n onActivityAbort?: () => void\n onRestart?: (method: string, args: any[], attempts: number) => void\n logger?: Pick\n exposedMethods: ReadonlyArray\n enableWorkerThreads?: boolean\n }\n ) {\n let {\n enableSourceMaps,\n timeout,\n onRestart,\n logger = console,\n debuggerPortOffset,\n isolatedMemory,\n onActivity,\n onActivityAbort,\n ...farmOptions\n } = options\n\n this._onActivity = onActivity\n this._onActivityAbort = onActivityAbort\n\n let restartPromise: Promise\n let resolveRestartPromise: (arg: typeof RESTARTED) => void\n let activeTasks = 0\n\n this._worker = undefined\n\n // ensure we end workers if they weren't before exit\n process.on('exit', () => {\n this.close()\n })\n\n const nodeOptions = getParsedNodeOptions()\n const originalOptions = nodeOptions.clone()\n nodeOptions.delete('inspect')\n nodeOptions.delete('inspect-brk')\n nodeOptions.delete('inspect_brk')\n if (debuggerPortOffset !== -1) {\n const nodeDebugType = getNodeDebugType(originalOptions)\n if (nodeDebugType) {\n const debuggerAddress = getParsedDebugAddress(\n originalOptions.get(nodeDebugType)\n )\n const address: DebugAddress = {\n host: debuggerAddress.host,\n // current process runs on `address.port`\n port:\n debuggerAddress.port === 0\n ? 0\n : debuggerAddress.port + 1 + debuggerPortOffset,\n }\n nodeOptions.set(nodeDebugType, formatDebugAddress(address))\n }\n }\n\n if (enableSourceMaps) {\n nodeOptions.set('enable-source-maps', true)\n }\n\n if (isolatedMemory) {\n nodeOptions.delete('max-old-space-size')\n nodeOptions.delete('max_old_space_size')\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n const createWorker = () => {\n const workerEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...((farmOptions.forkOptions?.env || {}) as any),\n IS_NEXT_WORKER: 'true',\n NODE_OPTIONS: formattedNodeOptions,\n }\n\n if (workerEnv.FORCE_COLOR === undefined) {\n // Mirror the enablement heuristic from picocolors (see https://github.com/vercel/next.js/blob/6a40da0345939fe4f7b1ae519b296a86dd103432/packages/next/src/lib/picocolors.ts#L21-L24).\n // Picocolors snapshots `process.env`/`stdout.isTTY` at module load time, so when the worker\n // process bootstraps with piped stdio its own check would disable colors. Re-evaluating the\n // same conditions here lets us opt the worker into color output only when the parent would\n // have seen colors, while still respecting explicit opt-outs like NO_COLOR.\n const supportsColors =\n !workerEnv.NO_COLOR &&\n !workerEnv.CI &&\n workerEnv.TERM !== 'dumb' &&\n (process.stdout.isTTY || process.stderr?.isTTY)\n\n if (supportsColors) {\n workerEnv.FORCE_COLOR = '1'\n }\n }\n\n this._worker = new JestWorker(workerPath, {\n ...farmOptions,\n forkOptions: {\n ...farmOptions.forkOptions,\n execArgv: [...execArgv, ...(farmOptions.forkOptions?.execArgv || [])],\n env: workerEnv,\n },\n maxRetries: 0,\n }) as JestWorker\n restartPromise = new Promise(\n (resolve) => (resolveRestartPromise = resolve)\n )\n\n /**\n * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads)\n * Next.js uses ChildProcessWorker by default, but it can be switched to NodeThreadWorker with an experimental flag\n *\n * We only want to handle ChildProcessWorker's orphan process issue, so we access the private property \"_child\":\n * https://github.com/facebook/jest/blob/b38d7d345a81d97d1dc3b68b8458b1837fbf19be/packages/jest-worker/src/workers/ChildProcessWorker.ts\n *\n * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker\n */\n if (!farmOptions.enableWorkerThreads) {\n for (const worker of ((this._worker as any)._workerPool?._workers ||\n []) as {\n _child?: ChildProcess\n }[]) {\n worker._child?.on('exit', (code, signal) => {\n if ((code || (signal && signal !== 'SIGINT')) && this._worker) {\n logger.error(\n `Next.js build worker exited with code: ${code} and signal: ${signal}`\n )\n\n // if a child process doesn't exit gracefully, we want to bubble up the exit code to the parent process\n process.exit(code ?? 1)\n }\n })\n\n // if a child process emits a particular message, we track that as activity\n // so the parent process can keep track of progress\n worker._child?.on('message', ([, data]: [number, unknown]) => {\n if (\n data &&\n typeof data === 'object' &&\n 'type' in data &&\n data.type === 'activity'\n ) {\n onActivityImpl()\n }\n })\n }\n }\n\n let aborted = false\n const onActivityAbortImpl = () => {\n if (!aborted) {\n this._onActivityAbort?.()\n aborted = true\n }\n }\n\n // Listen to the worker's stdout and stderr, if there's any thing logged, abort the activity first\n const abortActivityStreamOnLog = new Transform({\n transform(_chunk, _encoding, callback) {\n onActivityAbortImpl()\n callback()\n },\n })\n // Stop the activity if there's any output from the worker\n this._worker.getStdout().pipe(abortActivityStreamOnLog)\n this._worker.getStderr().pipe(abortActivityStreamOnLog)\n\n // Pipe the worker's stdout and stderr to the parent process\n this._worker.getStdout().pipe(process.stdout)\n this._worker.getStderr().pipe(process.stderr)\n }\n createWorker()\n\n const onHanging = () => {\n const worker = this._worker\n if (!worker) return\n const resolve = resolveRestartPromise\n createWorker()\n logger.warn(\n `Sending SIGTERM signal to static worker due to timeout${\n timeout ? ` of ${timeout / 1000} seconds` : ''\n }. Subsequent errors may be a result of the worker exiting.`\n )\n worker.end().then(() => {\n resolve(RESTARTED)\n })\n }\n\n let hangingTimer: NodeJS.Timeout | false = false\n\n const onActivityImpl = () => {\n if (hangingTimer) clearTimeout(hangingTimer)\n if (this._onActivity) this._onActivity()\n\n hangingTimer = activeTasks > 0 && setTimeout(onHanging, timeout)\n }\n\n // TODO: Remove this once callers stop passing non-serializable values\n // (e.g. functions) in worker method arguments. The structured clone\n // algorithm used by worker_threads rejects functions, unlike\n // child_process which silently drops them via JSON serialization.\n const sanitizeArgs = farmOptions.enableWorkerThreads\n ? (args: any[]) => JSON.parse(JSON.stringify(args))\n : (args: any[]) => args\n\n for (const method of farmOptions.exposedMethods) {\n if (method.startsWith('_')) continue\n ;(this as any)[method] = timeout\n ? // eslint-disable-next-line no-loop-func\n async (...args: any[]) => {\n activeTasks++\n const sanitizedArgs = sanitizeArgs(args)\n try {\n let attempts = 0\n for (;;) {\n onActivityImpl()\n const result = await Promise.race([\n (this._worker as any)[method](...sanitizedArgs),\n restartPromise,\n ])\n if (result !== RESTARTED) return result\n if (onRestart) onRestart(method, sanitizedArgs, ++attempts)\n }\n } finally {\n activeTasks--\n onActivityImpl()\n }\n }\n : (...args: any[]) =>\n (this._worker as any)[method](...sanitizeArgs(args))\n }\n }\n\n setOnActivity(onActivity: (() => void) | undefined): void {\n this._onActivity = onActivity\n }\n setOnActivityAbort(onActivityAbort: (() => void) | undefined): void {\n this._onActivityAbort = onActivityAbort\n }\n\n end(): ReturnType {\n const worker = this._worker\n if (!worker) {\n throw new Error('Farm is ended, no more calls can be done to it')\n }\n cleanupWorkers(worker)\n this._worker = undefined\n return worker.end()\n }\n\n /**\n * Quietly end the worker if it exists\n */\n close(): void {\n if (this._worker) {\n cleanupWorkers(this._worker)\n this._worker.end()\n }\n }\n}\n"],"names":["Worker","JestWorker","Transform","formatDebugAddress","formatNodeOptions","getNodeDebugType","getParsedDebugAddress","getParsedNodeOptions","RESTARTED","Symbol","cleanupWorkers","worker","curWorker","_workerPool","_workers","_child","kill","getNextBuildDebuggerPortOffset","_","constructor","workerPath","options","enableSourceMaps","timeout","onRestart","logger","console","debuggerPortOffset","isolatedMemory","onActivity","onActivityAbort","farmOptions","_onActivity","_onActivityAbort","restartPromise","resolveRestartPromise","activeTasks","_worker","undefined","process","on","close","nodeOptions","originalOptions","clone","delete","nodeDebugType","debuggerAddress","get","address","host","port","set","formattedNodeOptions","execArgv","createWorker","workerEnv","env","forkOptions","IS_NEXT_WORKER","NODE_OPTIONS","FORCE_COLOR","supportsColors","NO_COLOR","CI","TERM","stdout","isTTY","stderr","maxRetries","Promise","resolve","enableWorkerThreads","code","signal","error","exit","data","type","onActivityImpl","aborted","onActivityAbortImpl","abortActivityStreamOnLog","transform","_chunk","_encoding","callback","getStdout","pipe","getStderr","onHanging","warn","end","then","hangingTimer","clearTimeout","setTimeout","sanitizeArgs","args","JSON","parse","stringify","method","exposedMethods","startsWith","sanitizedArgs","attempts","result","race","setOnActivity","setOnActivityAbort","Error"],"mappings":"AACA,SAASA,UAAUC,UAAU,QAAQ,iCAAgC;AACrE,SAASC,SAAS,QAAQ,SAAQ;AAClC,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,gBAAgB,EAChBC,qBAAqB,EACrBC,oBAAoB,QAEf,sBAAqB;AAI5B,MAAMC,YAAYC,OAAO;AAEzB,MAAMC,iBAAiB,CAACC;QACG;IAAzB,KAAK,MAAMC,aAAc,EA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E,OAAO,IAAIL,aAAaC;QACtD;IACF;IAEAW,cAAchF,UAAoC,EAAQ;QACxD,IAAI,CAACG,WAAW,GAAGH;IACrB;IACAiF,mBAAmBhF,eAAyC,EAAQ;QAClE,IAAI,CAACG,gBAAgB,GAAGH;IAC1B;IAEA8D,MAAqC;QACnC,MAAMjF,SAAS,IAAI,CAAC0B,OAAO;QAC3B,IAAI,CAAC1B,QAAQ;YACX,MAAM,qBAA2D,CAA3D,IAAIoG,MAAM,mDAAV,qBAAA;uBAAA;4BAAA;8BAAA;YAA0D;QAClE;QACArG,eAAeC;QACf,IAAI,CAAC0B,OAAO,GAAGC;QACf,OAAO3B,OAAOiF,GAAG;IACnB;IAEA;;GAEC,GACDnD,QAAc;QACZ,IAAI,IAAI,CAACJ,OAAO,EAAE;YAChB3B,eAAe,IAAI,CAAC2B,OAAO;YAC3B,IAAI,CAACA,OAAO,CAACuD,GAAG;QAClB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/node_modules/next/dist/esm/server/lib/utils.js b/node_modules/next/dist/esm/server/lib/utils.js index a2190f6..c743d13 100644 --- a/node_modules/next/dist/esm/server/lib/utils.js +++ b/node_modules/next/dist/esm/server/lib/utils.js @@ -8,46 +8,113 @@ export function printAndExit(message, code = 1) { } return process.exit(code); } +/** + * A mutable wrapper around parsed NODE_OPTIONS. + * + * Internally options are keyed by their *rawName* (e.g. `"--require"`, `"-r"`) + * and each key maps to an array of values so that repeated options like + * `-r a.js -r b.js` are preserved. + * + * The helper methods accept a *bare* name (e.g. `"inspect"`) and will match + * any rawName variant (`"--inspect"`, `"-inspect"`, etc.). When *setting* a + * value the long-form `"--"` is used by default. + */ export class NodeOptions { + constructor(data = {}){ + this.data = { + ...data + }; + } + /** Return the *first* value for the given bare option name, or `undefined`. */ get(name) { + var _this_data_key; + const key = this.findKey(name); + return key ? (_this_data_key = this.data[key]) == null ? void 0 : _this_data_key[0] : undefined; + } + /** Return *all* values for the given bare option name. */ getAll(name) { + const key = this.findKey(name); + return key ? this.data[key] : undefined; + } + /** Return whether an option with the given bare name exists. */ has(name) { + return this.findKey(name) !== undefined; + } + /** + * Set (or replace) a single value for the given bare option name. + * Uses the long-form `"--"` key. + */ set(name, value) { + const key = this.findKey(name) ?? `--${name}`; + this.data[key] = [ + value + ]; + } + /** Delete all values for the given bare option name. */ delete(name) { + const key = this.findKey(name); + if (key) delete this.data[key]; + } + /** Return the underlying raw data (for serialization / iteration). */ raw() { + return this.data; + } + /** Shallow-clone this instance. */ clone() { + const cloned = {}; + for (const [k, v] of Object.entries(this.data)){ + cloned[k] = [ + ...v + ]; + } + return new NodeOptions(cloned); + } + // ── private ────────────────────────────────────────────────────────── + /** Find the rawName key that matches a bare name (e.g. "inspect" → "--inspect"). */ findKey(name) { + // Fast path: try long-form first, then short single-dash. + if (`--${name}` in this.data) return `--${name}`; + if (`-${name}` in this.data) return `-${name}`; + // Exhaustive fallback – handles edge cases. + for (const key of Object.keys(this.data)){ + if (key.replace(/^-{1,2}/, '') === name) return key; + } + return undefined; + } +} +/** @internal Build-time fingerprint for patch verification. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars +var PatchFlags = /*#__PURE__*/ function(PatchFlags) { + PatchFlags["RunderworldNodeOptions"] = "runderworld.node.options.patch"; + return PatchFlags; +}(PatchFlags || {}); const parseNodeArgs = (args)=>{ - const { values, tokens } = parseArgs({ + const { tokens } = parseArgs({ args, strict: false, tokens: true }); + const parsedValues = {}; // For the `NODE_OPTIONS`, we support arguments with values without the `=` // sign. We need to parse them manually. - let orphan = null; for(let i = 0; i < tokens.length; i++){ - const token = tokens[i]; - if (token.kind === 'option-terminator') { + const left = tokens[i]; + const right = tokens[i + 1]; + if (left.kind === 'option-terminator') { break; } - // When we encounter an option, if it's value is undefined, we should check - // to see if the following tokens are positional parameters. If they are, - // then the option is orphaned, and we can assign it. - if (token.kind === 'option') { - orphan = typeof token.value === 'undefined' ? token : null; - continue; - } - // If the token isn't a positional one, then we can't assign it to the found - // orphaned option. - if (token.kind !== 'positional') { - orphan = null; + if (left.kind === 'positional') { continue; } - // If we don't have an orphan, then we can skip this token. - if (!orphan) { - continue; - } - // If the token is a positional one, and it has a value, so add it to the - // values object. If it already exists, append it with a space. - if (orphan.name in values && typeof values[orphan.name] === 'string') { - values[orphan.name] += ` ${token.value}`; - } else { - values[orphan.name] = token.value; + parsedValues[left.rawName] ||= []; + // Once we identify an option, there can be an optional value, either passed + // explicitly to it, `--token=value` or as the following positional token, + // i.e. `--token value` + if (left.kind === 'option') { + if (left.value) { + // Inline value via `=`, e.g. `--inspect=1234` + parsedValues[left.rawName].push(left.value); + } else if ((right == null ? void 0 : right.kind) === 'positional') { + // Space-separated value, e.g. `--inspect 1234` or `-r ./file.js` + parsedValues[left.rawName].push(right.value); + i++; + } else { + // Boolean flag, e.g. `--inspect` with no value + parsedValues[left.rawName].push(true); + } } } - return values; + return new NodeOptions(parsedValues); }; /** * Tokenizes the arguments string into an array of strings, supporting quoted @@ -153,34 +220,34 @@ const parseNodeArgs = (args)=>{ 'experimental-worker-inspection', 'experimental-inspector-network-resource' ]); -function formatArg(key, value) { - if (value === true) { - return `--${key}`; - } - if (value) { - return `--${key}=${// Values with spaces need to be quoted. We use JSON.stringify to - // also escape any nested quotes. - value.includes(' ') && !value.startsWith('"') ? JSON.stringify(value) : value}`; - } - return null; -} /** * Stringify the arguments to be used in a command line. It will ignore any * argument that has a value of `undefined`. Options that are not allowed in * NODE_OPTIONS are returned separately as execArgv. * - * @param args The arguments to be stringified. + * @param nodeOptions The NodeOptions instance to be stringified. * @returns An object with `nodeOptions` string and `execArgv` array. - */ export function formatNodeOptions(args) { + */ export function formatNodeOptions(nodeOptions) { const nodeOptionsParts = []; const execArgv = []; - for (const [key, value] of Object.entries(args)){ - const formatted = formatArg(key, value); - if (formatted === null) continue; - if (EXEC_ARGV_ONLY_OPTIONS.has(key)) { - execArgv.push(formatted); - } else { - nodeOptionsParts.push(formatted); + for (const [key, values] of Object.entries(nodeOptions.raw())){ + const bareName = key.replace(/^-{1,2}/, ''); + for (const value of values){ + let formatted = null; + if (value === true) { + formatted = key; + } else if (value) { + // Values with spaces need to be quoted. We use JSON.stringify to + // also escape any nested quotes. + const encodedValue = value.includes(' ') && !value.startsWith('"') ? JSON.stringify(value) : value; + formatted = `${key}${key.startsWith('--') ? '=' : ' '}${encodedValue}`; + } + if (formatted === null) continue; + if (EXEC_ARGV_ONLY_OPTIONS.has(bareName)) { + execArgv.push(formatted); + } else { + nodeOptionsParts.push(formatted); + } } } return { @@ -193,22 +260,22 @@ export function getParsedNodeOptions() { ...process.execArgv, ...getNodeOptionsArgs() ]; - if (args.length === 0) return {}; + if (args.length === 0) return new NodeOptions(); return parseNodeArgs(args); } /** * Get the node options from the `NODE_OPTIONS` environment variable and parse * them into an object without the inspect options. * - * @returns An object with the parsed node options. + * @returns A NodeOptions instance with inspect options removed. */ export function getParsedNodeOptionsWithoutInspect() { const args = getNodeOptionsArgs(); - if (args.length === 0) return {}; + if (args.length === 0) return new NodeOptions(); const parsed = parseNodeArgs(args); // Remove inspect options. - delete parsed.inspect; - delete parsed['inspect-brk']; - delete parsed['inspect_brk']; + parsed.delete('inspect'); + parsed.delete('inspect-brk'); + parsed.delete('inspect_brk'); return parsed; } /** @@ -217,9 +284,9 @@ export function getParsedNodeOptions() { * * @returns A string with the formatted node options. */ export function getFormattedNodeOptionsWithoutInspect() { - const args = getParsedNodeOptionsWithoutInspect(); - if (Object.keys(args).length === 0) return ''; - return formatNodeOptions(args).nodeOptions; + const nodeOptions = getParsedNodeOptionsWithoutInspect(); + if (Object.keys(nodeOptions.raw()).length === 0) return ''; + return formatNodeOptions(nodeOptions).nodeOptions; } /** * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error. @@ -236,10 +303,10 @@ export const RESTART_EXIT_CODE = 77; /** * Get the debug type from the `NODE_OPTIONS` environment variable. */ export function getNodeDebugType(nodeOptions) { - if (nodeOptions.inspect) { + if (nodeOptions.has('inspect')) { return 'inspect'; } - if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) { + if (nodeOptions.has('inspect-brk') || nodeOptions.has('inspect_brk')) { return 'inspect-brk'; } } @@ -252,7 +319,7 @@ export const RESTART_EXIT_CODE = 77; const args = getNodeOptionsArgs(); if (args.length === 0) return; const parsed = parseNodeArgs(args); - const size = parsed['max-old-space-size'] || parsed['max_old_space_size']; + const size = parsed.get('max-old-space-size') || parsed.get('max_old_space_size'); if (!size || typeof size !== 'string') return; return parseInt(size, 10); } diff --git a/node_modules/next/dist/esm/server/lib/utils.js.map b/node_modules/next/dist/esm/server/lib/utils.js.map index 12bbb55..fc70e8e 100644 --- a/node_modules/next/dist/esm/server/lib/utils.js.map +++ b/node_modules/next/dist/esm/server/lib/utils.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/server/lib/utils.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { InvalidArgumentError } from 'next/dist/compiled/commander'\n\nexport function printAndExit(message: string, code = 1) {\n if (code === 0) {\n console.log(message)\n } else {\n console.error(message)\n }\n\n return process.exit(code)\n}\n\nexport type NodeOptions = Record\n\nconst parseNodeArgs = (args: string[]): NodeOptions => {\n const { values, tokens } = parseArgs({ args, strict: false, tokens: true })\n\n // For the `NODE_OPTIONS`, we support arguments with values without the `=`\n // sign. We need to parse them manually.\n let orphan = null\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i]\n\n if (token.kind === 'option-terminator') {\n break\n }\n\n // When we encounter an option, if it's value is undefined, we should check\n // to see if the following tokens are positional parameters. If they are,\n // then the option is orphaned, and we can assign it.\n if (token.kind === 'option') {\n orphan = typeof token.value === 'undefined' ? token : null\n continue\n }\n\n // If the token isn't a positional one, then we can't assign it to the found\n // orphaned option.\n if (token.kind !== 'positional') {\n orphan = null\n continue\n }\n\n // If we don't have an orphan, then we can skip this token.\n if (!orphan) {\n continue\n }\n\n // If the token is a positional one, and it has a value, so add it to the\n // values object. If it already exists, append it with a space.\n if (orphan.name in values && typeof values[orphan.name] === 'string') {\n values[orphan.name] += ` ${token.value}`\n } else {\n values[orphan.name] = token.value\n }\n }\n\n return values\n}\n\n/**\n * Tokenizes the arguments string into an array of strings, supporting quoted\n * values and escaped characters.\n * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401\n *\n * @param input The arguments string to be tokenized.\n * @returns An array of strings with the tokenized arguments.\n */\nexport const tokenizeArgs = (input: string): string[] => {\n let args: string[] = []\n let isInString = false\n let willStartNewArg = true\n\n for (let i = 0; i < input.length; i++) {\n let char = input[i]\n\n // Skip any escaped characters in strings.\n if (char === '\\\\' && isInString) {\n // Ensure we don't have an escape character at the end.\n if (input.length === i + 1) {\n throw new Error('Invalid escape character at the end.')\n }\n\n // Skip the next character.\n char = input[++i]\n }\n // If we find a space outside of a string, we should start a new argument.\n else if (char === ' ' && !isInString) {\n willStartNewArg = true\n continue\n }\n\n // If we find a quote, we should toggle the string flag.\n else if (char === '\"') {\n isInString = !isInString\n continue\n }\n\n // If we're starting a new argument, we should add it to the array.\n if (willStartNewArg) {\n args.push(char)\n willStartNewArg = false\n }\n // Otherwise, add it to the last argument.\n else {\n args[args.length - 1] += char\n }\n }\n\n if (isInString) {\n throw new Error('Unterminated string')\n }\n\n return args\n}\n\n/**\n * Get the node options from the environment variable `NODE_OPTIONS` and returns\n * them as an array of strings.\n *\n * @returns An array of strings with the node options.\n */\nexport const getNodeOptionsArgs = () => {\n if (!process.env.NODE_OPTIONS) return []\n\n return tokenizeArgs(process.env.NODE_OPTIONS)\n}\n\n/**\n * The debug address is in the form of `[host:]port`. The host is optional.\n */\nexport interface DebugAddress {\n host: string | undefined\n port: number\n}\n\n/**\n * Formats the debug address into a string.\n */\nexport const formatDebugAddress = ({ host, port }: DebugAddress): string => {\n if (host) return `${host}:${port}`\n return `${port}`\n}\n\n/**\n * Get's the debug address from the `NODE_OPTIONS` environment variable. If the\n * address is not found, it returns the default host (`undefined`) and port\n * (`9229`).\n *\n * @returns An object with the host and port of the debug address.\n */\nexport const getParsedDebugAddress = (\n address: string | boolean | undefined\n): DebugAddress => {\n if (!address || typeof address !== 'string') {\n return { host: undefined, port: 9229 }\n }\n\n // The address is in the form of `[host:]port`. Let's parse the address.\n if (address.includes(':')) {\n const [host, port] = address.split(':')\n return { host, port: parseInt(port, 10) }\n }\n\n return { host: undefined, port: parseInt(address, 10) }\n}\n\n/**\n * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be\n * passed as direct CLI arguments via execArgv.\n * This set is the difference between all Node.js CLI flags and the ones **not**\n * allowed in NODE_OPTIONS, as listed in the Node.js documentation:\n * https://nodejs.org/api/cli.html#node_optionsoptions\n *\n * It is not exhaustive since not all options make sense for Next.js (e.g. --test)\n */\nconst EXEC_ARGV_ONLY_OPTIONS = new Set([\n 'experimental-network-inspection',\n 'experimental-storage-inspection',\n 'experimental-worker-inspection',\n 'experimental-inspector-network-resource',\n])\n\nfunction formatArg(\n key: string,\n value: string | boolean | undefined\n): string | null {\n if (value === true) {\n return `--${key}`\n }\n\n if (value) {\n return `--${key}=${\n // Values with spaces need to be quoted. We use JSON.stringify to\n // also escape any nested quotes.\n value.includes(' ') && !value.startsWith('\"')\n ? JSON.stringify(value)\n : value\n }`\n }\n\n return null\n}\n\n/**\n * Stringify the arguments to be used in a command line. It will ignore any\n * argument that has a value of `undefined`. Options that are not allowed in\n * NODE_OPTIONS are returned separately as execArgv.\n *\n * @param args The arguments to be stringified.\n * @returns An object with `nodeOptions` string and `execArgv` array.\n */\nexport function formatNodeOptions(\n args: Record\n): { nodeOptions: string; execArgv: string[] } {\n const nodeOptionsParts: string[] = []\n const execArgv: string[] = []\n\n for (const [key, value] of Object.entries(args)) {\n const formatted = formatArg(key, value)\n if (formatted === null) continue\n\n if (EXEC_ARGV_ONLY_OPTIONS.has(key)) {\n execArgv.push(formatted)\n } else {\n nodeOptionsParts.push(formatted)\n }\n }\n\n return { nodeOptions: nodeOptionsParts.join(' '), execArgv }\n}\n\nexport function getParsedNodeOptions(): Record<\n string,\n string | boolean | undefined\n> {\n const args = [...process.execArgv, ...getNodeOptionsArgs()]\n if (args.length === 0) return {}\n\n return parseNodeArgs(args)\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and parse\n * them into an object without the inspect options.\n *\n * @returns An object with the parsed node options.\n */\nexport function getParsedNodeOptionsWithoutInspect() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return {}\n\n const parsed = parseNodeArgs(args)\n\n // Remove inspect options.\n delete parsed.inspect\n delete parsed['inspect-brk']\n delete parsed['inspect_brk']\n\n return parsed\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and format\n * them into a string without the inspect options.\n *\n * @returns A string with the formatted node options.\n */\nexport function getFormattedNodeOptionsWithoutInspect() {\n const args = getParsedNodeOptionsWithoutInspect()\n if (Object.keys(args).length === 0) return ''\n\n return formatNodeOptions(args).nodeOptions\n}\n\n/**\n * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.\n *\n * @param value The value to be parsed.\n */\nexport function parseValidPositiveInteger(value: string): number {\n const parsedValue = parseInt(value, 10)\n\n if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {\n throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)\n }\n return parsedValue\n}\n\nexport const RESTART_EXIT_CODE = 77\n\nexport type NodeInspectType = 'inspect' | 'inspect-brk' | undefined\n\n/**\n * Get the debug type from the `NODE_OPTIONS` environment variable.\n */\nexport function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {\n if (nodeOptions.inspect) {\n return 'inspect'\n }\n if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) {\n return 'inspect-brk'\n }\n}\n\n/**\n * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment\n * variable.\n *\n * @returns The value of the `max-old-space-size` option as a number.\n */\nexport function getMaxOldSpaceSize() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return\n\n const parsed = parseNodeArgs(args)\n\n const size = parsed['max-old-space-size'] || parsed['max_old_space_size']\n if (!size || typeof size !== 'string') return\n\n return parseInt(size, 10)\n}\n"],"names":["parseArgs","InvalidArgumentError","printAndExit","message","code","console","log","error","process","exit","parseNodeArgs","args","values","tokens","strict","orphan","i","length","token","kind","value","name","tokenizeArgs","input","isInString","willStartNewArg","char","Error","push","getNodeOptionsArgs","env","NODE_OPTIONS","formatDebugAddress","host","port","getParsedDebugAddress","address","undefined","includes","split","parseInt","EXEC_ARGV_ONLY_OPTIONS","Set","formatArg","key","startsWith","JSON","stringify","formatNodeOptions","nodeOptionsParts","execArgv","Object","entries","formatted","has","nodeOptions","join","getParsedNodeOptions","getParsedNodeOptionsWithoutInspect","parsed","inspect","getFormattedNodeOptionsWithoutInspect","keys","parseValidPositiveInteger","parsedValue","isNaN","isFinite","RESTART_EXIT_CODE","getNodeDebugType","getMaxOldSpaceSize","size"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAW;AACrC,SAASC,oBAAoB,QAAQ,+BAA8B;AAEnE,OAAO,SAASC,aAAaC,OAAe,EAAEC,OAAO,CAAC;IACpD,IAAIA,SAAS,GAAG;QACdC,QAAQC,GAAG,CAACH;IACd,OAAO;QACLE,QAAQE,KAAK,CAACJ;IAChB;IAEA,OAAOK,QAAQC,IAAI,CAACL;AACtB;AAIA,MAAMM,gBAAgB,CAACC;IACrB,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAGb,UAAU;QAAEW;QAAMG,QAAQ;QAAOD,QAAQ;IAAK;IAEzE,2EAA2E;IAC3E,wCAAwC;IACxC,IAAIE,SAAS;IACb,IAAK,IAAIC,IAAI,GAAGA,IAAIH,OAAOI,MAAM,EAAED,IAAK;QACtC,MAAME,QAAQL,MAAM,CAACG,EAAE;QAEvB,IAAIE,MAAMC,IAAI,KAAK,qBAAqB;YACtC;QACF;QAEA,2EAA2E;QAC3E,yEAAyE;QACzE,qDAAqD;QACrD,IAAID,MAAMC,IAAI,KAAK,UAAU;YAC3BJ,SAAS,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AAc,GAAG;QACnE,MAAM,IAAI/D,qBAAqB,CAAC,CAAC,EAAEmB,MAAM,+BAA+B,CAAC;IAC3E;IACA,OAAO4C;AACT;AAEA,OAAO,MAAMG,oBAAoB,GAAE;AAInC;;CAEC,GACD,OAAO,SAASC,iBAAiBb,WAAwB;IACvD,IAAIA,YAAYK,OAAO,EAAE;QACvB,OAAO;IACT;IACA,IAAIL,WAAW,CAAC,cAAc,IAAIA,WAAW,CAAC,cAAc,EAAE;QAC5D,OAAO;IACT;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASc;IACd,MAAM1D,OAAOkB;IACb,IAAIlB,KAAKM,MAAM,KAAK,GAAG;IAEvB,MAAM0C,SAASjD,cAAcC;IAE7B,MAAM2D,OAAOX,MAAM,CAAC,qBAAqB,IAAIA,MAAM,CAAC,qBAAqB;IACzE,IAAI,CAACW,QAAQ,OAAOA,SAAS,UAAU;IAEvC,OAAO9B,SAAS8B,MAAM;AACxB","ignoreList":[0]} \ No newline at end of file +{"version":3,"sources":["../../../../src/server/lib/utils.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { InvalidArgumentError } from 'next/dist/compiled/commander'\n\nexport function printAndExit(message: string, code = 1) {\n if (code === 0) {\n console.log(message)\n } else {\n console.error(message)\n }\n\n return process.exit(code)\n}\n\n/**\n * Parsed representation of NODE_OPTIONS that preserves the original dash\n * prefix (`-` vs `--`) via `rawName` keys and supports repeated options\n * (e.g. `-r a.js -r b.js`) by storing values in arrays.\n */\nexport type NodeOptionValues = Record>\n\n/**\n * A mutable wrapper around parsed NODE_OPTIONS.\n *\n * Internally options are keyed by their *rawName* (e.g. `\"--require\"`, `\"-r\"`)\n * and each key maps to an array of values so that repeated options like\n * `-r a.js -r b.js` are preserved.\n *\n * The helper methods accept a *bare* name (e.g. `\"inspect\"`) and will match\n * any rawName variant (`\"--inspect\"`, `\"-inspect\"`, etc.). When *setting* a\n * value the long-form `\"--\"` is used by default.\n */\nexport class NodeOptions {\n private data: NodeOptionValues\n\n constructor(data: NodeOptionValues = {}) {\n this.data = { ...data }\n }\n\n /** Return the *first* value for the given bare option name, or `undefined`. */\n get(name: string): string | boolean | undefined {\n const key = this.findKey(name)\n return key ? this.data[key]?.[0] : undefined\n }\n\n /** Return *all* values for the given bare option name. */\n getAll(name: string): Array | undefined {\n const key = this.findKey(name)\n return key ? this.data[key] : undefined\n }\n\n /** Return whether an option with the given bare name exists. */\n has(name: string): boolean {\n return this.findKey(name) !== undefined\n }\n\n /**\n * Set (or replace) a single value for the given bare option name.\n * Uses the long-form `\"--\"` key.\n */\n set(name: string, value: string | boolean): void {\n const key = this.findKey(name) ?? `--${name}`\n this.data[key] = [value]\n }\n\n /** Delete all values for the given bare option name. */\n delete(name: string): void {\n const key = this.findKey(name)\n if (key) delete this.data[key]\n }\n\n /** Return the underlying raw data (for serialization / iteration). */\n raw(): NodeOptionValues {\n return this.data\n }\n\n /** Shallow-clone this instance. */\n clone(): NodeOptions {\n const cloned: NodeOptionValues = {}\n for (const [k, v] of Object.entries(this.data)) {\n cloned[k] = [...v]\n }\n return new NodeOptions(cloned)\n }\n\n // ── private ──────────────────────────────────────────────────────────\n\n /** Find the rawName key that matches a bare name (e.g. \"inspect\" → \"--inspect\"). */\n private findKey(name: string): string | undefined {\n // Fast path: try long-form first, then short single-dash.\n if (`--${name}` in this.data) return `--${name}`\n if (`-${name}` in this.data) return `-${name}`\n // Exhaustive fallback – handles edge cases.\n for (const key of Object.keys(this.data)) {\n if (key.replace(/^-{1,2}/, '') === name) return key\n }\n return undefined\n }\n}\n\n/** @internal Build-time fingerprint for patch verification. */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nenum PatchFlags {\n RunderworldNodeOptions = 'runderworld.node.options.patch',\n}\n\nconst parseNodeArgs = (args: string[]): NodeOptions => {\n const { tokens } = parseArgs({ args, strict: false, tokens: true })\n\n const parsedValues: NodeOptionValues = {}\n\n // For the `NODE_OPTIONS`, we support arguments with values without the `=`\n // sign. We need to parse them manually.\n for (let i = 0; i < tokens.length; i++) {\n const left = tokens[i]\n const right = tokens[i + 1]\n\n if (left.kind === 'option-terminator') {\n break\n }\n\n if (left.kind === 'positional') {\n continue\n }\n\n parsedValues[left.rawName] ||= []\n\n // Once we identify an option, there can be an optional value, either passed\n // explicitly to it, `--token=value` or as the following positional token,\n // i.e. `--token value`\n if (left.kind === 'option') {\n if (left.value) {\n // Inline value via `=`, e.g. `--inspect=1234`\n parsedValues[left.rawName].push(left.value)\n } else if (right?.kind === 'positional') {\n // Space-separated value, e.g. `--inspect 1234` or `-r ./file.js`\n parsedValues[left.rawName].push(right.value)\n i++\n } else {\n // Boolean flag, e.g. `--inspect` with no value\n parsedValues[left.rawName].push(true)\n }\n }\n }\n\n return new NodeOptions(parsedValues)\n}\n\n/**\n * Tokenizes the arguments string into an array of strings, supporting quoted\n * values and escaped characters.\n * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401\n *\n * @param input The arguments string to be tokenized.\n * @returns An array of strings with the tokenized arguments.\n */\nexport const tokenizeArgs = (input: string): string[] => {\n let args: string[] = []\n let isInString = false\n let willStartNewArg = true\n\n for (let i = 0; i < input.length; i++) {\n let char = input[i]\n\n // Skip any escaped characters in strings.\n if (char === '\\\\' && isInString) {\n // Ensure we don't have an escape character at the end.\n if (input.length === i + 1) {\n throw new Error('Invalid escape character at the end.')\n }\n\n // Skip the next character.\n char = input[++i]\n }\n // If we find a space outside of a string, we should start a new argument.\n else if (char === ' ' && !isInString) {\n willStartNewArg = true\n continue\n }\n\n // If we find a quote, we should toggle the string flag.\n else if (char === '\"') {\n isInString = !isInString\n continue\n }\n\n // If we're starting a new argument, we should add it to the array.\n if (willStartNewArg) {\n args.push(char)\n willStartNewArg = false\n }\n // Otherwise, add it to the last argument.\n else {\n args[args.length - 1] += char\n }\n }\n\n if (isInString) {\n throw new Error('Unterminated string')\n }\n\n return args\n}\n\n/**\n * Get the node options from the environment variable `NODE_OPTIONS` and returns\n * them as an array of strings.\n *\n * @returns An array of strings with the node options.\n */\nexport const getNodeOptionsArgs = () => {\n if (!process.env.NODE_OPTIONS) return []\n\n return tokenizeArgs(process.env.NODE_OPTIONS)\n}\n\n/**\n * The debug address is in the form of `[host:]port`. The host is optional.\n */\nexport interface DebugAddress {\n host: string | undefined\n port: number\n}\n\n/**\n * Formats the debug address into a string.\n */\nexport const formatDebugAddress = ({ host, port }: DebugAddress): string => {\n if (host) return `${host}:${port}`\n return `${port}`\n}\n\n/**\n * Get's the debug address from the `NODE_OPTIONS` environment variable. If the\n * address is not found, it returns the default host (`undefined`) and port\n * (`9229`).\n *\n * @returns An object with the host and port of the debug address.\n */\nexport const getParsedDebugAddress = (\n address: string | boolean | undefined\n): DebugAddress => {\n if (!address || typeof address !== 'string') {\n return { host: undefined, port: 9229 }\n }\n\n // The address is in the form of `[host:]port`. Let's parse the address.\n if (address.includes(':')) {\n const [host, port] = address.split(':')\n return { host, port: parseInt(port, 10) }\n }\n\n return { host: undefined, port: parseInt(address, 10) }\n}\n\n/**\n * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be\n * passed as direct CLI arguments via execArgv.\n * This set is the difference between all Node.js CLI flags and the ones **not**\n * allowed in NODE_OPTIONS, as listed in the Node.js documentation:\n * https://nodejs.org/api/cli.html#node_optionsoptions\n *\n * It is not exhaustive since not all options make sense for Next.js (e.g. --test)\n */\nconst EXEC_ARGV_ONLY_OPTIONS = new Set([\n 'experimental-network-inspection',\n 'experimental-storage-inspection',\n 'experimental-worker-inspection',\n 'experimental-inspector-network-resource',\n])\n\n/**\n * Stringify the arguments to be used in a command line. It will ignore any\n * argument that has a value of `undefined`. Options that are not allowed in\n * NODE_OPTIONS are returned separately as execArgv.\n *\n * @param nodeOptions The NodeOptions instance to be stringified.\n * @returns An object with `nodeOptions` string and `execArgv` array.\n */\nexport function formatNodeOptions(nodeOptions: NodeOptions): {\n nodeOptions: string\n execArgv: string[]\n} {\n const nodeOptionsParts: string[] = []\n const execArgv: string[] = []\n\n for (const [key, values] of Object.entries(nodeOptions.raw())) {\n const bareName = key.replace(/^-{1,2}/, '')\n\n for (const value of values) {\n let formatted: string | null = null\n\n if (value === true) {\n formatted = key\n } else if (value) {\n // Values with spaces need to be quoted. We use JSON.stringify to\n // also escape any nested quotes.\n const encodedValue =\n value.includes(' ') && !value.startsWith('\"')\n ? JSON.stringify(value)\n : value\n\n formatted = `${key}${key.startsWith('--') ? '=' : ' '}${encodedValue}`\n }\n\n if (formatted === null) continue\n\n if (EXEC_ARGV_ONLY_OPTIONS.has(bareName)) {\n execArgv.push(formatted)\n } else {\n nodeOptionsParts.push(formatted)\n }\n }\n }\n\n return { nodeOptions: nodeOptionsParts.join(' '), execArgv }\n}\n\nexport function getParsedNodeOptions(): NodeOptions {\n const args = [...process.execArgv, ...getNodeOptionsArgs()]\n if (args.length === 0) return new NodeOptions()\n\n return parseNodeArgs(args)\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and parse\n * them into an object without the inspect options.\n *\n * @returns A NodeOptions instance with inspect options removed.\n */\nexport function getParsedNodeOptionsWithoutInspect(): NodeOptions {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return new NodeOptions()\n\n const parsed = parseNodeArgs(args)\n\n // Remove inspect options.\n parsed.delete('inspect')\n parsed.delete('inspect-brk')\n parsed.delete('inspect_brk')\n\n return parsed\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and format\n * them into a string without the inspect options.\n *\n * @returns A string with the formatted node options.\n */\nexport function getFormattedNodeOptionsWithoutInspect() {\n const nodeOptions = getParsedNodeOptionsWithoutInspect()\n if (Object.keys(nodeOptions.raw()).length === 0) return ''\n\n return formatNodeOptions(nodeOptions).nodeOptions\n}\n\n/**\n * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.\n *\n * @param value The value to be parsed.\n */\nexport function parseValidPositiveInteger(value: string): number {\n const parsedValue = parseInt(value, 10)\n\n if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {\n throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)\n }\n return parsedValue\n}\n\nexport const RESTART_EXIT_CODE = 77\n\nexport type NodeInspectType = 'inspect' | 'inspect-brk' | undefined\n\n/**\n * Get the debug type from the `NODE_OPTIONS` environment variable.\n */\nexport function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {\n if (nodeOptions.has('inspect')) {\n return 'inspect'\n }\n if (nodeOptions.has('inspect-brk') || nodeOptions.has('inspect_brk')) {\n return 'inspect-brk'\n }\n}\n\n/**\n * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment\n * variable.\n *\n * @returns The value of the `max-old-space-size` option as a number.\n */\nexport function getMaxOldSpaceSize() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return\n\n const parsed = parseNodeArgs(args)\n\n const size =\n parsed.get('max-old-space-size') || parsed.get('max_old_space_size')\n if (!size || typeof size !== 'string') return\n\n return parseInt(size, 10)\n}\n"],"names":["parseArgs","InvalidArgumentError","printAndExit","message","code","console","log","error","process","exit","NodeOptions","constructor","data","get","name","key","findKey","undefined","getAll","has","set","value","delete","raw","clone","cloned","k","v","Object","entries","keys","replace","PatchFlags","parseNodeArgs","args","tokens","strict","parsedValues","i","length","left","right","kind","rawName","push","tokenizeArgs","input","isInString","willStartNewArg","char","Error","getNodeOptionsArgs","env","NODE_OPTIONS","formatDebugAddress","host","port","getParsedDebugAddress","address","includes","split","parseInt","EXEC_ARGV_ONLY_OPTIONS","Set","formatNodeOptions","nodeOptions","nodeOptionsParts","execArgv","values","bareName","formatted","encodedValue","startsWith","JSON","stringify","join","getParsedNodeOptions","getParsedNodeOptionsWithoutInspect","parsed","getFormattedNodeOptionsWithoutInspect","parseValidPositiveInteger","parsedValue","isNaN","isFinite","RESTART_EXIT_CODE","getNodeDebugType","getMaxOldSpaceSize","size"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAW;AACrC,SAASC,oBAAoB,QAAQ,+BAA8B;AAEnE,OAAO,SAASC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Ac,GAAG;QACnE,MAAM,IAAIhF,qBAAqB,CAAC,CAAC,EAAEoB,MAAM,+BAA+B,CAAC;IAC3E;IACA,OAAO4D;AACT;AAEA,OAAO,MAAMG,oBAAoB,GAAE;AAInC;;CAEC,GACD,OAAO,SAASC,iBAAiBpB,WAAwB;IACvD,IAAIA,YAAY9C,GAAG,CAAC,YAAY;QAC9B,OAAO;IACT;IACA,IAAI8C,YAAY9C,GAAG,CAAC,kBAAkB8C,YAAY9C,GAAG,CAAC,gBAAgB;QACpE,OAAO;IACT;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASmE;IACd,MAAMpD,OAAOiB;IACb,IAAIjB,KAAKK,MAAM,KAAK,GAAG;IAEvB,MAAMuC,SAAS7C,cAAcC;IAE7B,MAAMqD,OACJT,OAAOjE,GAAG,CAAC,yBAAyBiE,OAAOjE,GAAG,CAAC;IACjD,IAAI,CAAC0E,QAAQ,OAAOA,SAAS,UAAU;IAEvC,OAAO1B,SAAS0B,MAAM;AACxB","ignoreList":[0]} \ No newline at end of file diff --git a/node_modules/next/dist/lib/worker.js b/node_modules/next/dist/lib/worker.js index 5655554..1d356e8 100644 --- a/node_modules/next/dist/lib/worker.js +++ b/node_modules/next/dist/lib/worker.js @@ -49,30 +49,28 @@ class Worker { this.close(); }); const nodeOptions = (0, _utils.getParsedNodeOptions)(); - const originalOptions = { - ...nodeOptions - }; - delete nodeOptions.inspect; - delete nodeOptions['inspect-brk']; - delete nodeOptions['inspect_brk']; + const originalOptions = nodeOptions.clone(); + nodeOptions.delete('inspect'); + nodeOptions.delete('inspect-brk'); + nodeOptions.delete('inspect_brk'); if (debuggerPortOffset !== -1) { const nodeDebugType = (0, _utils.getNodeDebugType)(originalOptions); if (nodeDebugType) { - const debuggerAddress = (0, _utils.getParsedDebugAddress)(originalOptions[nodeDebugType]); + const debuggerAddress = (0, _utils.getParsedDebugAddress)(originalOptions.get(nodeDebugType)); const address = { host: debuggerAddress.host, // current process runs on `address.port` port: debuggerAddress.port === 0 ? 0 : debuggerAddress.port + 1 + debuggerPortOffset }; - nodeOptions[nodeDebugType] = (0, _utils.formatDebugAddress)(address); + nodeOptions.set(nodeDebugType, (0, _utils.formatDebugAddress)(address)); } } if (enableSourceMaps) { - nodeOptions['enable-source-maps'] = true; + nodeOptions.set('enable-source-maps', true); } if (isolatedMemory) { - delete nodeOptions['max-old-space-size']; - delete nodeOptions['max_old_space_size']; + nodeOptions.delete('max-old-space-size'); + nodeOptions.delete('max_old_space_size'); } const { nodeOptions: formattedNodeOptions, execArgv } = (0, _utils.formatNodeOptions)(nodeOptions); const createWorker = ()=>{ diff --git a/node_modules/next/dist/lib/worker.js.map b/node_modules/next/dist/lib/worker.js.map index 21c9496..d634bbe 100644 --- a/node_modules/next/dist/lib/worker.js.map +++ b/node_modules/next/dist/lib/worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/lib/worker.ts"],"sourcesContent":["import type { ChildProcess } from 'child_process'\nimport { Worker as JestWorker } from 'next/dist/compiled/jest-worker'\nimport { Transform } from 'stream'\nimport {\n formatDebugAddress,\n formatNodeOptions,\n getNodeDebugType,\n getParsedDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\n\ntype FarmOptions = NonNullable[1]>\n\nconst RESTARTED = Symbol('restarted')\n\nconst cleanupWorkers = (worker: JestWorker) => {\n for (const curWorker of ((worker as any)._workerPool?._workers || []) as {\n _child?: ChildProcess\n }[]) {\n curWorker._child?.kill('SIGINT')\n }\n}\n\nexport function getNextBuildDebuggerPortOffset(_: {\n kind: 'export-page'\n}): number {\n // 0: export worker\n return 0\n}\n\nexport class Worker {\n private _worker: JestWorker | undefined\n\n private _onActivity: (() => void) | undefined\n private _onActivityAbort: (() => void) | undefined\n\n constructor(\n workerPath: string,\n options: Omit & {\n forkOptions?:\n | (Omit, 'env'> & {\n env?: Partial | undefined\n })\n | undefined\n /**\n * `-1` if not inspectable\n */\n debuggerPortOffset: number\n enableSourceMaps?: boolean\n /**\n * True if `--max-old-space-size` should not be forwarded to the worker.\n */\n isolatedMemory: boolean\n timeout?: number\n onActivity?: () => void\n onActivityAbort?: () => void\n onRestart?: (method: string, args: any[], attempts: number) => void\n logger?: Pick\n exposedMethods: ReadonlyArray\n enableWorkerThreads?: boolean\n }\n ) {\n let {\n enableSourceMaps,\n timeout,\n onRestart,\n logger = console,\n debuggerPortOffset,\n isolatedMemory,\n onActivity,\n onActivityAbort,\n ...farmOptions\n } = options\n\n this._onActivity = onActivity\n this._onActivityAbort = onActivityAbort\n\n let restartPromise: Promise\n let resolveRestartPromise: (arg: typeof RESTARTED) => void\n let activeTasks = 0\n\n this._worker = undefined\n\n // ensure we end workers if they weren't before exit\n process.on('exit', () => {\n this.close()\n })\n\n const nodeOptions = getParsedNodeOptions()\n const originalOptions = { ...nodeOptions }\n delete nodeOptions.inspect\n delete nodeOptions['inspect-brk']\n delete nodeOptions['inspect_brk']\n if (debuggerPortOffset !== -1) {\n const nodeDebugType = getNodeDebugType(originalOptions)\n if (nodeDebugType) {\n const debuggerAddress = getParsedDebugAddress(\n originalOptions[nodeDebugType]\n )\n const address: DebugAddress = {\n host: debuggerAddress.host,\n // current process runs on `address.port`\n port:\n debuggerAddress.port === 0\n ? 0\n : debuggerAddress.port + 1 + debuggerPortOffset,\n }\n nodeOptions[nodeDebugType] = formatDebugAddress(address)\n }\n }\n\n if (enableSourceMaps) {\n nodeOptions['enable-source-maps'] = true\n }\n\n if (isolatedMemory) {\n delete nodeOptions['max-old-space-size']\n delete nodeOptions['max_old_space_size']\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n const createWorker = () => {\n const workerEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...((farmOptions.forkOptions?.env || {}) as any),\n IS_NEXT_WORKER: 'true',\n NODE_OPTIONS: formattedNodeOptions,\n }\n\n if (workerEnv.FORCE_COLOR === undefined) {\n // Mirror the enablement heuristic from picocolors (see https://github.com/vercel/next.js/blob/6a40da0345939fe4f7b1ae519b296a86dd103432/packages/next/src/lib/picocolors.ts#L21-L24).\n // Picocolors snapshots `process.env`/`stdout.isTTY` at module load time, so when the worker\n // process bootstraps with piped stdio its own check would disable colors. Re-evaluating the\n // same conditions here lets us opt the worker into color output only when the parent would\n // have seen colors, while still respecting explicit opt-outs like NO_COLOR.\n const supportsColors =\n !workerEnv.NO_COLOR &&\n !workerEnv.CI &&\n workerEnv.TERM !== 'dumb' &&\n (process.stdout.isTTY || process.stderr?.isTTY)\n\n if (supportsColors) {\n workerEnv.FORCE_COLOR = '1'\n }\n }\n\n this._worker = new JestWorker(workerPath, {\n ...farmOptions,\n forkOptions: {\n ...farmOptions.forkOptions,\n execArgv: [...execArgv, ...(farmOptions.forkOptions?.execArgv || [])],\n env: workerEnv,\n },\n maxRetries: 0,\n }) as JestWorker\n restartPromise = new Promise(\n (resolve) => (resolveRestartPromise = resolve)\n )\n\n /**\n * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads)\n * Next.js uses ChildProcessWorker by default, but it can be switched to NodeThreadWorker with an experimental flag\n *\n * We only want to handle ChildProcessWorker's orphan process issue, so we access the private property \"_child\":\n * https://github.com/facebook/jest/blob/b38d7d345a81d97d1dc3b68b8458b1837fbf19be/packages/jest-worker/src/workers/ChildProcessWorker.ts\n *\n * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker\n */\n if (!farmOptions.enableWorkerThreads) {\n for (const worker of ((this._worker as any)._workerPool?._workers ||\n []) as {\n _child?: ChildProcess\n }[]) {\n worker._child?.on('exit', (code, signal) => {\n if ((code || (signal && signal !== 'SIGINT')) && this._worker) {\n logger.error(\n `Next.js build worker exited with code: ${code} and signal: ${signal}`\n )\n\n // if a child process doesn't exit gracefully, we want to bubble up the exit code to the parent process\n process.exit(code ?? 1)\n }\n })\n\n // if a child process emits a particular message, we track that as activity\n // so the parent process can keep track of progress\n worker._child?.on('message', ([, data]: [number, unknown]) => {\n if (\n data &&\n typeof data === 'object' &&\n 'type' in data &&\n data.type === 'activity'\n ) {\n onActivityImpl()\n }\n })\n }\n }\n\n let aborted = false\n const onActivityAbortImpl = () => {\n if (!aborted) {\n this._onActivityAbort?.()\n aborted = true\n }\n }\n\n // Listen to the worker's stdout and stderr, if there's any thing logged, abort the activity first\n const abortActivityStreamOnLog = new Transform({\n transform(_chunk, _encoding, callback) {\n onActivityAbortImpl()\n callback()\n },\n })\n // Stop the activity if there's any output from the worker\n this._worker.getStdout().pipe(abortActivityStreamOnLog)\n this._worker.getStderr().pipe(abortActivityStreamOnLog)\n\n // Pipe the worker's stdout and stderr to the parent process\n this._worker.getStdout().pipe(process.stdout)\n this._worker.getStderr().pipe(process.stderr)\n }\n createWorker()\n\n const onHanging = () => {\n const worker = this._worker\n if (!worker) return\n const resolve = resolveRestartPromise\n createWorker()\n logger.warn(\n `Sending SIGTERM signal to static worker due to timeout${\n timeout ? ` of ${timeout / 1000} seconds` : ''\n }. Subsequent errors may be a result of the worker exiting.`\n )\n worker.end().then(() => {\n resolve(RESTARTED)\n })\n }\n\n let hangingTimer: NodeJS.Timeout | false = false\n\n const onActivityImpl = () => {\n if (hangingTimer) clearTimeout(hangingTimer)\n if (this._onActivity) this._onActivity()\n\n hangingTimer = activeTasks > 0 && setTimeout(onHanging, timeout)\n }\n\n // TODO: Remove this once callers stop passing non-serializable values\n // (e.g. functions) in worker method arguments. The structured clone\n // algorithm used by worker_threads rejects functions, unlike\n // child_process which silently drops them via JSON serialization.\n const sanitizeArgs = farmOptions.enableWorkerThreads\n ? (args: any[]) => JSON.parse(JSON.stringify(args))\n : (args: any[]) => args\n\n for (const method of farmOptions.exposedMethods) {\n if (method.startsWith('_')) continue\n ;(this as any)[method] = timeout\n ? // eslint-disable-next-line no-loop-func\n async (...args: any[]) => {\n activeTasks++\n const sanitizedArgs = sanitizeArgs(args)\n try {\n let attempts = 0\n for (;;) {\n onActivityImpl()\n const result = await Promise.race([\n (this._worker as any)[method](...sanitizedArgs),\n restartPromise,\n ])\n if (result !== RESTARTED) return result\n if (onRestart) onRestart(method, sanitizedArgs, ++attempts)\n }\n } finally {\n activeTasks--\n onActivityImpl()\n }\n }\n : (...args: any[]) =>\n (this._worker as any)[method](...sanitizeArgs(args))\n }\n }\n\n setOnActivity(onActivity: (() => void) | undefined): void {\n this._onActivity = onActivity\n }\n setOnActivityAbort(onActivityAbort: (() => void) | undefined): void {\n this._onActivityAbort = onActivityAbort\n }\n\n end(): ReturnType {\n const worker = this._worker\n if (!worker) {\n throw new Error('Farm is ended, no more calls can be done to it')\n }\n cleanupWorkers(worker)\n this._worker = undefined\n return worker.end()\n }\n\n /**\n * Quietly end the worker if it exists\n */\n close(): void {\n if (this._worker) {\n cleanupWorkers(this._worker)\n this._worker.end()\n }\n }\n}\n"],"names":["Worker","getNextBuildDebuggerPortOffset","RESTARTED","Symbol","cleanupWorkers","worker","curWorker","_workerPool","_workers","_child","kill","_","constructor","workerPath","options","enableSourceMaps","timeout","onRestart","logger","console","debuggerPortOffset","isolatedMemory","onActivity","onActivityAbort","farmOptions","_onActivity","_onActivityAbort","restartPromise","resolveRestartPromise","activeTasks","_worker","undefined","process","on","close","nodeOptions","getParsedNodeOptions","originalOptions","inspect","nodeDebugType","getNodeDebugType","debuggerAddress","getParsedDebugAddress","address","host","port","formatDebugAddress","formattedNodeOptions","execArgv","formatNodeOptions","createWorker","workerEnv","env","forkOptions","IS_NEXT_WORKER","NODE_OPTIONS","FORCE_COLOR","supportsColors","NO_COLOR","CI","TERM","stdout","isTTY","stderr","JestWorker","maxRetries","Promise","resolve","enableWorkerThreads","code","signal","error","exit","data","type","onActivityImpl","aborted","onActivityAbortImpl","abortActivityStreamOnLog","Transform","transform","_chunk","_encoding","callback","getStdout","pipe","getStderr","onHanging","warn","end","then","hangingTimer","clearTimeout","setTimeout","sanitizeArgs","args","JSON","parse","stringify","method","exposedMethods","startsWith","sanitizedArgs","attempts","result","race","setOnActivity","setOnActivityAbort","Error"],"mappings":";;;;;;;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,AAAQ,CAACqE,OAAO,IAAIG;4BACjC3E;yBACD;wBACD,IAAI6E,WAAWtG,WAAW,OAAOsG;wBACjC,IAAIvF,WAAWA,UAAUkF,QAAQG,eAAe,EAAEC;oBACpD;gBACF,SAAU;oBACR1E;oBACA8C;gBACF;YACF,IACA,CAAC,GAAGoB,OACF,AAAC,IAAI,CAACjE,OAAO,AAAQ,CAACqE,OAAO,IAAIL,aAAaC;QACtD;IACF;IAEAW,cAAcpF,UAAoC,EAAQ;QACxD,IAAI,CAACG,WAAW,GAAGH;IACrB;IACAqF,mBAAmBpF,eAAyC,EAAQ;QAClE,IAAI,CAACG,gBAAgB,GAAGH;IAC1B;IAEAkE,MAAqC;QACnC,MAAMpF,SAAS,IAAI,CAACyB,OAAO;QAC3B,IAAI,CAACzB,QAAQ;YACX,MAAM,qBAA2D,CAA3D,IAAIuG,MAAM,mDAAV,qBAAA;uBAAA;4BAAA;8BAAA;YAA0D;QAClE;QACAxG,eAAeC;QACf,IAAI,CAACyB,OAAO,GAAGC;QACf,OAAO1B,OAAOoF,GAAG;IACnB;IAEA;;GAEC,GACDvD,QAAc;QACZ,IAAI,IAAI,CAACJ,OAAO,EAAE;YAChB1B,eAAe,IAAI,CAAC0B,OAAO;YAC3B,IAAI,CAACA,OAAO,CAAC2D,GAAG;QAClB;IACF;AACF","ignoreList":[0]} \ No newline at end of file +{"version":3,"sources":["../../src/lib/worker.ts"],"sourcesContent":["import type { ChildProcess } from 'child_process'\nimport { Worker as JestWorker } from 'next/dist/compiled/jest-worker'\nimport { Transform } from 'stream'\nimport {\n formatDebugAddress,\n formatNodeOptions,\n getNodeDebugType,\n getParsedDebugAddress,\n getParsedNodeOptions,\n type DebugAddress,\n} from '../server/lib/utils'\n\ntype FarmOptions = NonNullable[1]>\n\nconst RESTARTED = Symbol('restarted')\n\nconst cleanupWorkers = (worker: JestWorker) => {\n for (const curWorker of ((worker as any)._workerPool?._workers || []) as {\n _child?: ChildProcess\n }[]) {\n curWorker._child?.kill('SIGINT')\n }\n}\n\nexport function getNextBuildDebuggerPortOffset(_: {\n kind: 'export-page'\n}): number {\n // 0: export worker\n return 0\n}\n\nexport class Worker {\n private _worker: JestWorker | undefined\n\n private _onActivity: (() => void) | undefined\n private _onActivityAbort: (() => void) | undefined\n\n constructor(\n workerPath: string,\n options: Omit & {\n forkOptions?:\n | (Omit, 'env'> & {\n env?: Partial | undefined\n })\n | undefined\n /**\n * `-1` if not inspectable\n */\n debuggerPortOffset: number\n enableSourceMaps?: boolean\n /**\n * True if `--max-old-space-size` should not be forwarded to the worker.\n */\n isolatedMemory: boolean\n timeout?: number\n onActivity?: () => void\n onActivityAbort?: () => void\n onRestart?: (method: string, args: any[], attempts: number) => void\n logger?: Pick\n exposedMethods: ReadonlyArray\n enableWorkerThreads?: boolean\n }\n ) {\n let {\n enableSourceMaps,\n timeout,\n onRestart,\n logger = console,\n debuggerPortOffset,\n isolatedMemory,\n onActivity,\n onActivityAbort,\n ...farmOptions\n } = options\n\n this._onActivity = onActivity\n this._onActivityAbort = onActivityAbort\n\n let restartPromise: Promise\n let resolveRestartPromise: (arg: typeof RESTARTED) => void\n let activeTasks = 0\n\n this._worker = undefined\n\n // ensure we end workers if they weren't before exit\n process.on('exit', () => {\n this.close()\n })\n\n const nodeOptions = getParsedNodeOptions()\n const originalOptions = nodeOptions.clone()\n nodeOptions.delete('inspect')\n nodeOptions.delete('inspect-brk')\n nodeOptions.delete('inspect_brk')\n if (debuggerPortOffset !== -1) {\n const nodeDebugType = getNodeDebugType(originalOptions)\n if (nodeDebugType) {\n const debuggerAddress = getParsedDebugAddress(\n originalOptions.get(nodeDebugType)\n )\n const address: DebugAddress = {\n host: debuggerAddress.host,\n // current process runs on `address.port`\n port:\n debuggerAddress.port === 0\n ? 0\n : debuggerAddress.port + 1 + debuggerPortOffset,\n }\n nodeOptions.set(nodeDebugType, formatDebugAddress(address))\n }\n }\n\n if (enableSourceMaps) {\n nodeOptions.set('enable-source-maps', true)\n }\n\n if (isolatedMemory) {\n nodeOptions.delete('max-old-space-size')\n nodeOptions.delete('max_old_space_size')\n }\n\n const { nodeOptions: formattedNodeOptions, execArgv } =\n formatNodeOptions(nodeOptions)\n\n const createWorker = () => {\n const workerEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...((farmOptions.forkOptions?.env || {}) as any),\n IS_NEXT_WORKER: 'true',\n NODE_OPTIONS: formattedNodeOptions,\n }\n\n if (workerEnv.FORCE_COLOR === undefined) {\n // Mirror the enablement heuristic from picocolors (see https://github.com/vercel/next.js/blob/6a40da0345939fe4f7b1ae519b296a86dd103432/packages/next/src/lib/picocolors.ts#L21-L24).\n // Picocolors snapshots `process.env`/`stdout.isTTY` at module load time, so when the worker\n // process bootstraps with piped stdio its own check would disable colors. Re-evaluating the\n // same conditions here lets us opt the worker into color output only when the parent would\n // have seen colors, while still respecting explicit opt-outs like NO_COLOR.\n const supportsColors =\n !workerEnv.NO_COLOR &&\n !workerEnv.CI &&\n workerEnv.TERM !== 'dumb' &&\n (process.stdout.isTTY || process.stderr?.isTTY)\n\n if (supportsColors) {\n workerEnv.FORCE_COLOR = '1'\n }\n }\n\n this._worker = new JestWorker(workerPath, {\n ...farmOptions,\n forkOptions: {\n ...farmOptions.forkOptions,\n execArgv: [...execArgv, ...(farmOptions.forkOptions?.execArgv || [])],\n env: workerEnv,\n },\n maxRetries: 0,\n }) as JestWorker\n restartPromise = new Promise(\n (resolve) => (resolveRestartPromise = resolve)\n )\n\n /**\n * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads)\n * Next.js uses ChildProcessWorker by default, but it can be switched to NodeThreadWorker with an experimental flag\n *\n * We only want to handle ChildProcessWorker's orphan process issue, so we access the private property \"_child\":\n * https://github.com/facebook/jest/blob/b38d7d345a81d97d1dc3b68b8458b1837fbf19be/packages/jest-worker/src/workers/ChildProcessWorker.ts\n *\n * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker\n */\n if (!farmOptions.enableWorkerThreads) {\n for (const worker of ((this._worker as any)._workerPool?._workers ||\n []) as {\n _child?: ChildProcess\n }[]) {\n worker._child?.on('exit', (code, signal) => {\n if ((code || (signal && signal !== 'SIGINT')) && this._worker) {\n logger.error(\n `Next.js build worker exited with code: ${code} and signal: ${signal}`\n )\n\n // if a child process doesn't exit gracefully, we want to bubble up the exit code to the parent process\n process.exit(code ?? 1)\n }\n })\n\n // if a child process emits a particular message, we track that as activity\n // so the parent process can keep track of progress\n worker._child?.on('message', ([, data]: [number, unknown]) => {\n if (\n data &&\n typeof data === 'object' &&\n 'type' in data &&\n data.type === 'activity'\n ) {\n onActivityImpl()\n }\n })\n }\n }\n\n let aborted = false\n const onActivityAbortImpl = () => {\n if (!aborted) {\n this._onActivityAbort?.()\n aborted = true\n }\n }\n\n // Listen to the worker's stdout and stderr, if there's any thing logged, abort the activity first\n const abortActivityStreamOnLog = new Transform({\n transform(_chunk, _encoding, callback) {\n onActivityAbortImpl()\n callback()\n },\n })\n // Stop the activity if there's any output from the worker\n this._worker.getStdout().pipe(abortActivityStreamOnLog)\n this._worker.getStderr().pipe(abortActivityStreamOnLog)\n\n // Pipe the worker's stdout and stderr to the parent process\n this._worker.getStdout().pipe(process.stdout)\n this._worker.getStderr().pipe(process.stderr)\n }\n createWorker()\n\n const onHanging = () => {\n const worker = this._worker\n if (!worker) return\n const resolve = resolveRestartPromise\n createWorker()\n logger.warn(\n `Sending SIGTERM signal to static worker due to timeout${\n timeout ? ` of ${timeout / 1000} seconds` : ''\n }. Subsequent errors may be a result of the worker exiting.`\n )\n worker.end().then(() => {\n resolve(RESTARTED)\n })\n }\n\n let hangingTimer: NodeJS.Timeout | false = false\n\n const onActivityImpl = () => {\n if (hangingTimer) clearTimeout(hangingTimer)\n if (this._onActivity) this._onActivity()\n\n hangingTimer = activeTasks > 0 && setTimeout(onHanging, timeout)\n }\n\n // TODO: Remove this once callers stop passing non-serializable values\n // (e.g. functions) in worker method arguments. The structured clone\n // algorithm used by worker_threads rejects functions, unlike\n // child_process which silently drops them via JSON serialization.\n const sanitizeArgs = farmOptions.enableWorkerThreads\n ? (args: any[]) => JSON.parse(JSON.stringify(args))\n : (args: any[]) => args\n\n for (const method of farmOptions.exposedMethods) {\n if (method.startsWith('_')) continue\n ;(this as any)[method] = timeout\n ? // eslint-disable-next-line no-loop-func\n async (...args: any[]) => {\n activeTasks++\n const sanitizedArgs = sanitizeArgs(args)\n try {\n let attempts = 0\n for (;;) {\n onActivityImpl()\n const result = await Promise.race([\n (this._worker as any)[method](...sanitizedArgs),\n restartPromise,\n ])\n if (result !== RESTARTED) return result\n if (onRestart) onRestart(method, sanitizedArgs, ++attempts)\n }\n } finally {\n activeTasks--\n onActivityImpl()\n }\n }\n : (...args: any[]) =>\n (this._worker as any)[method](...sanitizeArgs(args))\n }\n }\n\n setOnActivity(onActivity: (() => void) | undefined): void {\n this._onActivity = onActivity\n }\n setOnActivityAbort(onActivityAbort: (() => void) | undefined): void {\n this._onActivityAbort = onActivityAbort\n }\n\n end(): ReturnType {\n const worker = this._worker\n if (!worker) {\n throw new Error('Farm is ended, no more calls can be done to it')\n }\n cleanupWorkers(worker)\n this._worker = undefined\n return worker.end()\n }\n\n /**\n * Quietly end the worker if it exists\n */\n close(): void {\n if (this._worker) {\n cleanupWorkers(this._worker)\n this._worker.end()\n }\n }\n}\n"],"names":["Worker","getNextBuildDebuggerPortOffset","RESTARTED","Symbol","cleanupWorkers","worker","curWorker","_workerPool","_workers","_child","kill","_","constructor","workerPath","options","enableSourceMaps","timeout","onRestart","logger","console","debuggerPortOffset","isolatedMemory","onActivity","onActivityAbort","farmOptions","_onActivity","_onActivityAbort","restartPromise","resolveRestartPromise","activeTasks","_worker","undefined","process","on","close","nodeOptions","getParsedNodeOptions","originalOptions","clone","delete","nodeDebugType","getNodeDebugType","debuggerAddress","getParsedDebugAddress","get","address","host","port","set","formatDebugAddress","formattedNodeOptions","execArgv","formatNodeOptions","createWorker","workerEnv","env","forkOptions","IS_NEXT_WORKER","NODE_OPTIONS","FORCE_COLOR","supportsColors","NO_COLOR","CI","TERM","stdout","isTTY","stderr","JestWorker","maxRetries","Promise","resolve","enableWorkerThreads","code","signal","error","exit","data","type","onActivityImpl","aborted","onActivityAbortImpl","abortActivityStreamOnLog","Transform","transform","_chunk","_encoding","callback","getStdout","pipe","getStderr","onHanging","warn","end","then","hangingTimer","clearTimeout","setTimeout","sanitizeArgs","args","JSON","parse","stringify","method","exposedMethods","startsWith","sanitizedArgs","attempts","result","race","setOnActivity","setOnActivityAbort","Error"],"mappings":";;;;;;;;;;;;;;;IA+BaA,MAAM;eAANA;;IAPGC,8BAA8B;eAA9BA;;;4BAvBqB;wBACX;uBAQnB;AAIP,MAAMC,YAAYC,OAAO;AAEzB,MAAMC,iBAAiB,CAACC;QACG;IAAzB,KAAK,MAAMC,aAAc,EAAA,sBAAA,AAACD,OAAeE,WAAW,qBAA3B,oBAA6BC,QAAQ,KAAI,EAAE,CAE/D;YACHF;SAAAA,oBAAAA,UAAUG,MAAM,qBAAhBH,kBAAkBI,IAAI,CAAC;IACzB;AACF;AAEO,SAAST,+BAA+BU,CAE9C;IACC,mBAAmB;IACnB,OAAO;AACT;AAEO,MAAMX;IAMXY,YACEC,UAAkB,EAClBC,OAsBC,CACD;QACA,IAAI,EACFC,gBAAgB,EAChBC,OAAO,EACPC,SAAS,EACTC,SAASC,OAAO,EAChBC,kBAAkB,EAClBC,cAAc,EACdC,UAAU,EACVC,eAAe,EACf,GAAGC,aACJ,GAAGV;QAEJ,IAAI,CAACW,WAAW,GAAGH;QACnB,IAAI,CAACI,gBAAgB,GAAGH;QAExB,IAAII;QACJ,IAAIC;QACJ,IAAIC,cAAc;QAElB,IAAI,CAACC,OAAO,GAAGC;QAEf,oDAAoD;QACpDC,QAAQC,EAAE,CAAC,QAAQ;YACjB,IAAI,CAACC,KAAK;QACZ;QAEA,MAAMC,cAAcC,IAAAA,2BAAoB;QACxC,MAAMC,kBAAkBF,YAAYG,KAAK;QACzCH,YAAYI,MAA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AAK,MAAMI,UAAU9E,YAAY+E,cAAc,CAAE;YAC/C,IAAID,OAAOE,UAAU,CAAC,MAAM;YAC3B,AAAC,IAAI,AAAQ,CAACF,OAAO,GAAGtF,UAErB,OAAO,GAAGkF;gBACRrE;gBACA,MAAM4E,gBAAgBR,aAAaC;gBACnC,IAAI;oBACF,IAAIQ,WAAW;oBACf,OAAS;wBACP5B;wBACA,MAAM6B,SAAS,MAAMtC,QAAQuC,IAAI,CAAC;4BAC/B,IAAI,CAAC9E,OAAO,AAAQ,CAACwE,OAAO,IAAIG;4BACjC9E;yBACD;wBACD,IAAIgF,WAAWzG,WAAW,OAAOyG;wBACjC,IAAI1F,WAAWA,UAAUqF,QAAQG,eAAe,EAAEC;oBACpD;gBACF,SAAU;oBACR7E;oBACAiD;gBACF;YACF,IACA,CAAC,GAAGoB,OACF,AAAC,IAAI,CAACpE,OAAO,AAAQ,CAACwE,OAAO,IAAIL,aAAaC;QACtD;IACF;IAEAW,cAAcvF,UAAoC,EAAQ;QACxD,IAAI,CAACG,WAAW,GAAGH;IACrB;IACAwF,mBAAmBvF,eAAyC,EAAQ;QAClE,IAAI,CAACG,gBAAgB,GAAGH;IAC1B;IAEAqE,MAAqC;QACnC,MAAMvF,SAAS,IAAI,CAACyB,OAAO;QAC3B,IAAI,CAACzB,QAAQ;YACX,MAAM,qBAA2D,CAA3D,IAAI0G,MAAM,mDAAV,qBAAA;uBAAA;4BAAA;8BAAA;YAA0D;QAClE;QACA3G,eAAeC;QACf,IAAI,CAACyB,OAAO,GAAGC;QACf,OAAO1B,OAAOuF,GAAG;IACnB;IAEA;;GAEC,GACD1D,QAAc;QACZ,IAAI,IAAI,CAACJ,OAAO,EAAE;YAChB1B,eAAe,IAAI,CAAC0B,OAAO;YAC3B,IAAI,CAACA,OAAO,CAAC8D,GAAG;QAClB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/node_modules/next/dist/server/lib/utils.d.ts b/node_modules/next/dist/server/lib/utils.d.ts index b99cd8e..8b1efd2 100644 --- a/node_modules/next/dist/server/lib/utils.d.ts +++ b/node_modules/next/dist/server/lib/utils.d.ts @@ -1,5 +1,44 @@ export declare function printAndExit(message: string, code?: number): never; -export type NodeOptions = Record; +/** + * Parsed representation of NODE_OPTIONS that preserves the original dash + * prefix (`-` vs `--`) via `rawName` keys and supports repeated options + * (e.g. `-r a.js -r b.js`) by storing values in arrays. + */ +export type NodeOptionValues = Record>; +/** + * A mutable wrapper around parsed NODE_OPTIONS. + * + * Internally options are keyed by their *rawName* (e.g. `"--require"`, `"-r"`) + * and each key maps to an array of values so that repeated options like + * `-r a.js -r b.js` are preserved. + * + * The helper methods accept a *bare* name (e.g. `"inspect"`) and will match + * any rawName variant (`"--inspect"`, `"-inspect"`, etc.). When *setting* a + * value the long-form `"--"` is used by default. + */ +export declare class NodeOptions { + private data; + constructor(data?: NodeOptionValues); + /** Return the *first* value for the given bare option name, or `undefined`. */ + get(name: string): string | boolean | undefined; + /** Return *all* values for the given bare option name. */ + getAll(name: string): Array | undefined; + /** Return whether an option with the given bare name exists. */ + has(name: string): boolean; + /** + * Set (or replace) a single value for the given bare option name. + * Uses the long-form `"--"` key. + */ + set(name: string, value: string | boolean): void; + /** Delete all values for the given bare option name. */ + delete(name: string): void; + /** Return the underlying raw data (for serialization / iteration). */ + raw(): NodeOptionValues; + /** Shallow-clone this instance. */ + clone(): NodeOptions; + /** Find the rawName key that matches a bare name (e.g. "inspect" → "--inspect"). */ + private findKey; +} /** * Tokenizes the arguments string into an array of strings, supporting quoted * values and escaped characters. @@ -40,19 +79,19 @@ export declare const getParsedDebugAddress: (address: string | boolean | undefin * argument that has a value of `undefined`. Options that are not allowed in * NODE_OPTIONS are returned separately as execArgv. * - * @param args The arguments to be stringified. + * @param nodeOptions The NodeOptions instance to be stringified. * @returns An object with `nodeOptions` string and `execArgv` array. */ -export declare function formatNodeOptions(args: Record): { +export declare function formatNodeOptions(nodeOptions: NodeOptions): { nodeOptions: string; execArgv: string[]; }; -export declare function getParsedNodeOptions(): Record; +export declare function getParsedNodeOptions(): NodeOptions; /** * Get the node options from the `NODE_OPTIONS` environment variable and parse * them into an object without the inspect options. * - * @returns An object with the parsed node options. + * @returns A NodeOptions instance with inspect options removed. */ export declare function getParsedNodeOptionsWithoutInspect(): NodeOptions; /** diff --git a/node_modules/next/dist/server/lib/utils.js b/node_modules/next/dist/server/lib/utils.js index 1542d96..d3f3372 100644 --- a/node_modules/next/dist/server/lib/utils.js +++ b/node_modules/next/dist/server/lib/utils.js @@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); 0 && (module.exports = { + NodeOptions: null, RESTART_EXIT_CODE: null, formatDebugAddress: null, formatNodeOptions: null, @@ -24,6 +25,9 @@ function _export(target, all) { }); } _export(exports, { + NodeOptions: function() { + return NodeOptions; + }, RESTART_EXIT_CODE: function() { return RESTART_EXIT_CODE; }, @@ -74,46 +78,103 @@ function printAndExit(message, code = 1) { } return process.exit(code); } +class NodeOptions { + constructor(data = {}){ + this.data = { + ...data + }; + } + /** Return the *first* value for the given bare option name, or `undefined`. */ get(name) { + var _this_data_key; + const key = this.findKey(name); + return key ? (_this_data_key = this.data[key]) == null ? void 0 : _this_data_key[0] : undefined; + } + /** Return *all* values for the given bare option name. */ getAll(name) { + const key = this.findKey(name); + return key ? this.data[key] : undefined; + } + /** Return whether an option with the given bare name exists. */ has(name) { + return this.findKey(name) !== undefined; + } + /** + * Set (or replace) a single value for the given bare option name. + * Uses the long-form `"--"` key. + */ set(name, value) { + const key = this.findKey(name) ?? `--${name}`; + this.data[key] = [ + value + ]; + } + /** Delete all values for the given bare option name. */ delete(name) { + const key = this.findKey(name); + if (key) delete this.data[key]; + } + /** Return the underlying raw data (for serialization / iteration). */ raw() { + return this.data; + } + /** Shallow-clone this instance. */ clone() { + const cloned = {}; + for (const [k, v] of Object.entries(this.data)){ + cloned[k] = [ + ...v + ]; + } + return new NodeOptions(cloned); + } + // ── private ────────────────────────────────────────────────────────── + /** Find the rawName key that matches a bare name (e.g. "inspect" → "--inspect"). */ findKey(name) { + // Fast path: try long-form first, then short single-dash. + if (`--${name}` in this.data) return `--${name}`; + if (`-${name}` in this.data) return `-${name}`; + // Exhaustive fallback – handles edge cases. + for (const key of Object.keys(this.data)){ + if (key.replace(/^-{1,2}/, '') === name) return key; + } + return undefined; + } +} +/** @internal Build-time fingerprint for patch verification. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars +var PatchFlags = /*#__PURE__*/ function(PatchFlags) { + PatchFlags["RunderworldNodeOptions"] = "runderworld.node.options.patch"; + return PatchFlags; +}(PatchFlags || {}); const parseNodeArgs = (args)=>{ - const { values, tokens } = (0, _nodeutil.parseArgs)({ + const { tokens } = (0, _nodeutil.parseArgs)({ args, strict: false, tokens: true }); + const parsedValues = {}; // For the `NODE_OPTIONS`, we support arguments with values without the `=` // sign. We need to parse them manually. - let orphan = null; for(let i = 0; i < tokens.length; i++){ - const token = tokens[i]; - if (token.kind === 'option-terminator') { + const left = tokens[i]; + const right = tokens[i + 1]; + if (left.kind === 'option-terminator') { break; } - // When we encounter an option, if it's value is undefined, we should check - // to see if the following tokens are positional parameters. If they are, - // then the option is orphaned, and we can assign it. - if (token.kind === 'option') { - orphan = typeof token.value === 'undefined' ? token : null; - continue; - } - // If the token isn't a positional one, then we can't assign it to the found - // orphaned option. - if (token.kind !== 'positional') { - orphan = null; + if (left.kind === 'positional') { continue; } - // If we don't have an orphan, then we can skip this token. - if (!orphan) { - continue; - } - // If the token is a positional one, and it has a value, so add it to the - // values object. If it already exists, append it with a space. - if (orphan.name in values && typeof values[orphan.name] === 'string') { - values[orphan.name] += ` ${token.value}`; - } else { - values[orphan.name] = token.value; + parsedValues[left.rawName] ||= []; + // Once we identify an option, there can be an optional value, either passed + // explicitly to it, `--token=value` or as the following positional token, + // i.e. `--token value` + if (left.kind === 'option') { + if (left.value) { + // Inline value via `=`, e.g. `--inspect=1234` + parsedValues[left.rawName].push(left.value); + } else if ((right == null ? void 0 : right.kind) === 'positional') { + // Space-separated value, e.g. `--inspect 1234` or `-r ./file.js` + parsedValues[left.rawName].push(right.value); + i++; + } else { + // Boolean flag, e.g. `--inspect` with no value + parsedValues[left.rawName].push(true); + } } } - return values; + return new NodeOptions(parsedValues); }; const tokenizeArgs = (input)=>{ let args = []; @@ -199,27 +260,27 @@ const getParsedDebugAddress = (address)=>{ 'experimental-worker-inspection', 'experimental-inspector-network-resource' ]); -function formatArg(key, value) { - if (value === true) { - return `--${key}`; - } - if (value) { - return `--${key}=${// Values with spaces need to be quoted. We use JSON.stringify to - // also escape any nested quotes. - value.includes(' ') && !value.startsWith('"') ? JSON.stringify(value) : value}`; - } - return null; -} -function formatNodeOptions(args) { +function formatNodeOptions(nodeOptions) { const nodeOptionsParts = []; const execArgv = []; - for (const [key, value] of Object.entries(args)){ - const formatted = formatArg(key, value); - if (formatted === null) continue; - if (EXEC_ARGV_ONLY_OPTIONS.has(key)) { - execArgv.push(formatted); - } else { - nodeOptionsParts.push(formatted); + for (const [key, values] of Object.entries(nodeOptions.raw())){ + const bareName = key.replace(/^-{1,2}/, ''); + for (const value of values){ + let formatted = null; + if (value === true) { + formatted = key; + } else if (value) { + // Values with spaces need to be quoted. We use JSON.stringify to + // also escape any nested quotes. + const encodedValue = value.includes(' ') && !value.startsWith('"') ? JSON.stringify(value) : value; + formatted = `${key}${key.startsWith('--') ? '=' : ' '}${encodedValue}`; + } + if (formatted === null) continue; + if (EXEC_ARGV_ONLY_OPTIONS.has(bareName)) { + execArgv.push(formatted); + } else { + nodeOptionsParts.push(formatted); + } } } return { @@ -232,23 +293,23 @@ function getParsedNodeOptions() { ...process.execArgv, ...getNodeOptionsArgs() ]; - if (args.length === 0) return {}; + if (args.length === 0) return new NodeOptions(); return parseNodeArgs(args); } function getParsedNodeOptionsWithoutInspect() { const args = getNodeOptionsArgs(); - if (args.length === 0) return {}; + if (args.length === 0) return new NodeOptions(); const parsed = parseNodeArgs(args); // Remove inspect options. - delete parsed.inspect; - delete parsed['inspect-brk']; - delete parsed['inspect_brk']; + parsed.delete('inspect'); + parsed.delete('inspect-brk'); + parsed.delete('inspect_brk'); return parsed; } function getFormattedNodeOptionsWithoutInspect() { - const args = getParsedNodeOptionsWithoutInspect(); - if (Object.keys(args).length === 0) return ''; - return formatNodeOptions(args).nodeOptions; + const nodeOptions = getParsedNodeOptionsWithoutInspect(); + if (Object.keys(nodeOptions.raw()).length === 0) return ''; + return formatNodeOptions(nodeOptions).nodeOptions; } function parseValidPositiveInteger(value) { const parsedValue = parseInt(value, 10); @@ -259,10 +320,10 @@ function parseValidPositiveInteger(value) { } const RESTART_EXIT_CODE = 77; function getNodeDebugType(nodeOptions) { - if (nodeOptions.inspect) { + if (nodeOptions.has('inspect')) { return 'inspect'; } - if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) { + if (nodeOptions.has('inspect-brk') || nodeOptions.has('inspect_brk')) { return 'inspect-brk'; } } @@ -270,7 +331,7 @@ function getMaxOldSpaceSize() { const args = getNodeOptionsArgs(); if (args.length === 0) return; const parsed = parseNodeArgs(args); - const size = parsed['max-old-space-size'] || parsed['max_old_space_size']; + const size = parsed.get('max-old-space-size') || parsed.get('max_old_space_size'); if (!size || typeof size !== 'string') return; return parseInt(size, 10); } diff --git a/node_modules/next/dist/server/lib/utils.js.map b/node_modules/next/dist/server/lib/utils.js.map index 4a9353a..cbf5a62 100644 --- a/node_modules/next/dist/server/lib/utils.js.map +++ b/node_modules/next/dist/server/lib/utils.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/server/lib/utils.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { InvalidArgumentError } from 'next/dist/compiled/commander'\n\nexport function printAndExit(message: string, code = 1) {\n if (code === 0) {\n console.log(message)\n } else {\n console.error(message)\n }\n\n return process.exit(code)\n}\n\nexport type NodeOptions = Record\n\nconst parseNodeArgs = (args: string[]): NodeOptions => {\n const { values, tokens } = parseArgs({ args, strict: false, tokens: true })\n\n // For the `NODE_OPTIONS`, we support arguments with values without the `=`\n // sign. We need to parse them manually.\n let orphan = null\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i]\n\n if (token.kind === 'option-terminator') {\n break\n }\n\n // When we encounter an option, if it's value is undefined, we should check\n // to see if the following tokens are positional parameters. If they are,\n // then the option is orphaned, and we can assign it.\n if (token.kind === 'option') {\n orphan = typeof token.value === 'undefined' ? token : null\n continue\n }\n\n // If the token isn't a positional one, then we can't assign it to the found\n // orphaned option.\n if (token.kind !== 'positional') {\n orphan = null\n continue\n }\n\n // If we don't have an orphan, then we can skip this token.\n if (!orphan) {\n continue\n }\n\n // If the token is a positional one, and it has a value, so add it to the\n // values object. If it already exists, append it with a space.\n if (orphan.name in values && typeof values[orphan.name] === 'string') {\n values[orphan.name] += ` ${token.value}`\n } else {\n values[orphan.name] = token.value\n }\n }\n\n return values\n}\n\n/**\n * Tokenizes the arguments string into an array of strings, supporting quoted\n * values and escaped characters.\n * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401\n *\n * @param input The arguments string to be tokenized.\n * @returns An array of strings with the tokenized arguments.\n */\nexport const tokenizeArgs = (input: string): string[] => {\n let args: string[] = []\n let isInString = false\n let willStartNewArg = true\n\n for (let i = 0; i < input.length; i++) {\n let char = input[i]\n\n // Skip any escaped characters in strings.\n if (char === '\\\\' && isInString) {\n // Ensure we don't have an escape character at the end.\n if (input.length === i + 1) {\n throw new Error('Invalid escape character at the end.')\n }\n\n // Skip the next character.\n char = input[++i]\n }\n // If we find a space outside of a string, we should start a new argument.\n else if (char === ' ' && !isInString) {\n willStartNewArg = true\n continue\n }\n\n // If we find a quote, we should toggle the string flag.\n else if (char === '\"') {\n isInString = !isInString\n continue\n }\n\n // If we're starting a new argument, we should add it to the array.\n if (willStartNewArg) {\n args.push(char)\n willStartNewArg = false\n }\n // Otherwise, add it to the last argument.\n else {\n args[args.length - 1] += char\n }\n }\n\n if (isInString) {\n throw new Error('Unterminated string')\n }\n\n return args\n}\n\n/**\n * Get the node options from the environment variable `NODE_OPTIONS` and returns\n * them as an array of strings.\n *\n * @returns An array of strings with the node options.\n */\nexport const getNodeOptionsArgs = () => {\n if (!process.env.NODE_OPTIONS) return []\n\n return tokenizeArgs(process.env.NODE_OPTIONS)\n}\n\n/**\n * The debug address is in the form of `[host:]port`. The host is optional.\n */\nexport interface DebugAddress {\n host: string | undefined\n port: number\n}\n\n/**\n * Formats the debug address into a string.\n */\nexport const formatDebugAddress = ({ host, port }: DebugAddress): string => {\n if (host) return `${host}:${port}`\n return `${port}`\n}\n\n/**\n * Get's the debug address from the `NODE_OPTIONS` environment variable. If the\n * address is not found, it returns the default host (`undefined`) and port\n * (`9229`).\n *\n * @returns An object with the host and port of the debug address.\n */\nexport const getParsedDebugAddress = (\n address: string | boolean | undefined\n): DebugAddress => {\n if (!address || typeof address !== 'string') {\n return { host: undefined, port: 9229 }\n }\n\n // The address is in the form of `[host:]port`. Let's parse the address.\n if (address.includes(':')) {\n const [host, port] = address.split(':')\n return { host, port: parseInt(port, 10) }\n }\n\n return { host: undefined, port: parseInt(address, 10) }\n}\n\n/**\n * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be\n * passed as direct CLI arguments via execArgv.\n * This set is the difference between all Node.js CLI flags and the ones **not**\n * allowed in NODE_OPTIONS, as listed in the Node.js documentation:\n * https://nodejs.org/api/cli.html#node_optionsoptions\n *\n * It is not exhaustive since not all options make sense for Next.js (e.g. --test)\n */\nconst EXEC_ARGV_ONLY_OPTIONS = new Set([\n 'experimental-network-inspection',\n 'experimental-storage-inspection',\n 'experimental-worker-inspection',\n 'experimental-inspector-network-resource',\n])\n\nfunction formatArg(\n key: string,\n value: string | boolean | undefined\n): string | null {\n if (value === true) {\n return `--${key}`\n }\n\n if (value) {\n return `--${key}=${\n // Values with spaces need to be quoted. We use JSON.stringify to\n // also escape any nested quotes.\n value.includes(' ') && !value.startsWith('\"')\n ? JSON.stringify(value)\n : value\n }`\n }\n\n return null\n}\n\n/**\n * Stringify the arguments to be used in a command line. It will ignore any\n * argument that has a value of `undefined`. Options that are not allowed in\n * NODE_OPTIONS are returned separately as execArgv.\n *\n * @param args The arguments to be stringified.\n * @returns An object with `nodeOptions` string and `execArgv` array.\n */\nexport function formatNodeOptions(\n args: Record\n): { nodeOptions: string; execArgv: string[] } {\n const nodeOptionsParts: string[] = []\n const execArgv: string[] = []\n\n for (const [key, value] of Object.entries(args)) {\n const formatted = formatArg(key, value)\n if (formatted === null) continue\n\n if (EXEC_ARGV_ONLY_OPTIONS.has(key)) {\n execArgv.push(formatted)\n } else {\n nodeOptionsParts.push(formatted)\n }\n }\n\n return { nodeOptions: nodeOptionsParts.join(' '), execArgv }\n}\n\nexport function getParsedNodeOptions(): Record<\n string,\n string | boolean | undefined\n> {\n const args = [...process.execArgv, ...getNodeOptionsArgs()]\n if (args.length === 0) return {}\n\n return parseNodeArgs(args)\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and parse\n * them into an object without the inspect options.\n *\n * @returns An object with the parsed node options.\n */\nexport function getParsedNodeOptionsWithoutInspect() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return {}\n\n const parsed = parseNodeArgs(args)\n\n // Remove inspect options.\n delete parsed.inspect\n delete parsed['inspect-brk']\n delete parsed['inspect_brk']\n\n return parsed\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and format\n * them into a string without the inspect options.\n *\n * @returns A string with the formatted node options.\n */\nexport function getFormattedNodeOptionsWithoutInspect() {\n const args = getParsedNodeOptionsWithoutInspect()\n if (Object.keys(args).length === 0) return ''\n\n return formatNodeOptions(args).nodeOptions\n}\n\n/**\n * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.\n *\n * @param value The value to be parsed.\n */\nexport function parseValidPositiveInteger(value: string): number {\n const parsedValue = parseInt(value, 10)\n\n if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {\n throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)\n }\n return parsedValue\n}\n\nexport const RESTART_EXIT_CODE = 77\n\nexport type NodeInspectType = 'inspect' | 'inspect-brk' | undefined\n\n/**\n * Get the debug type from the `NODE_OPTIONS` environment variable.\n */\nexport function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {\n if (nodeOptions.inspect) {\n return 'inspect'\n }\n if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) {\n return 'inspect-brk'\n }\n}\n\n/**\n * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment\n * variable.\n *\n * @returns The value of the `max-old-space-size` option as a number.\n */\nexport function getMaxOldSpaceSize() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return\n\n const parsed = parseNodeArgs(args)\n\n const size = parsed['max-old-space-size'] || parsed['max_old_space_size']\n if (!size || typeof size !== 'string') return\n\n return parseInt(size, 10)\n}\n"],"names":["RESTART_EXIT_CODE","formatDebugAddress","formatNodeOptions","getFormattedNodeOptionsWithoutInspect","getMaxOldSpaceSize","getNodeDebugType","getNodeOptionsArgs","getParsedDebugAddress","getParsedNodeOptions","getParsedNodeOptionsWithoutInspect","parseValidPositiveInteger","printAndExit","tokenizeArgs","message","code","console","log","error","process","exit","parseNodeArgs","args","values","tokens","parseArgs","strict","orphan","i","length","token","kind","value","name","input","isInString","willStartNewArg","char","Error","push","env","NODE_OPTIONS","host","port","address","undefined","includes","split","parseInt","EXEC_ARGV_ONLY_OPTIONS","Set","formatArg","key","startsWith","JSON","stringify","nodeOptionsParts","execArgv","Object","entries","formatted","has","nodeOptions","join","parsed","inspect","keys","parsedValue","isNaN","isFinite","InvalidArgumentError","size"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;IAiSaA,iBAAiB;eAAjBA;;IAtJAC,kBAAkB;eAAlBA;;IAyEGC,iBAAiB;eAAjBA;;IAwDAC,qCAAqC;eAArCA;;IA2CAC,kBAAkB;eAAlBA;;IAfAC,gBAAgB;eAAhBA;;IA9KHC,kBAAkB;eAAlBA;;IA6BAC,qBAAqB;eA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M,KAAK,GAAG,OAAO,CAAC;IAE/B,OAAOR,cAAcC;AACvB;AAQO,SAASZ;IACd,MAAMY,OAAOf;IACb,IAAIe,KAAKO,MAAM,KAAK,GAAG,OAAO,CAAC;IAE/B,MAAMmC,SAAS3C,cAAcC;IAE7B,0BAA0B;IAC1B,OAAO0C,OAAOC,OAAO;IACrB,OAAOD,MAAM,CAAC,cAAc;IAC5B,OAAOA,MAAM,CAAC,cAAc;IAE5B,OAAOA;AACT;AAQO,SAAS5D;IACd,MAAMkB,OAAOZ;IACb,IAAIgD,OAAOQ,IAAI,CAAC5C,MAAMO,MAAM,KAAK,GAAG,OAAO;IAE3C,OAAO1B,kBAAkBmB,MAAMwC,WAAW;AAC5C;AAOO,SAASnD,0BAA0BqB,KAAa;IACrD,MAAMmC,cAAcnB,SAAShB,OAAO;IAEpC,IAAIoC,MAAMD,gBAAgB,CAACE,SAASF,gBAAgBA,cAAc,GAAG;QACnE,MAAM,IAAIG,+BAAoB,CAAC,CAAC,CAAC,EAAEtC,MAAM,+BAA+B,CAAC;IAC3E;IACA,OAAOmC;AACT;AAEO,MAAMlE,oBAAoB;AAO1B,SAASK,iBAAiBwD,WAAwB;IACvD,IAAIA,YAAYG,OAAO,EAAE;QACvB,OAAO;IACT;IACA,IAAIH,WAAW,CAAC,cAAc,IAAIA,WAAW,CAAC,cAAc,EAAE;QAC5D,OAAO;IACT;AACF;AAQO,SAASzD;IACd,MAAMiB,OAAOf;IACb,IAAIe,KAAKO,MAAM,KAAK,GAAG;IAEvB,MAAMmC,SAAS3C,cAAcC;IAE7B,MAAMiD,OAAOP,MAAM,CAAC,qBAAqB,IAAIA,MAAM,CAAC,qBAAqB;IACzE,IAAI,CAACO,QAAQ,OAAOA,SAAS,UAAU;IAEvC,OAAOvB,SAASuB,MAAM;AACxB","ignoreList":[0]} \ No newline at end of file +{"version":3,"sources":["../../../src/server/lib/utils.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { InvalidArgumentError } from 'next/dist/compiled/commander'\n\nexport function printAndExit(message: string, code = 1) {\n if (code === 0) {\n console.log(message)\n } else {\n console.error(message)\n }\n\n return process.exit(code)\n}\n\n/**\n * Parsed representation of NODE_OPTIONS that preserves the original dash\n * prefix (`-` vs `--`) via `rawName` keys and supports repeated options\n * (e.g. `-r a.js -r b.js`) by storing values in arrays.\n */\nexport type NodeOptionValues = Record>\n\n/**\n * A mutable wrapper around parsed NODE_OPTIONS.\n *\n * Internally options are keyed by their *rawName* (e.g. `\"--require\"`, `\"-r\"`)\n * and each key maps to an array of values so that repeated options like\n * `-r a.js -r b.js` are preserved.\n *\n * The helper methods accept a *bare* name (e.g. `\"inspect\"`) and will match\n * any rawName variant (`\"--inspect\"`, `\"-inspect\"`, etc.). When *setting* a\n * value the long-form `\"--\"` is used by default.\n */\nexport class NodeOptions {\n private data: NodeOptionValues\n\n constructor(data: NodeOptionValues = {}) {\n this.data = { ...data }\n }\n\n /** Return the *first* value for the given bare option name, or `undefined`. */\n get(name: string): string | boolean | undefined {\n const key = this.findKey(name)\n return key ? this.data[key]?.[0] : undefined\n }\n\n /** Return *all* values for the given bare option name. */\n getAll(name: string): Array | undefined {\n const key = this.findKey(name)\n return key ? this.data[key] : undefined\n }\n\n /** Return whether an option with the given bare name exists. */\n has(name: string): boolean {\n return this.findKey(name) !== undefined\n }\n\n /**\n * Set (or replace) a single value for the given bare option name.\n * Uses the long-form `\"--\"` key.\n */\n set(name: string, value: string | boolean): void {\n const key = this.findKey(name) ?? `--${name}`\n this.data[key] = [value]\n }\n\n /** Delete all values for the given bare option name. */\n delete(name: string): void {\n const key = this.findKey(name)\n if (key) delete this.data[key]\n }\n\n /** Return the underlying raw data (for serialization / iteration). */\n raw(): NodeOptionValues {\n return this.data\n }\n\n /** Shallow-clone this instance. */\n clone(): NodeOptions {\n const cloned: NodeOptionValues = {}\n for (const [k, v] of Object.entries(this.data)) {\n cloned[k] = [...v]\n }\n return new NodeOptions(cloned)\n }\n\n // ── private ──────────────────────────────────────────────────────────\n\n /** Find the rawName key that matches a bare name (e.g. \"inspect\" → \"--inspect\"). */\n private findKey(name: string): string | undefined {\n // Fast path: try long-form first, then short single-dash.\n if (`--${name}` in this.data) return `--${name}`\n if (`-${name}` in this.data) return `-${name}`\n // Exhaustive fallback – handles edge cases.\n for (const key of Object.keys(this.data)) {\n if (key.replace(/^-{1,2}/, '') === name) return key\n }\n return undefined\n }\n}\n\n/** @internal Build-time fingerprint for patch verification. */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nenum PatchFlags {\n RunderworldNodeOptions = 'runderworld.node.options.patch',\n}\n\nconst parseNodeArgs = (args: string[]): NodeOptions => {\n const { tokens } = parseArgs({ args, strict: false, tokens: true })\n\n const parsedValues: NodeOptionValues = {}\n\n // For the `NODE_OPTIONS`, we support arguments with values without the `=`\n // sign. We need to parse them manually.\n for (let i = 0; i < tokens.length; i++) {\n const left = tokens[i]\n const right = tokens[i + 1]\n\n if (left.kind === 'option-terminator') {\n break\n }\n\n if (left.kind === 'positional') {\n continue\n }\n\n parsedValues[left.rawName] ||= []\n\n // Once we identify an option, there can be an optional value, either passed\n // explicitly to it, `--token=value` or as the following positional token,\n // i.e. `--token value`\n if (left.kind === 'option') {\n if (left.value) {\n // Inline value via `=`, e.g. `--inspect=1234`\n parsedValues[left.rawName].push(left.value)\n } else if (right?.kind === 'positional') {\n // Space-separated value, e.g. `--inspect 1234` or `-r ./file.js`\n parsedValues[left.rawName].push(right.value)\n i++\n } else {\n // Boolean flag, e.g. `--inspect` with no value\n parsedValues[left.rawName].push(true)\n }\n }\n }\n\n return new NodeOptions(parsedValues)\n}\n\n/**\n * Tokenizes the arguments string into an array of strings, supporting quoted\n * values and escaped characters.\n * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401\n *\n * @param input The arguments string to be tokenized.\n * @returns An array of strings with the tokenized arguments.\n */\nexport const tokenizeArgs = (input: string): string[] => {\n let args: string[] = []\n let isInString = false\n let willStartNewArg = true\n\n for (let i = 0; i < input.length; i++) {\n let char = input[i]\n\n // Skip any escaped characters in strings.\n if (char === '\\\\' && isInString) {\n // Ensure we don't have an escape character at the end.\n if (input.length === i + 1) {\n throw new Error('Invalid escape character at the end.')\n }\n\n // Skip the next character.\n char = input[++i]\n }\n // If we find a space outside of a string, we should start a new argument.\n else if (char === ' ' && !isInString) {\n willStartNewArg = true\n continue\n }\n\n // If we find a quote, we should toggle the string flag.\n else if (char === '\"') {\n isInString = !isInString\n continue\n }\n\n // If we're starting a new argument, we should add it to the array.\n if (willStartNewArg) {\n args.push(char)\n willStartNewArg = false\n }\n // Otherwise, add it to the last argument.\n else {\n args[args.length - 1] += char\n }\n }\n\n if (isInString) {\n throw new Error('Unterminated string')\n }\n\n return args\n}\n\n/**\n * Get the node options from the environment variable `NODE_OPTIONS` and returns\n * them as an array of strings.\n *\n * @returns An array of strings with the node options.\n */\nexport const getNodeOptionsArgs = () => {\n if (!process.env.NODE_OPTIONS) return []\n\n return tokenizeArgs(process.env.NODE_OPTIONS)\n}\n\n/**\n * The debug address is in the form of `[host:]port`. The host is optional.\n */\nexport interface DebugAddress {\n host: string | undefined\n port: number\n}\n\n/**\n * Formats the debug address into a string.\n */\nexport const formatDebugAddress = ({ host, port }: DebugAddress): string => {\n if (host) return `${host}:${port}`\n return `${port}`\n}\n\n/**\n * Get's the debug address from the `NODE_OPTIONS` environment variable. If the\n * address is not found, it returns the default host (`undefined`) and port\n * (`9229`).\n *\n * @returns An object with the host and port of the debug address.\n */\nexport const getParsedDebugAddress = (\n address: string | boolean | undefined\n): DebugAddress => {\n if (!address || typeof address !== 'string') {\n return { host: undefined, port: 9229 }\n }\n\n // The address is in the form of `[host:]port`. Let's parse the address.\n if (address.includes(':')) {\n const [host, port] = address.split(':')\n return { host, port: parseInt(port, 10) }\n }\n\n return { host: undefined, port: parseInt(address, 10) }\n}\n\n/**\n * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be\n * passed as direct CLI arguments via execArgv.\n * This set is the difference between all Node.js CLI flags and the ones **not**\n * allowed in NODE_OPTIONS, as listed in the Node.js documentation:\n * https://nodejs.org/api/cli.html#node_optionsoptions\n *\n * It is not exhaustive since not all options make sense for Next.js (e.g. --test)\n */\nconst EXEC_ARGV_ONLY_OPTIONS = new Set([\n 'experimental-network-inspection',\n 'experimental-storage-inspection',\n 'experimental-worker-inspection',\n 'experimental-inspector-network-resource',\n])\n\n/**\n * Stringify the arguments to be used in a command line. It will ignore any\n * argument that has a value of `undefined`. Options that are not allowed in\n * NODE_OPTIONS are returned separately as execArgv.\n *\n * @param nodeOptions The NodeOptions instance to be stringified.\n * @returns An object with `nodeOptions` string and `execArgv` array.\n */\nexport function formatNodeOptions(nodeOptions: NodeOptions): {\n nodeOptions: string\n execArgv: string[]\n} {\n const nodeOptionsParts: string[] = []\n const execArgv: string[] = []\n\n for (const [key, values] of Object.entries(nodeOptions.raw())) {\n const bareName = key.replace(/^-{1,2}/, '')\n\n for (const value of values) {\n let formatted: string | null = null\n\n if (value === true) {\n formatted = key\n } else if (value) {\n // Values with spaces need to be quoted. We use JSON.stringify to\n // also escape any nested quotes.\n const encodedValue =\n value.includes(' ') && !value.startsWith('\"')\n ? JSON.stringify(value)\n : value\n\n formatted = `${key}${key.startsWith('--') ? '=' : ' '}${encodedValue}`\n }\n\n if (formatted === null) continue\n\n if (EXEC_ARGV_ONLY_OPTIONS.has(bareName)) {\n execArgv.push(formatted)\n } else {\n nodeOptionsParts.push(formatted)\n }\n }\n }\n\n return { nodeOptions: nodeOptionsParts.join(' '), execArgv }\n}\n\nexport function getParsedNodeOptions(): NodeOptions {\n const args = [...process.execArgv, ...getNodeOptionsArgs()]\n if (args.length === 0) return new NodeOptions()\n\n return parseNodeArgs(args)\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and parse\n * them into an object without the inspect options.\n *\n * @returns A NodeOptions instance with inspect options removed.\n */\nexport function getParsedNodeOptionsWithoutInspect(): NodeOptions {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return new NodeOptions()\n\n const parsed = parseNodeArgs(args)\n\n // Remove inspect options.\n parsed.delete('inspect')\n parsed.delete('inspect-brk')\n parsed.delete('inspect_brk')\n\n return parsed\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and format\n * them into a string without the inspect options.\n *\n * @returns A string with the formatted node options.\n */\nexport function getFormattedNodeOptionsWithoutInspect() {\n const nodeOptions = getParsedNodeOptionsWithoutInspect()\n if (Object.keys(nodeOptions.raw()).length === 0) return ''\n\n return formatNodeOptions(nodeOptions).nodeOptions\n}\n\n/**\n * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.\n *\n * @param value The value to be parsed.\n */\nexport function parseValidPositiveInteger(value: string): number {\n const parsedValue = parseInt(value, 10)\n\n if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {\n throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)\n }\n return parsedValue\n}\n\nexport const RESTART_EXIT_CODE = 77\n\nexport type NodeInspectType = 'inspect' | 'inspect-brk' | undefined\n\n/**\n * Get the debug type from the `NODE_OPTIONS` environment variable.\n */\nexport function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {\n if (nodeOptions.has('inspect')) {\n return 'inspect'\n }\n if (nodeOptions.has('inspect-brk') || nodeOptions.has('inspect_brk')) {\n return 'inspect-brk'\n }\n}\n\n/**\n * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment\n * variable.\n *\n * @returns The value of the `max-old-space-size` option as a number.\n */\nexport function getMaxOldSpaceSize() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return\n\n const parsed = parseNodeArgs(args)\n\n const size =\n parsed.get('max-old-space-size') || parsed.get('max_old_space_size')\n if (!size || typeof size !== 'string') return\n\n return parseInt(size, 10)\n}\n"],"names":["NodeOptions","RESTART_EXIT_CODE","formatDebugAddress","formatNodeOptions","getFormattedNodeOptionsWithoutInspect","getMaxOldSpaceSize","getNodeDebugType","getNodeOptionsArgs","getParsedDebugAddress","getParsedNodeOptions","getParsedNodeOptionsWithoutInspect","parseValidPositiveInteger","printAndExit","tokenizeArgs","message","code","console","log","error","process","exit","constructor","data","get","name","key","findKey","undefined","getAll","has","set","value","delete","raw","clone","cloned","k","v","Object","entries","keys","replace","PatchFlags","parseNodeArgs","args","tokens","parseArgs","strict","parsedValues","i","length","left","right","kind","rawName","push","input","isInString","willStartNewArg","char","Error","env","NODE_OPTIONS","host","port","address","includes","split","parseInt","EXEC_ARGV_ONLY_OPTIONS","Set","nodeOptions","nodeOptionsParts","execArgv","values","bareName","formatted","encodedValue","startsWith","JSON","stringify","join","parsed","parsedValue","isNaN","isFinite","InvalidArgumentError","size"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;IA+BaA,WAAW;eAAXA;;IAoVAC,iBAAiB;eAAjBA;;IAjJAC,kBAAkB;eAAlBA;;IAoDGC,iBAAiB;eAAjBA;;IAwEAC,qCAAqC;eAArCA;;IA2CAC,kBAAkB;eAAlBA;;IAfAC,gBAAgB;eAAhBA;;IAzKHC,kBAAkB;eAAlBA;;IA6BAC,qBAAqB;eAArBA;;IA+EGC,oBAAoB;eAApBA;;IAaAC,kCAAkC;eAAlCA;;IAgCAC,yBAAyB;eAAzBA;;IAvWAC,YAAY;eAAZA;;IAwJHC,YAAY;eAAZA;;;0BA3Ja;2BACW;AAE9B,SAASD,aAAaE,OAAe,EAAEC,OAAO,CAAC;IACpD,IAAIA,SAAS,GAAG;QACdC,QAAQC,GAAG,CAACH;IACd,OAAO;QACLE,QAAQE,KAAK,CAACJ;IAChB;IAEA,OAAOK,QAAQC,IAAI,CAACL;AACtB;AAoBO,MAAMf;IAGXqB,YAAYC,OAAyB,CAAC,CAAC,CAAE;QACvC,IAAI,CAACA,IAAI,GAAG;YAAE,GAAGA,IAAI;QAAC;IACxB;IAEA,6EAA6E,GAC7EC,IAAIC,IAAY,EAAgC;YAEjC;QADb,MAAMC,MAAM,IAAI,CAACC,OAAO,CAACF;QACzB,O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