{"version":3,"sources":["../../../../src/server/dev/hot-reloader-turbopack.ts"],"sourcesContent":["import type { Socket } from 'net'\nimport { mkdir, writeFile } from 'fs/promises'\nimport * as inspector from 'inspector'\nimport { join, extname, relative } from 'path'\nimport { pathToFileURL } from 'url'\n\nimport ws from 'next/dist/compiled/ws'\n\nimport type { OutputState } from '../../build/output/store'\nimport { store as consoleStore } from '../../build/output/store'\nimport type {\n  CompilationError,\n  HmrMessageSentToBrowser,\n  NextJsHotReloaderInterface,\n  ReloadPageMessage,\n  SyncMessage,\n  TurbopackConnectedMessage,\n} from './hot-reloader-types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport type {\n  Update as TurbopackUpdate,\n  Endpoint,\n  WrittenEndpoint,\n  TurbopackResult,\n  Project,\n  Entrypoints,\n  NodeJsHmrUpdate,\n  NodeJsPartialHmrUpdate,\n} from '../../build/swc/types'\nimport { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc'\nimport * as Log from '../../build/output/log'\nimport { BLOCKED_PAGES } from '../../shared/lib/constants'\nimport {\n  getOverlayMiddleware,\n  getSourceMapMiddleware,\n  getOriginalStackFrames,\n} from './middleware-turbopack'\nimport { PageNotFoundError } from '../../shared/lib/utils'\nimport { debounce } from '../utils'\nimport { deleteCache } from './require-cache'\nimport {\n  clearAllModuleContexts,\n  clearModuleContext,\n} from '../lib/render-server'\nimport { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path'\nimport { trace } from '../../trace'\nimport {\n  AssetMapper,\n  type ChangeSubscriptions,\n  type ClientState,\n  handleEntrypoints,\n  handlePagesErrorRoute,\n  handleRouteType,\n  hasEntrypointForKey,\n  msToNs,\n  type ReadyIds,\n  type SendHmr,\n  type StartBuilding,\n  processTopLevelIssues,\n  printNonFatalIssue,\n  normalizedPageToTurbopackStructureRoute,\n} from './turbopack-utils'\nimport {\n  propagateServerField,\n  type ServerFields,\n  type SetupOpts,\n} from '../lib/router-utils/setup-dev-bundler'\nimport { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loader'\nimport { findPagePathData } from './on-demand-entry-handler'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport {\n  type EntryKey,\n  getEntryKey,\n  splitEntryKey,\n} from '../../shared/lib/turbopack/entry-key'\nimport {\n  createBinaryHmrMessageData,\n  FAST_REFRESH_RUNTIME_RELOAD,\n} from './messages'\nimport { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-server'\nimport { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\nimport { isDeferredEntry } from '../../build/entries'\nimport {\n  isMetadataRoute,\n  isMetadataRouteFile,\n} from '../../lib/metadata/is-metadata-route'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'\nimport {\n  formatIssue,\n  isFileSystemCacheEnabledForDev,\n  isWellKnownError,\n  processIssues,\n  renderStyledStringToErrorAnsi,\n  type EntryIssuesMap,\n  type IssuesMap,\n  type TopLevelIssuesMap,\n} from '../../shared/lib/turbopack/utils'\nimport { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'\nimport { devIndicatorServerState } from './dev-indicator-server-state'\nimport { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'\nimport { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'\nimport { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'\nimport { getSupportedBrowsers } from '../../build/get-supported-browsers'\nimport { printBuildErrors } from '../../build/print-build-errors'\nimport {\n  receiveBrowserLogsTurbopack,\n  handleClientFileLogs,\n} from './browser-logs/receive-logs'\nimport { normalizePath } from '../../lib/normalize-path'\nimport {\n  devToolsConfigMiddleware,\n  getDevToolsConfig,\n} from '../../next-devtools/server/devtools-config-middleware'\nimport { getAttachNodejsDebuggerMiddleware } from '../../next-devtools/server/attach-nodejs-debugger-middleware'\nimport {\n  connectReactDebugChannel,\n  connectReactDebugChannelForHtmlRequest,\n  deleteReactDebugChannelForHtmlRequest,\n  setReactDebugChannelForHtmlRequest,\n} from './debug-channel'\nimport {\n  getVersionInfo,\n  matchNextPageBundleRequest,\n} from './hot-reloader-shared-utils'\nimport { getMcpMiddleware } from '../mcp/get-mcp-middleware'\nimport { handleErrorStateResponse } from '../mcp/tools/get-errors'\nimport { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'\nimport { setStackFrameResolver } from '../mcp/tools/utils/format-errors'\nimport { recordMcpTelemetry } from '../mcp/mcp-telemetry-tracker'\nimport { getFileLogger } from './browser-logs/file-logger'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { Lockfile } from '../../build/lockfile'\nimport {\n  sendSerializedErrorsToClient,\n  sendSerializedErrorsToClientForHtmlRequest,\n  setErrorsRscStreamForHtmlRequest,\n} from './serialized-errors'\n\nconst wsServer = new ws.Server({ noServer: true })\nconst isTestMode = !!(\n  process.env.NEXT_TEST_MODE ||\n  process.env.__NEXT_TEST_MODE ||\n  process.env.DEBUG\n)\n\nconst sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())\n\ndeclare const __next__clear_chunk_cache__: (() => void) | null | undefined\n\ndeclare const __turbopack_server_hmr_apply__:\n  | ((update: NodeJsPartialHmrUpdate) => boolean)\n  | undefined\n\ntype ServerHmrSubscriptions = Map<\n  string,\n  AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>\n>\n\nfunction setupServerHmr(\n  project: Project,\n  {\n    clear,\n  }: {\n    clear: () => void | Promise<void>\n  }\n) {\n  const serverHmrSubscriptions: ServerHmrSubscriptions = new Map()\n\n  /**\n   * Subscribe to HMR updates for a server chunk.\n   * @param chunkPath - Server chunk output path (e.g., \"server/chunks/ssr/..._.js\")\n   */\n  function subscribeToServerHmr(chunkPath: string) {\n    if (serverHmrSubscriptions.has(chunkPath)) {\n      return\n    }\n\n    const subscription = project.hmrEvents(chunkPath, HmrTarget.Server)\n    serverHmrSubscriptions.set(chunkPath, subscription)\n\n    // Start listening for changes in background\n    ;(async () => {\n      // Skip initial state\n      await subscription.next()\n\n      for await (const result of subscription) {\n        const update = result as NodeJsHmrUpdate\n\n        // Fully re-evaluate all chunks from disk. Clears the module cache and\n        // notifies browsers to refetch RSC.\n        if (update.type === 'restart') {\n          await clear()\n          continue\n        }\n\n        if (update.type !== 'partial') {\n          continue\n        }\n\n        const instruction = update.instruction\n        if (!instruction || instruction.type !== 'EcmascriptMergedUpdate') {\n          continue\n        }\n\n        if (typeof __turbopack_server_hmr_apply__ === 'function') {\n          const applied = __turbopack_server_hmr_apply__(update)\n          if (!applied) {\n            await clear()\n          }\n        }\n      }\n    })().catch(async (err) => {\n      console.error('[Server HMR] Subscription error:', err)\n      serverHmrSubscriptions.delete(chunkPath)\n      await clear()\n    })\n  }\n\n  // Listen to the Rust bindings update us on changing server HMR chunk paths\n  ;(async () => {\n    try {\n      const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(\n        HmrTarget.Server\n      )\n\n      // Process chunk paths (both initial and subsequent updates)\n      for await (const data of serverHmrChunkPaths) {\n        const currentChunkPaths = new Set<string>(\n          data.chunkNames.filter((path) => path.endsWith('.js'))\n        )\n\n        // Clean up subscriptions for removed chunk paths (like when pages are deleted)\n        const chunkPathsToRemove: string[] = []\n        for (const chunkPath of serverHmrSubscriptions.keys()) {\n          if (!currentChunkPaths.has(chunkPath)) {\n            chunkPathsToRemove.push(chunkPath)\n          }\n        }\n\n        for (const chunkPath of chunkPathsToRemove) {\n          const subscription = serverHmrSubscriptions.get(chunkPath)\n          subscription?.return?.()\n          serverHmrSubscriptions.delete(chunkPath)\n        }\n\n        // Subscribe to HMR events for new server chunks\n        for (const chunkPath of currentChunkPaths) {\n          if (!serverHmrSubscriptions.has(chunkPath)) {\n            subscribeToServerHmr(chunkPath)\n          }\n        }\n      }\n    } catch (err) {\n      console.error('[Server HMR Setup] Error in chunk path subscription:', err)\n    }\n  })()\n\n  return serverHmrSubscriptions\n}\n\n/**\n * Replaces turbopack:///[project] with the specified project in the `source` field.\n */\nfunction rewriteTurbopackSources(\n  projectRoot: string,\n  sourceMap: ModernSourceMapPayload\n): void {\n  if ('sections' in sourceMap) {\n    for (const section of sourceMap.sections) {\n      rewriteTurbopackSources(projectRoot, section.map)\n    }\n  } else {\n    for (let i = 0; i < sourceMap.sources.length; i++) {\n      sourceMap.sources[i] = pathToFileURL(\n        join(\n          projectRoot,\n          sourceMap.sources[i].replace(/turbopack:\\/\\/\\/\\[project\\]/, '')\n        )\n      ).toString()\n    }\n  }\n}\n\nfunction getSourceMapFromTurbopack(\n  project: Project,\n  projectRoot: string,\n  sourceURL: string\n): ModernSourceMapPayload | undefined {\n  let sourceMapJson: string | null = null\n\n  try {\n    sourceMapJson = project.getSourceMapSync(sourceURL)\n  } catch (err) {}\n\n  if (sourceMapJson === null) {\n    return undefined\n  } else {\n    const payload: ModernSourceMapPayload = JSON.parse(sourceMapJson)\n    // The sourcemap from Turbopack is not yet written to disk so its `sources`\n    // are not absolute paths yet. We need to rewrite them to be absolute paths.\n    rewriteTurbopackSources(projectRoot, payload)\n    return payload\n  }\n}\n\nexport async function createHotReloaderTurbopack(\n  opts: SetupOpts & { isSrcDir: boolean },\n  serverFields: ServerFields,\n  distDir: string,\n  resetFetch: () => void,\n  lockfile: Lockfile | undefined,\n  serverFastRefresh?: boolean\n): Promise<NextJsHotReloaderInterface> {\n  const dev = true\n  const buildId = 'development'\n  const { nextConfig, dir: projectPath } = opts\n\n  const bindings = getBindingsSync()\n\n  // Turbopack requires native bindings and cannot run with WASM bindings.\n  // Detect this early and give a clear, actionable error message.\n  if (bindings.isWasm) {\n    throw new Error(\n      `Turbopack is not supported on this platform (${process.platform}/${process.arch}) because native bindings are not available. ` +\n        `Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.\\n\\n` +\n        `To use Next.js on this platform, use Webpack instead:\\n` +\n        `  next dev --webpack\\n\\n` +\n        `For more information, see: https://nextjs.org/docs/app/api-reference/turbopack#supported-platforms`\n    )\n  }\n\n  // For the debugging purpose, check if createNext or equivalent next instance setup in test cases\n  // works correctly. Normally `run-test` hides output so only will be visible when `--debug` flag is used.\n  if (isTestMode) {\n    ;(require('console') as typeof import('console')).log(\n      'Creating turbopack project',\n      {\n        dir: projectPath,\n        testMode: isTestMode,\n      }\n    )\n  }\n\n  const hasRewrites =\n    opts.fsChecker.rewrites.afterFiles.length > 0 ||\n    opts.fsChecker.rewrites.beforeFiles.length > 0 ||\n    opts.fsChecker.rewrites.fallback.length > 0\n\n  const hotReloaderSpan = trace('hot-reloader', undefined, {\n    version: process.env.__NEXT_VERSION as string,\n  })\n  // Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing\n  // of the current `next dev` invocation.\n  hotReloaderSpan.stop()\n\n  // Initialize log monitor for file logging\n  // Enable logging by default in development mode\n  const mcpServerEnabled = !!nextConfig.experimental.mcpServer\n  const fileLogger = getFileLogger()\n  fileLogger.initialize(distDir, mcpServerEnabled)\n\n  const encryptionKey = await generateEncryptionKeyBase64({\n    isBuild: false,\n    distDir,\n  })\n\n  // TODO: Implement\n  let clientRouterFilters: any\n  if (nextConfig.experimental.clientRouterFilter) {\n    // TODO this need to be set correctly for filesystem cache to work\n  }\n\n  const supportedBrowsers = getSupportedBrowsers(projectPath, dev)\n  const currentNodeJsVersion = process.versions.node\n\n  const rootPath =\n    opts.nextConfig.turbopack?.root ||\n    opts.nextConfig.outputFileTracingRoot ||\n    projectPath\n  const project = await bindings.turbo.createProject(\n    {\n      rootPath,\n      projectPath: normalizePath(relative(rootPath, projectPath) || '.'),\n      distDir,\n      nextConfig: opts.nextConfig,\n      watch: {\n        enable: dev,\n        pollIntervalMs: nextConfig.watchOptions?.pollIntervalMs,\n      },\n      dev,\n      env: process.env as Record<string, string>,\n      defineEnv: createDefineEnv({\n        isTurbopack: true,\n        clientRouterFilters,\n        config: nextConfig,\n        dev,\n        distDir,\n        projectPath,\n        fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,\n        hasRewrites,\n        // TODO: Implement\n        middlewareMatchers: undefined,\n        rewrites: opts.fsChecker.rewrites,\n      }),\n      buildId,\n      encryptionKey,\n      previewProps: opts.fsChecker.previewProps,\n      browserslistQuery: supportedBrowsers.join(', '),\n      noMangling: false,\n      writeRoutesHashesManifest: false,\n      currentNodeJsVersion,\n      isPersistentCachingEnabled: isFileSystemCacheEnabledForDev(\n        opts.nextConfig\n      ),\n      nextVersion: process.env.__NEXT_VERSION as string,\n      serverHmr: serverFastRefresh,\n    },\n    {\n      memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,\n      isShortSession: false,\n    }\n  )\n  backgroundLogCompilationEvents(project, {\n    eventTypes: [\n      'StartupCacheInvalidationEvent',\n      'TimingEvent',\n      'SlowFilesystemEvent',\n      'TraceEvent',\n    ],\n    parentSpan: hotReloaderSpan,\n  })\n  setBundlerFindSourceMapImplementation(\n    getSourceMapFromTurbopack.bind(null, project, projectPath)\n  )\n\n  // Set up code frame renderer using native bindings\n  const { installCodeFrameSupport } =\n    require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')\n  installCodeFrameSupport()\n\n  opts.onDevServerCleanup?.(async () => {\n    setBundlerFindSourceMapImplementation(() => undefined)\n    await project.onExit()\n    await lockfile?.unlock()\n  })\n  const entrypointsSubscription = project.entrypointsSubscribe()\n\n  const currentWrittenEntrypoints: Map<EntryKey, WrittenEndpoint> = new Map()\n  const currentEntrypoints: Entrypoints = {\n    global: {\n      app: undefined,\n      document: undefined,\n      error: undefined,\n\n      middleware: undefined,\n      instrumentation: undefined,\n    },\n\n    page: new Map(),\n    app: new Map(),\n  }\n\n  const currentTopLevelIssues: TopLevelIssuesMap = new Map()\n  const currentEntryIssues: EntryIssuesMap = new Map()\n\n  const manifestLoader = new TurbopackManifestLoader({\n    buildId,\n    distDir,\n    encryptionKey,\n    dev: true,\n    sriEnabled: false,\n  })\n\n  // Dev specific\n  const changeSubscriptions: ChangeSubscriptions = new Map()\n  const serverPathState = new Map<string, string>()\n  const readyIds: ReadyIds = new Set()\n  let currentEntriesHandlingResolve: ((value?: unknown) => void) | undefined\n  let currentEntriesHandling = new Promise(\n    (resolve) => (currentEntriesHandlingResolve = resolve)\n  )\n\n  const assetMapper = new AssetMapper()\n\n  // Deferred entries state management\n  const deferredEntriesConfig = nextConfig.experimental.deferredEntries\n  const hasDeferredEntriesConfig =\n    deferredEntriesConfig && deferredEntriesConfig.length > 0\n  let onBeforeDeferredEntriesCalled = false\n  let onBeforeDeferredEntriesPromise: Promise<void> | null = null\n  // Track non-deferred entries that are currently being built\n  const nonDeferredBuildingEntries: Set<string> = new Set()\n\n  // Function to wait for all non-deferred entries to be built\n  async function waitForNonDeferredEntries(): Promise<void> {\n    return new Promise<void>((resolve) => {\n      const checkEntries = () => {\n        // Check if there are any non-deferred entries that are still building\n        if (nonDeferredBuildingEntries.size === 0) {\n          resolve()\n        } else {\n          // Check again after a short delay\n          setTimeout(checkEntries, 100)\n        }\n      }\n      checkEntries()\n    })\n  }\n\n  // Function to handle deferred entry processing\n  async function processDeferredEntry(): Promise<void> {\n    if (!hasDeferredEntriesConfig) return\n\n    // Wait for all non-deferred entries to be built\n    await waitForNonDeferredEntries()\n\n    // Call the onBeforeDeferredEntries callback once\n    if (!onBeforeDeferredEntriesCalled) {\n      onBeforeDeferredEntriesCalled = true\n\n      if (nextConfig.experimental.onBeforeDeferredEntries) {\n        if (!onBeforeDeferredEntriesPromise) {\n          onBeforeDeferredEntriesPromise =\n            nextConfig.experimental.onBeforeDeferredEntries()\n        }\n        await onBeforeDeferredEntriesPromise\n      }\n    } else if (onBeforeDeferredEntriesPromise) {\n      // Wait for any in-progress callback\n      await onBeforeDeferredEntriesPromise\n    }\n  }\n\n  // Track whether HMR is pending - used to call callback once after HMR settles\n  let hmrPendingDeferredCallback = false\n\n  // Debounced function to call onBeforeDeferredEntries after HMR\n  // This prevents rapid-fire calls when turbopack fires many update events\n  // Use 500ms debounce to ensure all rapid updates are batched together\n  const callOnBeforeDeferredEntriesAfterHMR = debounce(() => {\n    // Only call if HMR triggered a need for the callback\n    if (hasDeferredEntriesConfig && hmrPendingDeferredCallback) {\n      hmrPendingDeferredCallback = false\n      onBeforeDeferredEntriesCalled = true\n      if (nextConfig.experimental.onBeforeDeferredEntries) {\n        onBeforeDeferredEntriesPromise =\n          nextConfig.experimental.onBeforeDeferredEntries()\n      }\n    }\n  }, 500)\n\n  function clearRequireCache(\n    key: EntryKey,\n    writtenEndpoint: WrittenEndpoint,\n    {\n      force,\n    }: {\n      // Always clear the cache, don't check if files have changed\n      force?: boolean\n    } = {}\n  ): boolean {\n    if (force) {\n      for (const { path, contentHash } of writtenEndpoint.serverPaths) {\n        // We ignore source maps\n        if (path.endsWith('.map')) continue\n        const localKey = `${key}:${path}`\n        serverPathState.set(localKey, contentHash)\n        serverPathState.set(path, contentHash)\n      }\n    } else {\n      // Figure out if the server files have changed\n      let hasChange = false\n      for (const { path, contentHash } of writtenEndpoint.serverPaths) {\n        // We ignore source maps\n        if (path.endsWith('.map')) continue\n        const localKey = `${key}:${path}`\n        const localHash = serverPathState.get(localKey)\n        const globalHash = serverPathState.get(path)\n        if (\n          (localHash && localHash !== contentHash) ||\n          (globalHash && globalHash !== contentHash)\n        ) {\n          hasChange = true\n          serverPathState.set(localKey, contentHash)\n          serverPathState.set(path, contentHash)\n        } else {\n          if (!localHash) {\n            serverPathState.set(localKey, contentHash)\n          }\n          if (!globalHash) {\n            serverPathState.set(path, contentHash)\n          }\n        }\n      }\n\n      if (!hasChange) {\n        return false\n      }\n    }\n\n    const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>\n      join(distDir, p)\n    )\n\n    const { type: entryType, page: entryPage } = splitEntryKey(key)\n\n    // Server HMR applies to App Router entries built with the Turbopack Node.js\n    // runtime: app pages and regular route handlers. Edge routes, Pages Router\n    // pages, middleware/instrumentation, and metadata routes (manifest.ts,\n    // robots.ts, sitemap.ts, icon.tsx, etc.) are excluded. Metadata routes are\n    // excluded because they serve HTTP responses directly and must re-execute\n    // on every request to pick up file changes; the in-place module update\n    // model of Server HMR does not apply to them.\n    const usesServerHmr =\n      serverFastRefresh &&\n      entryType === 'app' &&\n      writtenEndpoint.type !== 'edge' &&\n      !isMetadataRoute(entryPage)\n\n    const filesToDelete: string[] = []\n    for (const file of serverPaths) {\n      clearModuleContext(file)\n\n      const relativePath = relative(distDir, file)\n      if (\n        // For Pages Router, edge routes, middleware, and manifest files:\n        // clear the sharedCache in evalManifest(), Node.js require.cache,\n        // and edge runtime module contexts.\n        force ||\n        !usesServerHmr ||\n        !serverHmrSubscriptions?.has(relativePath)\n      ) {\n        filesToDelete.push(file)\n      }\n    }\n    deleteCache(filesToDelete)\n\n    // Reset the fetch patch so patchFetch() can re-wrap on the next request.\n    if (serverPaths.length > 0) {\n      resetFetch()\n    }\n\n    // Clear Turbopack's chunk-loading cache so chunks are re-required from disk on\n    // the next request.\n    //\n    // For App Router with server HMR, this is normally skipped as server HMR\n    // manages module updates in-place. However, it *is* required when force is `true`\n    // (like for .env file or tsconfig changes).\n    if (\n      (!usesServerHmr || force) &&\n      typeof __next__clear_chunk_cache__ === 'function'\n    ) {\n      __next__clear_chunk_cache__()\n    }\n\n    return true\n  }\n\n  const buildingIds = new Set()\n\n  const startBuilding: StartBuilding = (id, requestUrl, forceRebuild) => {\n    if (!forceRebuild && readyIds.has(id)) {\n      return () => {}\n    }\n    if (buildingIds.size === 0) {\n      consoleStore.setState(\n        {\n          loading: true,\n          trigger: id,\n          url: requestUrl,\n        } as OutputState,\n        true\n      )\n    }\n    buildingIds.add(id)\n    return function finishBuilding() {\n      if (buildingIds.size === 0) {\n        return\n      }\n      readyIds.add(id)\n      buildingIds.delete(id)\n      if (buildingIds.size === 0) {\n        hmrEventHappened = false\n        consoleStore.setState(\n          {\n            loading: false,\n          } as OutputState,\n          true\n        )\n      }\n    }\n  }\n\n  let serverHmrSubscriptions: ServerHmrSubscriptions | undefined\n\n  let hmrEventHappened = false\n  let hmrHash = 0\n\n  const clientsWithoutHtmlRequestId = new Set<ws>()\n  const clientsByHtmlRequestId = new Map<string, ws>()\n  const cacheStatusesByHtmlRequestId = new Map<string, ServerCacheStatus>()\n  const clientStates = new WeakMap<ws, ClientState>()\n\n  function sendToClient(client: ws, message: HmrMessageSentToBrowser) {\n    const data =\n      typeof message.type === 'number'\n        ? createBinaryHmrMessageData(message)\n        : JSON.stringify(message)\n\n    client.send(data)\n  }\n\n  function sendEnqueuedMessages() {\n    for (const [, issueMap] of currentEntryIssues) {\n      if (\n        [...issueMap.values()].filter((i) => i.severity !== 'warning').length >\n        0\n      ) {\n        // During compilation errors we want to delay the HMR events until errors are fixed\n        return\n      }\n    }\n\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      const state = clientStates.get(client)\n      if (!state) {\n        continue\n      }\n\n      for (const [, issueMap] of state.clientIssues) {\n        if (\n          [...issueMap.values()].filter((i) => i.severity !== 'warning')\n            .length > 0\n        ) {\n          // During compilation errors we want to delay the HMR events until errors are fixed\n          return\n        }\n      }\n\n      for (const message of state.messages.values()) {\n        sendToClient(client, message)\n      }\n      state.messages.clear()\n\n      if (state.turbopackUpdates.length > 0) {\n        sendToClient(client, {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_MESSAGE,\n          data: state.turbopackUpdates,\n        })\n        state.turbopackUpdates.length = 0\n      }\n    }\n  }\n  const sendEnqueuedMessagesDebounce = debounce(sendEnqueuedMessages, 2)\n\n  const sendHmr: SendHmr = (id: string, message: HmrMessageSentToBrowser) => {\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      clientStates.get(client)?.messages.set(id, message)\n    }\n\n    hmrEventHappened = true\n    sendEnqueuedMessagesDebounce()\n  }\n\n  function sendTurbopackMessage(payload: TurbopackUpdate) {\n    // TODO(PACK-2049): For some reason we end up emitting hundreds of issues messages on bigger apps,\n    //   a lot of which are duplicates.\n    //   They are currently not handled on the client at all, so might as well not send them for now.\n    payload.diagnostics = []\n    payload.issues = []\n\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      clientStates.get(client)?.turbopackUpdates.push(payload)\n    }\n\n    hmrEventHappened = true\n    sendEnqueuedMessagesDebounce()\n  }\n\n  async function subscribeToClientChanges(\n    key: EntryKey,\n    includeIssues: boolean,\n    endpoint: Endpoint,\n    createMessage: (\n      change: TurbopackResult,\n      hash: string\n    ) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void,\n    onError?: (\n      error: Error\n    ) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void\n  ) {\n    if (changeSubscriptions.has(key)) {\n      return\n    }\n\n    const { side } = splitEntryKey(key)\n\n    const changedPromise = endpoint[`${side}Changed`](includeIssues)\n    changeSubscriptions.set(key, changedPromise)\n    try {\n      const changed = await changedPromise\n\n      for await (const change of changed) {\n        processIssues(currentEntryIssues, key, change, false, true)\n        // TODO: Get an actual content hash from Turbopack.\n        const message = await createMessage(change, String(++hmrHash))\n        if (message) {\n          sendHmr(key, message)\n        }\n      }\n    } catch (e) {\n      changeSubscriptions.delete(key)\n      const payload = await onError?.(e as Error)\n      if (payload) {\n        sendHmr(key, payload)\n      }\n      return\n    }\n    changeSubscriptions.delete(key)\n  }\n\n  async function unsubscribeFromClientChanges(key: EntryKey) {\n    const subscription = await changeSubscriptions.get(key)\n    if (subscription) {\n      await subscription.return?.()\n      changeSubscriptions.delete(key)\n    }\n    currentEntryIssues.delete(key)\n  }\n\n  async function subscribeToClientHmrEvents(client: ws, id: string) {\n    const key = getEntryKey('assets', 'client', id)\n    if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n      // maybe throw an error / force the client to reload?\n      return\n    }\n\n    const state = clientStates.get(client)\n    if (!state || state.subscriptions.has(id)) {\n      return\n    }\n\n    const subscription = project!.hmrEvents(id, HmrTarget.Client)\n    state.subscriptions.set(id, subscription)\n\n    // The subscription will always emit once, which is the initial\n    // computation. This is not a change, so swallow it.\n    try {\n      await subscription.next()\n\n      for await (const data of subscription) {\n        processIssues(state.clientIssues, key, data, false, true)\n        if (data.type !== 'issues') {\n          sendTurbopackMessage(data as TurbopackUpdate)\n        }\n      }\n    } catch (e) {\n      // The client might be using an HMR session from a previous server, tell them\n      // to fully reload the page to resolve the issue. We can't use\n      // `hotReloader.send` since that would force every connected client to\n      // reload, only this client is out of date.\n      const reloadMessage: ReloadPageMessage = {\n        type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n        data: `error in HMR event subscription for ${id}: ${e}`,\n      }\n      sendToClient(client, reloadMessage)\n      client.close()\n      return\n    }\n  }\n\n  function unsubscribeFromClientHmrEvents(client: ws, id: string) {\n    const state = clientStates.get(client)\n    if (!state) {\n      return\n    }\n\n    const subscription = state.subscriptions.get(id)\n    subscription?.return!()\n\n    const key = getEntryKey('assets', 'client', id)\n    state.clientIssues.delete(key)\n  }\n\n  async function handleEntrypointsSubscription() {\n    for await (const entrypoints of entrypointsSubscription) {\n      if (!currentEntriesHandlingResolve) {\n        currentEntriesHandling = new Promise(\n          // eslint-disable-next-line no-loop-func\n          (resolve) => (currentEntriesHandlingResolve = resolve)\n        )\n      }\n\n      // Always process issues/diagnostics, even if there are no entrypoints yet\n      processTopLevelIssues(currentTopLevelIssues, entrypoints)\n\n      // Certain crtical issues prevent any entrypoints from being constructed so return early\n      if (!('routes' in entrypoints)) {\n        printBuildErrors(entrypoints, true)\n\n        currentEntriesHandlingResolve!()\n        currentEntriesHandlingResolve = undefined\n        continue\n      }\n\n      const routes = entrypoints.routes\n      const existingRoutes = [\n        ...currentEntrypoints.app.keys(),\n        ...currentEntrypoints.page.keys(),\n      ]\n      const newRoutes = [...routes.keys()]\n\n      const addedRoutes = newRoutes.filter(\n        (route) =>\n          !currentEntrypoints.app.has(route) &&\n          !currentEntrypoints.page.has(route)\n      )\n      const removedRoutes = existingRoutes.filter((route) => !routes.has(route))\n\n      await handleEntrypoints({\n        entrypoints: entrypoints as any,\n\n        currentEntrypoints,\n\n        currentEntryIssues,\n        manifestLoader,\n        devRewrites: opts.fsChecker.rewrites,\n        productionRewrites: undefined,\n        logErrors: true,\n\n        dev: {\n          assetMapper,\n          changeSubscriptions,\n          clients: [\n            ...clientsWithoutHtmlRequestId,\n            ...clientsByHtmlRequestId.values(),\n          ],\n          clientStates,\n          serverFields,\n\n          hooks: {\n            handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n              currentWrittenEntrypoints.set(id, result)\n              return clearRequireCache(id, result, { force: forceDeleteCache })\n            },\n            propagateServerField: propagateServerField.bind(null, opts),\n            sendHmr,\n            startBuilding,\n            subscribeToChanges: subscribeToClientChanges,\n            unsubscribeFromChanges: unsubscribeFromClientChanges,\n            unsubscribeFromHmrEvents: unsubscribeFromClientHmrEvents,\n          },\n        },\n      })\n\n      // Reload matchers when the files have been compiled\n      await propagateServerField(opts, 'reloadMatchers', undefined)\n\n      if (addedRoutes.length > 0 || removedRoutes.length > 0) {\n        // When the list of routes changes a new manifest should be fetched for Pages Router.\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE,\n          data: [\n            {\n              devPagesManifest: true,\n            },\n          ],\n        })\n      }\n\n      for (const route of addedRoutes) {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.ADDED_PAGE,\n          data: [route],\n        })\n      }\n\n      for (const route of removedRoutes) {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.REMOVED_PAGE,\n          data: [route],\n        })\n      }\n\n      currentEntriesHandlingResolve!()\n      currentEntriesHandlingResolve = undefined\n    }\n  }\n\n  await mkdir(join(distDir, 'server'), { recursive: true })\n  await mkdir(join(distDir, 'static', buildId), { recursive: true })\n  await writeFile(\n    join(distDir, 'package.json'),\n    JSON.stringify(\n      {\n        type: 'commonjs',\n      },\n      null,\n      2\n    )\n  )\n\n  const middlewares = [\n    getOverlayMiddleware({\n      project,\n      projectPath,\n      isSrcDir: opts.isSrcDir,\n    }),\n    getSourceMapMiddleware(project),\n    getNextErrorFeedbackMiddleware(opts.telemetry),\n    getDevOverlayFontMiddleware(),\n    getDisableDevIndicatorMiddleware(),\n    getRestartDevServerMiddleware({\n      telemetry: opts.telemetry,\n      turbopackProject: project,\n    }),\n    devToolsConfigMiddleware({\n      distDir,\n      sendUpdateSignal: (data) => {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG,\n          data,\n        })\n      },\n    }),\n    getAttachNodejsDebuggerMiddleware(),\n    ...(nextConfig.experimental.mcpServer\n      ? [\n          getMcpMiddleware({\n            projectPath,\n            distDir,\n            nextConfig,\n            pagesDir: opts.pagesDir,\n            appDir: opts.appDir,\n            sendHmrMessage: (message) => hotReloader.send(message),\n            getActiveConnectionCount: () =>\n              clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,\n            getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,\n          }),\n        ]\n      : []),\n  ]\n\n  setStackFrameResolver(async (request) => {\n    return getOriginalStackFrames({\n      project,\n      projectPath,\n      isServer: request.isServer,\n      isEdgeServer: request.isEdgeServer,\n      isAppDirectory: request.isAppDirectory,\n      frames: request.frames,\n    })\n  })\n\n  let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined\n  // This fetch, even though not awaited, is not kicked off eagerly because the first `fetch()` in\n  // Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache\n  // We don't want that blocking time to be in the hot path for the `ready in` logging.\n  // Instead, the fetch is kicked off lazily when the first `getVersionInfoCached()` is called.\n  const getVersionInfoCached = (): ReturnType<typeof getVersionInfo> => {\n    if (!versionInfoCached) {\n      versionInfoCached = getVersionInfo()\n    }\n    return versionInfoCached\n  }\n\n  let devtoolsFrontendUrl: string | undefined\n  const inspectorURLRaw = inspector.url()\n  if (inspectorURLRaw !== undefined) {\n    const inspectorURL = new URL(inspectorURLRaw)\n\n    let debugInfo\n    try {\n      const debugInfoList = await fetch(\n        `http://${inspectorURL.host}/json/list`\n      ).then((res) => res.json())\n      debugInfo = debugInfoList[0]\n    } catch {}\n    if (debugInfo) {\n      devtoolsFrontendUrl = debugInfo.devtoolsFrontendUrl\n    }\n  }\n\n  const hotReloader: NextJsHotReloaderInterface = {\n    turbopackProject: project,\n    activeWebpackConfigs: undefined,\n    serverStats: null,\n    edgeServerStats: null,\n    async run(req, res, _parsedUrl) {\n      // intercept page chunks request and ensure them with turbopack\n      if (req.url?.startsWith('/_next/static/chunks/pages/')) {\n        const params = matchNextPageBundleRequest(req.url)\n\n        if (params) {\n          const decodedPagePath = `/${params.path\n            .map((param: string) => decodeURIComponent(param))\n            .join('/')}`\n\n          const denormalizedPagePath = denormalizePagePath(decodedPagePath)\n\n          await hotReloader\n            .ensurePage({\n              page: denormalizedPagePath,\n              clientOnly: false,\n              definition: undefined,\n              url: req.url,\n            })\n            .catch(console.error)\n        }\n      }\n\n      for (const middleware of middlewares) {\n        let calledNext = false\n\n        await middleware(req, res, () => {\n          calledNext = true\n        })\n\n        if (!calledNext) {\n          return { finished: true }\n        }\n      }\n\n      // Request was not finished.\n      return { finished: undefined }\n    },\n\n    // TODO: Figure out if socket type can match the NextJsHotReloaderInterface\n    onHMR(req, socket: Socket, head, onUpgrade) {\n      wsServer.handleUpgrade(req, socket, head, (client) => {\n        const clientIssues: EntryIssuesMap = new Map()\n        const subscriptions: Map<string, AsyncIterator<any>> = new Map()\n\n        const htmlRequestId = req.url\n          ? new URL(req.url, 'http://n').searchParams.get('id')\n          : null\n\n        // Clients with a request ID are inferred App Router clients. If Cache\n        // Components is not enabled, we consider those legacy clients. Pages\n        // Router clients are also considered legacy clients. TODO: Maybe mark\n        // clients as App Router / Pages Router clients explicitly, instead of\n        // inferring it from the presence of a request ID.\n        if (htmlRequestId) {\n          clientsByHtmlRequestId.set(htmlRequestId, client)\n          const enableCacheComponents = nextConfig.cacheComponents\n          if (enableCacheComponents) {\n            onUpgrade(client, { isLegacyClient: false })\n            const cacheStatus = cacheStatusesByHtmlRequestId.get(htmlRequestId)\n            if (cacheStatus !== undefined) {\n              sendToClient(client, {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,\n                state: cacheStatus,\n              })\n              cacheStatusesByHtmlRequestId.delete(htmlRequestId)\n            }\n          } else {\n            onUpgrade(client, { isLegacyClient: true })\n          }\n\n          connectReactDebugChannelForHtmlRequest(\n            htmlRequestId,\n            sendToClient.bind(null, client)\n          )\n\n          sendSerializedErrorsToClientForHtmlRequest(\n            htmlRequestId,\n            sendToClient.bind(null, client)\n          )\n        } else {\n          clientsWithoutHtmlRequestId.add(client)\n          onUpgrade(client, { isLegacyClient: true })\n        }\n\n        clientStates.set(client, {\n          clientIssues,\n          messages: new Map(),\n          turbopackUpdates: [],\n          subscriptions,\n        })\n\n        client.on('close', () => {\n          // Remove active subscriptions\n          for (const subscription of subscriptions.values()) {\n            subscription.return?.()\n          }\n          clientStates.delete(client)\n\n          if (htmlRequestId) {\n            clientsByHtmlRequestId.delete(htmlRequestId)\n            deleteReactDebugChannelForHtmlRequest(htmlRequestId)\n          } else {\n            clientsWithoutHtmlRequestId.delete(client)\n          }\n        })\n\n        client.addEventListener('message', async ({ data }) => {\n          const parsedData = JSON.parse(\n            typeof data !== 'string' ? data.toString() : data\n          )\n\n          // Next.js messages\n          switch (parsedData.event) {\n            case 'span-end': {\n              hotReloaderSpan.manualTraceChild(\n                parsedData.spanName,\n                msToNs(parsedData.startTime),\n                msToNs(parsedData.endTime),\n                parsedData.attributes\n              )\n              break\n            }\n            case 'client-hmr-latency': // { id, startTime, endTime, page, updatedModules, isPageHidden }\n              hotReloaderSpan.manualTraceChild(\n                parsedData.event,\n                msToNs(parsedData.startTime),\n                msToNs(parsedData.endTime),\n                {\n                  updatedModules: parsedData.updatedModules,\n                  page: parsedData.page,\n                  isPageHidden: parsedData.isPageHidden,\n                }\n              )\n              break\n\n            case 'client-error': // { errorCount, clientId }\n            case 'client-warning': // { warningCount, clientId }\n            case 'client-success': // { clientId }\n            case 'server-component-reload-page': // { clientId }\n            case 'client-reload-page': // { clientId }\n            case 'client-removed-page': // { page }\n            case 'client-full-reload': // { stackTrace, hadRuntimeError }\n              const { hadRuntimeError, dependencyChain } = parsedData\n              if (hadRuntimeError) {\n                Log.warn(FAST_REFRESH_RUNTIME_RELOAD)\n              }\n              if (\n                Array.isArray(dependencyChain) &&\n                typeof dependencyChain[0] === 'string'\n              ) {\n                const cleanedModulePath = dependencyChain[0]\n                  .replace(/^\\[project\\]/, '.')\n                  .replace(/ \\[.*\\] \\(.*\\)$/, '')\n                Log.warn(\n                  `Fast Refresh had to perform a full reload when ${cleanedModulePath} changed. Read more: https://nextjs.org/docs/messages/fast-refresh-reload`\n                )\n              }\n              break\n            case 'client-added-page':\n              // TODO\n              break\n            case 'browser-logs': {\n              const browserToTerminalConfig =\n                nextConfig.logging && nextConfig.logging.browserToTerminal\n              if (browserToTerminalConfig) {\n                await receiveBrowserLogsTurbopack({\n                  entries: parsedData.entries,\n                  router: parsedData.router,\n                  sourceType: parsedData.sourceType,\n                  project,\n                  projectPath,\n                  distDir,\n                  config: browserToTerminalConfig,\n                })\n              }\n              break\n            }\n            case 'client-file-logs': {\n              // Always log to file regardless of terminal flag\n              await handleClientFileLogs(parsedData.logs)\n              break\n            }\n            case 'ping': {\n              // Handle ping events to keep WebSocket connections alive\n              // No-op - just acknowledge the ping\n              break\n            }\n\n            case 'mcp-error-state-response': {\n              handleErrorStateResponse(\n                parsedData.requestId,\n                parsedData.errorState,\n                parsedData.url\n              )\n              break\n            }\n\n            case 'mcp-page-metadata-response': {\n              handlePageMetadataResponse(\n                parsedData.requestId,\n                parsedData.segmentTrieData,\n                parsedData.url\n              )\n              break\n            }\n\n            default:\n              // Might be a Turbopack message...\n              if (!parsedData.type) {\n                throw new Error(`unrecognized HMR message \"${data}\"`)\n              }\n          }\n\n          // Turbopack messages\n          switch (parsedData.type) {\n            case 'turbopack-subscribe':\n              subscribeToClientHmrEvents(client, parsedData.path)\n              break\n\n            case 'turbopack-unsubscribe':\n              unsubscribeFromClientHmrEvents(client, parsedData.path)\n              break\n\n            default:\n              if (!parsedData.event) {\n                throw new Error(`unrecognized Turbopack HMR message \"${data}\"`)\n              }\n          }\n        })\n\n        const turbopackConnectedMessage: TurbopackConnectedMessage = {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_CONNECTED,\n          data: { sessionId },\n        }\n        sendToClient(client, turbopackConnectedMessage)\n\n        const errors: CompilationError[] = []\n\n        for (const entryIssues of currentEntryIssues.values()) {\n          for (const issue of entryIssues.values()) {\n            if (issue.severity !== 'warning') {\n              errors.push({\n                message: formatIssue(issue),\n              })\n            } else {\n              printNonFatalIssue(issue)\n            }\n          }\n        }\n\n        if (devIndicatorServerState.disabledUntil < Date.now()) {\n          devIndicatorServerState.disabledUntil = 0\n        }\n\n        ;(async function () {\n          const versionInfo = await getVersionInfoCached()\n          const devToolsConfig = await getDevToolsConfig(distDir)\n\n          const syncMessage: SyncMessage = {\n            type: HMR_MESSAGE_SENT_TO_BROWSER.SYNC,\n            errors,\n            warnings: [],\n            hash: '',\n            versionInfo,\n            debug: {\n              devtoolsFrontendUrl,\n            },\n            devIndicator: devIndicatorServerState,\n            devToolsConfig,\n          }\n\n          sendToClient(client, syncMessage)\n        })()\n      })\n    },\n\n    send(action) {\n      const payload = JSON.stringify(action)\n\n      for (const client of [\n        ...clientsWithoutHtmlRequestId,\n        ...clientsByHtmlRequestId.values(),\n      ]) {\n        client.send(payload)\n      }\n    },\n\n    sendToLegacyClients(action) {\n      const payload = JSON.stringify(action)\n\n      // Clients with a request ID are inferred App Router clients. If Cache\n      // Components is not enabled, we consider those legacy clients. Pages\n      // Router clients are also considered legacy clients. TODO: Maybe mark\n      // clients as App Router / Pages Router clients explicitly, instead of\n      // inferring it from the presence of a request ID.\n\n      if (!nextConfig.cacheComponents) {\n        for (const client of clientsByHtmlRequestId.values()) {\n          client.send(payload)\n        }\n      }\n\n      for (const client of clientsWithoutHtmlRequestId) {\n        client.send(payload)\n      }\n    },\n\n    setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void {\n      // Legacy clients don't have Cache Components.\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n      if (client !== undefined) {\n        sendToClient(client, {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,\n          state: status,\n        })\n      } else {\n        // If the client is not connected, store the status so that we can send it\n        // when the client connects.\n        cacheStatusesByHtmlRequestId.set(htmlRequestId, status)\n      }\n    },\n\n    setReactDebugChannel(debugChannel, htmlRequestId, requestId) {\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n\n      if (htmlRequestId === requestId) {\n        // The debug channel is for the HTML request.\n        if (client) {\n          // If the client is connected, we can connect the debug channel for\n          // the HTML request immediately.\n          connectReactDebugChannel(\n            htmlRequestId,\n            debugChannel,\n            sendToClient.bind(null, client)\n          )\n        } else {\n          // Otherwise, we'll do that when the client connects and just store\n          // the debug channel.\n          setReactDebugChannelForHtmlRequest(htmlRequestId, debugChannel)\n        }\n      } else if (client) {\n        // The debug channel is for a subsequent request (e.g. client-side\n        // navigation for server function call). If the client is not connected\n        // anymore, we don't need to connect the debug channel.\n        connectReactDebugChannel(\n          requestId,\n          debugChannel,\n          sendToClient.bind(null, client)\n        )\n      }\n    },\n\n    sendErrorsToBrowser(errorsRscStream, htmlRequestId) {\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n\n      if (client) {\n        // If the client is connected, we can send the errors immediately.\n        sendSerializedErrorsToClient(\n          errorsRscStream,\n          sendToClient.bind(null, client)\n        )\n      } else {\n        // Otherwise, store the errors stream so that we can send it when the\n        // client connects.\n        setErrorsRscStreamForHtmlRequest(htmlRequestId, errorsRscStream)\n      }\n    },\n\n    setHmrServerError(_error) {\n      // Not implemented yet.\n    },\n    clearHmrServerError() {\n      // Not implemented yet.\n    },\n    async start() {},\n    async getCompilationErrors(page) {\n      const appEntryKey = getEntryKey('app', 'server', page)\n      const pagesEntryKey = getEntryKey('pages', 'server', page)\n\n      const topLevelIssues = currentTopLevelIssues.values()\n\n      const thisEntryIssues =\n        currentEntryIssues.get(appEntryKey) ??\n        currentEntryIssues.get(pagesEntryKey)\n\n      if (thisEntryIssues !== undefined && thisEntryIssues.size > 0) {\n        // If there is an error related to the requesting page we display it instead of the first error\n        return [...topLevelIssues, ...thisEntryIssues.values()]\n          .map((issue) => {\n            const formattedIssue = formatIssue(issue)\n            if (issue.severity === 'warning') {\n              printNonFatalIssue(issue)\n              return null\n            } else if (isWellKnownError(issue)) {\n              Log.error(formattedIssue)\n            }\n\n            return new Error(formattedIssue)\n          })\n          .filter((error) => error !== null)\n      }\n\n      // Otherwise, return all errors across pages\n      const errors = []\n      for (const issue of topLevelIssues) {\n        if (issue.severity !== 'warning') {\n          errors.push(new Error(formatIssue(issue)))\n        }\n      }\n      for (const entryIssues of currentEntryIssues.values()) {\n        for (const issue of entryIssues.values()) {\n          if (issue.severity !== 'warning') {\n            const message = formatIssue(issue)\n            errors.push(new Error(message))\n          } else {\n            printNonFatalIssue(issue)\n          }\n        }\n      }\n      return errors\n    },\n    async invalidate({\n      // .env files or tsconfig/jsconfig change\n      reloadAfterInvalidation,\n    }) {\n      if (reloadAfterInvalidation) {\n        for (const [key, entrypoint] of currentWrittenEntrypoints) {\n          clearRequireCache(key, entrypoint, { force: true })\n        }\n\n        await clearAllModuleContexts()\n        this.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,\n          hash: String(++hmrHash),\n        })\n      }\n    },\n    async buildFallbackError() {\n      // Not implemented yet.\n    },\n    async ensurePage({\n      page: inputPage,\n      // Unused parameters\n      // clientOnly,\n      appPaths,\n      definition,\n      isApp,\n      url: requestUrl,\n    }) {\n      // When there is no route definition this is an internal file not a route the user added.\n      // Middleware and instrumentation are handled in turbpack-utils.ts handleEntrypoints instead.\n      if (!definition) {\n        if (inputPage === '/middleware') return\n        if (inputPage === '/src/middleware') return\n        if (inputPage === '/instrumentation') return\n        if (inputPage === '/src/instrumentation') return\n      }\n\n      return hotReloaderSpan\n        .traceChild('ensure-page', {\n          inputPage,\n        })\n        .traceAsyncFn(async () => {\n          if (BLOCKED_PAGES.includes(inputPage) && inputPage !== '/_error') {\n            return\n          }\n\n          await currentEntriesHandling\n\n          // TODO We shouldn't look into the filesystem again. This should use the information from entrypoints\n          let routeDef: Pick<\n            RouteDefinition,\n            'filename' | 'bundlePath' | 'page'\n          > =\n            definition ??\n            (await findPagePathData(\n              projectPath,\n              inputPage,\n              nextConfig.pageExtensions,\n              opts.pagesDir,\n              opts.appDir,\n              !!nextConfig.experimental.globalNotFound\n            ))\n\n          // If the route is actually an app page route, then we should have access\n          // to the app route definition, and therefore, the appPaths from it.\n          if (!appPaths && definition && isAppPageRouteDefinition(definition)) {\n            appPaths = definition.appPaths\n          }\n\n          // Check if this is a deferred entry and wait for non-deferred entries first\n          if (hasDeferredEntriesConfig) {\n            const isDeferred = isDeferredEntry(\n              routeDef.page,\n              deferredEntriesConfig\n            )\n            if (isDeferred) {\n              await processDeferredEntry()\n            } else {\n              // Track non-deferred entry as building\n              nonDeferredBuildingEntries.add(routeDef.page)\n            }\n          }\n\n          let page = routeDef.page\n          if (appPaths) {\n            const normalizedPage = normalizeAppPath(page)\n\n            // filter out paths that are not exact matches (e.g. catchall)\n            const matchingAppPaths = appPaths.filter(\n              (path) => normalizeAppPath(path) === normalizedPage\n            )\n\n            // the last item in the array is the root page, if there are parallel routes\n            page = matchingAppPaths[matchingAppPaths.length - 1]\n          }\n\n          const pathname = definition?.pathname ?? inputPage\n\n          if (page === '/_error') {\n            let finishBuilding = startBuilding(pathname, requestUrl, false)\n            try {\n              await handlePagesErrorRoute({\n                currentEntryIssues,\n                entrypoints: currentEntrypoints,\n                manifestLoader,\n                devRewrites: opts.fsChecker.rewrites,\n                productionRewrites: undefined,\n                logErrors: true,\n                hooks: {\n                  subscribeToChanges: subscribeToClientChanges,\n                  handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n                    currentWrittenEntrypoints.set(id, result)\n                    assetMapper.setPathsForKey(id, result.clientPaths)\n                    return clearRequireCache(id, result, {\n                      force: forceDeleteCache,\n                    })\n                  },\n                },\n              })\n            } finally {\n              finishBuilding()\n            }\n            return\n          }\n\n          const isInsideAppDir = routeDef.bundlePath.startsWith('app/')\n          const isEntryMetadataRouteFile = isMetadataRouteFile(\n            routeDef.filename.replace(opts.appDir || '', ''),\n            nextConfig.pageExtensions,\n            true\n          )\n          const normalizedAppPage = isEntryMetadataRouteFile\n            ? normalizedPageToTurbopackStructureRoute(\n                page,\n                extname(routeDef.filename)\n              )\n            : page\n\n          const route = isInsideAppDir\n            ? currentEntrypoints.app.get(normalizedAppPage)\n            : currentEntrypoints.page.get(page)\n\n          if (!route) {\n            // TODO: why is this entry missing in turbopack?\n            if (page === '/middleware') return\n            if (page === '/src/middleware') return\n            if (page === '/proxy') return\n            if (page === '/src/proxy') return\n            if (page === '/instrumentation') return\n            if (page === '/src/instrumentation') return\n\n            throw new PageNotFoundError(`route not found ${page}`)\n          }\n\n          // We don't throw on ensureOpts.isApp === true for page-api\n          // since this can happen when app pages make\n          // api requests to page API routes.\n          if (isApp && route.type === 'page') {\n            throw new Error(`mis-matched route type: isApp && page for ${page}`)\n          }\n\n          const finishBuilding = startBuilding(pathname, requestUrl, false)\n          try {\n            await handleRouteType({\n              dev,\n              page,\n              pathname,\n              route,\n              currentEntryIssues,\n              entrypoints: currentEntrypoints,\n              manifestLoader,\n              readyIds,\n              devRewrites: opts.fsChecker.rewrites,\n              productionRewrites: undefined,\n              logErrors: true,\n\n              hooks: {\n                subscribeToChanges: subscribeToClientChanges,\n                handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n                  currentWrittenEntrypoints.set(id, result)\n                  assetMapper.setPathsForKey(id, result.clientPaths)\n                  return clearRequireCache(id, result, {\n                    force: forceDeleteCache,\n                  })\n                },\n              },\n            })\n          } finally {\n            finishBuilding()\n            // Remove non-deferred entry from building set\n            if (hasDeferredEntriesConfig) {\n              nonDeferredBuildingEntries.delete(routeDef.page)\n            }\n          }\n        })\n    },\n    close() {\n      // Report MCP telemetry if MCP server is enabled\n      recordMcpTelemetry(opts.telemetry)\n\n      for (const wsClient of [\n        ...clientsWithoutHtmlRequestId,\n        ...clientsByHtmlRequestId.values(),\n      ]) {\n        // it's okay to not cleanly close these websocket connections, this is dev\n        wsClient.terminate()\n      }\n      clientsWithoutHtmlRequestId.clear()\n      clientsByHtmlRequestId.clear()\n    },\n  }\n\n  handleEntrypointsSubscription().catch((err) => {\n    console.error(err)\n    process.exit(1)\n  })\n\n  // Write empty manifests\n  await currentEntriesHandling\n  await manifestLoader.writeManifests({\n    devRewrites: opts.fsChecker.rewrites,\n    productionRewrites: undefined,\n    entrypoints: currentEntrypoints,\n  })\n\n  async function handleProjectUpdates() {\n    for await (const updateMessage of project.updateInfoSubscribe(30)) {\n      switch (updateMessage.updateType) {\n        case 'start': {\n          hotReloader.send({ type: HMR_MESSAGE_SENT_TO_BROWSER.BUILDING })\n          // Mark that HMR has started and we need to call the callback after it settles\n          // This ensures onBeforeDeferredEntries will be called again during HMR\n          if (hasDeferredEntriesConfig) {\n            hmrPendingDeferredCallback = true\n            onBeforeDeferredEntriesCalled = false\n            onBeforeDeferredEntriesPromise = null\n          }\n          break\n        }\n        case 'end': {\n          sendEnqueuedMessages()\n\n          function addToErrorsMap(\n            errorsMap: Map<string, CompilationError>,\n            issueMap: IssuesMap\n          ) {\n            for (const [key, issue] of issueMap) {\n              if (issue.severity === 'warning') continue\n              if (errorsMap.has(key)) continue\n\n              const message = formatIssue(issue)\n\n              errorsMap.set(key, {\n                message,\n                details: issue.detail\n                  ? renderStyledStringToErrorAnsi(issue.detail)\n                  : undefined,\n              })\n            }\n          }\n\n          function addErrors(\n            errorsMap: Map<string, CompilationError>,\n            issues: EntryIssuesMap\n          ) {\n            for (const issueMap of issues.values()) {\n              addToErrorsMap(errorsMap, issueMap)\n            }\n          }\n\n          const errors = new Map<string, CompilationError>()\n          addToErrorsMap(errors, currentTopLevelIssues)\n          addErrors(errors, currentEntryIssues)\n\n          for (const client of [\n            ...clientsWithoutHtmlRequestId,\n            ...clientsByHtmlRequestId.values(),\n          ]) {\n            const state = clientStates.get(client)\n            if (!state) {\n              continue\n            }\n\n            const clientErrors = new Map(errors)\n            addErrors(clientErrors, state.clientIssues)\n\n            sendToClient(client, {\n              type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT,\n              hash: String(++hmrHash),\n              errors: [...clientErrors.values()],\n              warnings: [],\n            })\n          }\n\n          if (hmrEventHappened) {\n            const time = updateMessage.value.duration\n            const timeMessage =\n              time > 2000 ? `${Math.round(time / 100) / 10}s` : `${time}ms`\n            Log.event(`Compiled in ${timeMessage}`)\n            hmrEventHappened = false\n          }\n\n          // Call onBeforeDeferredEntries after compilation completes during HMR\n          // This ensures the callback is invoked even when non-deferred entries change\n          // Use debounced function to prevent rapid-fire calls from turbopack updates\n          if (hasDeferredEntriesConfig) {\n            callOnBeforeDeferredEntriesAfterHMR()\n          }\n          break\n        }\n        default:\n      }\n    }\n  }\n\n  handleProjectUpdates().catch((err) => {\n    console.error(err)\n    process.exit(1)\n  })\n\n  if (serverFastRefresh) {\n    serverHmrSubscriptions = setupServerHmr(project, {\n      clear: async () => {\n        // Clear Node's require cache of all Turbopack-built modules\n        const chunkPaths = [...(serverHmrSubscriptions?.keys() ?? [])].map(\n          (chunkPath) => join(distDir, chunkPath)\n        )\n        deleteCache(chunkPaths)\n\n        // Clear Turbopack's runtime caches\n        if (typeof __next__clear_chunk_cache__ === 'function') {\n          __next__clear_chunk_cache__()\n        }\n\n        // Reset the server HMR handler registry. All server runtime chunks are\n        // cleared from require.cache above; when they're next required they'll\n        // re-register into this Map and reinstall the routing dispatcher.\n        ;(globalThis as any).__turbopack_server_hmr_handlers__ = new Map()\n\n        // Clear all edge contexts\n        await clearAllModuleContexts()\n\n        resetFetch()\n\n        // Tell browsers to refetch RSC (soft refresh, not full page reload)\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,\n          hash: String(++hmrHash),\n        })\n      },\n    })\n  }\n\n  return hotReloader\n}\n"],"names":["mkdir","writeFile","inspector","join","extname","relative","pathToFileURL","ws","store","consoleStore","HMR_MESSAGE_SENT_TO_BROWSER","createDefineEnv","getBindingsSync","HmrTarget","Log","BLOCKED_PAGES","getOverlayMiddleware","getSourceMapMiddleware","getOriginalStackFrames","PageNotFoundError","debounce","deleteCache","clearAllModuleContexts","clearModuleContext","denormalizePagePath","trace","AssetMapper","handleEntrypoints","handlePagesErrorRoute","handleRouteType","hasEntrypointForKey","msToNs","processTopLevelIssues","printNonFatalIssue","normalizedPageToTurbopackStructureRoute","propagateServerField","TurbopackManifestLoader","findPagePathData","getEntryKey","splitEntryKey","createBinaryHmrMessageData","FAST_REFRESH_RUNTIME_RELOAD","generateEncryptionKeyBase64","isAppPageRouteDefinition","normalizeAppPath","isDeferredEntry","isMetadataRoute","isMetadataRouteFile","setBundlerFindSourceMapImplementation","getNextErrorFeedbackMiddleware","formatIssue","isFileSystemCacheEnabledForDev","isWellKnownError","processIssues","renderStyledStringToErrorAnsi","getDevOverlayFontMiddleware","devIndicatorServerState","getDisableDevIndicatorMiddleware","getRestartDevServerMiddleware","backgroundLogCompilationEvents","getSupportedBrowsers","printBuildErrors","receiveBrowserLogsTurbopack","handleClientFileLogs","normalizePath","devToolsConfigMiddleware","getDevToolsConfig","getAttachNodejsDebuggerMiddleware","connectReactDebugChannel","connectReactDebugChannelForHtmlRequest","deleteReactDebugChannelForHtmlRequest","setReactDebugChannelForHtmlRequest","getVersionInfo","matchNextPageBundleRequest","getMcpMiddleware","handleErrorStateResponse","handlePageMetadataResponse","setStackFrameResolver","recordMcpTelemetry","getFileLogger","sendSerializedErrorsToClient","sendSerializedErrorsToClientForHtmlRequest","setErrorsRscStreamForHtmlRequest","wsServer","Server","noServer","isTestMode","process","env","NEXT_TEST_MODE","__NEXT_TEST_MODE","DEBUG","sessionId","Math","floor","Number","MAX_SAFE_INTEGER","random","setupServerHmr","project","clear","serverHmrSubscriptions","Map","subscribeToServerHmr","chunkPath","has","subscription","hmrEvents","set","next","result","update","type","instruction","__turbopack_server_hmr_apply__","applied","catch","err","console","error","delete","serverHmrChunkPaths","hmrChunkNamesSubscribe","data","currentChunkPaths","Set","chunkNames","filter","path","endsWith","chunkPathsToRemove","keys","push","get","return","rewriteTurbopackSources","projectRoot","sourceMap","section","sections","map","i","sources","length","replace","toString","getSourceMapFromTurbopack","sourceURL","sourceMapJson","getSourceMapSync","undefined","payload","JSON","parse","createHotReloaderTurbopack","opts","serverFields","distDir","resetFetch","lockfile","serverFastRefresh","nextConfig","dev","buildId","dir","projectPath","bindings","isWasm","Error","platform","arch","require","log","testMode","hasRewrites","fsChecker","rewrites","afterFiles","beforeFiles","fallback","hotReloaderSpan","version","__NEXT_VERSION","stop","mcpServerEnabled","experimental","mcpServer","fileLogger","initialize","encryptionKey","isBuild","clientRouterFilters","clientRouterFilter","supportedBrowsers","currentNodeJsVersion","versions","node","rootPath","turbopack","root","outputFileTracingRoot","turbo","createProject","watch","enable","pollIntervalMs","watchOptions","defineEnv","isTurbopack","config","fetchCacheKeyPrefix","middlewareMatchers","previewProps","browserslistQuery","noMangling","writeRoutesHashesManifest","isPersistentCachingEnabled","nextVersion","serverHmr","memoryLimit","turbopackMemoryLimit","isShortSession","eventTypes","parentSpan","bind","installCodeFrameSupport","onDevServerCleanup","onExit","unlock","entrypointsSubscription","entrypointsSubscribe","currentWrittenEntrypoints","currentEntrypoints","global","app","document","middleware","instrumentation","page","currentTopLevelIssues","currentEntryIssues","manifestLoader","sriEnabled","changeSubscriptions","serverPathState","readyIds","currentEntriesHandlingResolve","currentEntriesHandling","Promise","resolve","assetMapper","deferredEntriesConfig","deferredEntries","hasDeferredEntriesConfig","onBeforeDeferredEntriesCalled","onBeforeDeferredEntriesPromise","nonDeferredBuildingEntries","waitForNonDeferredEntries","checkEntries","size","setTimeout","processDeferredEntry","onBeforeDeferredEntries","hmrPendingDeferredCallback","callOnBeforeDeferredEntriesAfterHMR","clearRequireCache","key","writtenEndpoint","force","contentHash","serverPaths","localKey","hasChange","localHash","globalHash","p","entryType","entryPage","usesServerHmr","filesToDelete","file","relativePath","__next__clear_chunk_cache__","buildingIds","startBuilding","id","requestUrl","forceRebuild","setState","loading","trigger","url","add","finishBuilding","hmrEventHappened","hmrHash","clientsWithoutHtmlRequestId","clientsByHtmlRequestId","cacheStatusesByHtmlRequestId","clientStates","WeakMap","sendToClient","client","message","stringify","send","sendEnqueuedMessages","issueMap","values","severity","state","clientIssues","messages","turbopackUpdates","TURBOPACK_MESSAGE","sendEnqueuedMessagesDebounce","sendHmr","sendTurbopackMessage","diagnostics","issues","subscribeToClientChanges","includeIssues","endpoint","createMessage","onError","side","changedPromise","changed","change","String","e","unsubscribeFromClientChanges","subscribeToClientHmrEvents","subscriptions","Client","reloadMessage","RELOAD_PAGE","close","unsubscribeFromClientHmrEvents","handleEntrypointsSubscription","entrypoints","routes","existingRoutes","newRoutes","addedRoutes","route","removedRoutes","devRewrites","productionRewrites","logErrors","clients","hooks","handleWrittenEndpoint","forceDeleteCache","subscribeToChanges","unsubscribeFromChanges","unsubscribeFromHmrEvents","hotReloader","DEV_PAGES_MANIFEST_UPDATE","devPagesManifest","ADDED_PAGE","REMOVED_PAGE","recursive","middlewares","isSrcDir","telemetry","turbopackProject","sendUpdateSignal","DEVTOOLS_CONFIG","pagesDir","appDir","sendHmrMessage","getActiveConnectionCount","getDevServerUrl","__NEXT_PRIVATE_ORIGIN","request","isServer","isEdgeServer","isAppDirectory","frames","versionInfoCached","getVersionInfoCached","devtoolsFrontendUrl","inspectorURLRaw","inspectorURL","URL","debugInfo","debugInfoList","fetch","host","then","res","json","activeWebpackConfigs","serverStats","edgeServerStats","run","req","_parsedUrl","startsWith","params","decodedPagePath","param","decodeURIComponent","denormalizedPagePath","ensurePage","clientOnly","definition","calledNext","finished","onHMR","socket","head","onUpgrade","handleUpgrade","htmlRequestId","searchParams","enableCacheComponents","cacheComponents","isLegacyClient","cacheStatus","CACHE_INDICATOR","on","addEventListener","parsedData","event","manualTraceChild","spanName","startTime","endTime","attributes","updatedModules","isPageHidden","hadRuntimeError","dependencyChain","warn","Array","isArray","cleanedModulePath","browserToTerminalConfig","logging","browserToTerminal","entries","router","sourceType","logs","requestId","errorState","segmentTrieData","turbopackConnectedMessage","TURBOPACK_CONNECTED","errors","entryIssues","issue","disabledUntil","Date","now","versionInfo","devToolsConfig","syncMessage","SYNC","warnings","hash","debug","devIndicator","action","sendToLegacyClients","setCacheStatus","status","setReactDebugChannel","debugChannel","sendErrorsToBrowser","errorsRscStream","setHmrServerError","_error","clearHmrServerError","start","getCompilationErrors","appEntryKey","pagesEntryKey","topLevelIssues","thisEntryIssues","formattedIssue","invalidate","reloadAfterInvalidation","entrypoint","SERVER_COMPONENT_CHANGES","buildFallbackError","inputPage","appPaths","isApp","traceChild","traceAsyncFn","includes","routeDef","pageExtensions","globalNotFound","isDeferred","normalizedPage","matchingAppPaths","pathname","setPathsForKey","clientPaths","isInsideAppDir","bundlePath","isEntryMetadataRouteFile","filename","normalizedAppPage","wsClient","terminate","exit","writeManifests","handleProjectUpdates","updateMessage","updateInfoSubscribe","updateType","BUILDING","addToErrorsMap","errorsMap","details","detail","addErrors","clientErrors","BUILT","time","value","duration","timeMessage","round","chunkPaths","globalThis","__turbopack_server_hmr_handlers__"],"mappings":"AACA,SAASA,KAAK,EAAEC,SAAS,QAAQ,cAAa;AAC9C,YAAYC,eAAe,YAAW;AACtC,SAASC,IAAI,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,OAAM;AAC9C,SAASC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