{"version":3,"sources":["../../../../src/server/dev/turbopack-utils.ts"],"sourcesContent":["import type {\n  ServerFields,\n  SetupOpts,\n} from '../lib/router-utils/setup-dev-bundler'\nimport type {\n  Issue,\n  TurbopackResult,\n  Endpoint,\n  RawEntrypoints,\n  Update as TurbopackUpdate,\n  WrittenEndpoint,\n} from '../../build/swc/types'\nimport {\n  type HmrMessageSentToBrowser,\n  HMR_MESSAGE_SENT_TO_BROWSER,\n} from './hot-reloader-types'\nimport * as Log from '../../build/output/log'\nimport { warnAboutEdgeRuntime } from '../../build/warn-about-edge-runtime'\nimport type { PropagateToWorkersField } from '../lib/router-utils/types'\nimport type { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loader'\nimport type { AppRoute, Entrypoints, PageRoute } from '../../build/swc/types'\nimport {\n  type EntryKey,\n  getEntryKey,\n  splitEntryKey,\n} from '../../shared/lib/turbopack/entry-key'\nimport type ws from 'next/dist/compiled/ws'\nimport { isMetadataRoute } from '../../lib/metadata/is-metadata-route'\nimport type { CustomRoutes } from '../../lib/load-custom-routes'\nimport {\n  formatIssue,\n  getIssueKey,\n  isRelevantWarning,\n  processIssues,\n  renderStyledStringToErrorAnsi,\n  type EntryIssuesMap,\n  type TopLevelIssuesMap,\n} from '../../shared/lib/turbopack/utils'\nimport { MIDDLEWARE_FILENAME, PROXY_FILENAME } from '../../lib/constants'\n\nconst onceErrorSet = new Set()\n/**\n * Check if given issue is a warning to be display only once.\n * This mimics behavior of get-page-static-info's warnOnce.\n * @param issue\n * @returns\n */\nfunction shouldEmitOnceWarning(issue: Issue): boolean {\n  const { severity, title, stage } = issue\n  if (severity === 'warning' && title.value === 'Invalid page configuration') {\n    if (onceErrorSet.has(issue)) {\n      return false\n    }\n    onceErrorSet.add(issue)\n  }\n  if (\n    severity === 'warning' &&\n    stage === 'config' &&\n    renderStyledStringToErrorAnsi(issue.title).includes(\"can't be external\")\n  ) {\n    if (onceErrorSet.has(issue)) {\n      return false\n    }\n    onceErrorSet.add(issue)\n  }\n\n  return true\n}\n\n/// Print out an issue to the console which should not block\n/// the build by throwing out or blocking error overlay.\nexport function printNonFatalIssue(issue: Issue) {\n  if (isRelevantWarning(issue) && shouldEmitOnceWarning(issue)) {\n    Log.warn(formatIssue(issue))\n  }\n}\n\nexport function processTopLevelIssues(\n  currentTopLevelIssues: TopLevelIssuesMap,\n  result: TurbopackResult\n) {\n  currentTopLevelIssues.clear()\n\n  for (const issue of result.issues) {\n    const issueKey = getIssueKey(issue)\n    currentTopLevelIssues.set(issueKey, issue)\n  }\n}\n\nexport { msToNs } from '../../shared/lib/turbopack/compilation-events'\n\nexport type ChangeSubscriptions = Map<\n  EntryKey,\n  Promise<AsyncIterableIterator<TurbopackResult>>\n>\n\nexport type HandleWrittenEndpoint = (\n  key: EntryKey,\n  result: TurbopackResult<WrittenEndpoint>,\n  forceDeleteCache: boolean\n) => boolean\n\nexport type StartChangeSubscription = (\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    e: Error\n  ) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void\n) => Promise<void>\n\nexport type StopChangeSubscription = (key: EntryKey) => Promise<void>\n\nexport type SendHmr = (id: string, message: HmrMessageSentToBrowser) => void\n\nexport type StartBuilding = (\n  id: string,\n  requestUrl: string | undefined,\n  forceRebuild: boolean\n) => () => void\n\nexport type ReadyIds = Set<string>\n\nexport type ClientState = {\n  clientIssues: EntryIssuesMap\n  messages: Map<string, HmrMessageSentToBrowser>\n  turbopackUpdates: TurbopackUpdate[]\n  subscriptions: Map<string, AsyncIterator<any>>\n}\n\nexport type ClientStateMap = WeakMap<ws, ClientState>\n\n// hooks only used by the dev server.\n// subscribeToChanges is optional: omit it to skip wiring HMR subscriptions\n// for one-shot compilations (e.g. the compile_route MCP tool) where there\n// is no client to receive updates and no unsubscribe path.\ntype HandleRouteTypeHooks = {\n  handleWrittenEndpoint: HandleWrittenEndpoint\n  subscribeToChanges: StartChangeSubscription\n  handleServerComponentChanges?: () => void\n  // When Turbopack server fast refresh is enabled, the aggregate server-HMR\n  // subscription (setupServerHmr `onApplied` in hot-reloader-turbopack.ts)\n  // owns the browser refresh signal for app-page RSC changes and only fires\n  // after the server module cache is refreshed. In that mode the per-page\n  // `rscHmrEndpoint` subscription must NOT also send SERVER_COMPONENT_CHANGES,\n  // or every edit triggers two RSC refetches (the first immediately\n  // superseded).\n  serverFastRefresh?: boolean\n}\n\nexport async function handleRouteType({\n  dev,\n  page,\n  pathname,\n  route,\n  currentEntryIssues,\n  entrypoints,\n  manifestLoader,\n  readyIds,\n  devRewrites,\n  productionRewrites,\n  hooks,\n  logErrors,\n}: {\n  dev: boolean\n  page: string\n  pathname: string\n  route: PageRoute | AppRoute\n\n  currentEntryIssues: EntryIssuesMap\n  entrypoints: Entrypoints\n  manifestLoader: TurbopackManifestLoader\n  devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n  productionRewrites: CustomRoutes['rewrites'] | undefined\n  logErrors: boolean\n\n  readyIds?: ReadyIds // dev\n\n  // hooks.subscribeToChanges may be omitted to skip HMR subscriptions for\n  // one-shot compilations (e.g. the compile_route MCP tool).\n  hooks?: HandleRouteTypeHooks // dev\n}) {\n  switch (route.type) {\n    case 'page': {\n      const clientKey = getEntryKey('pages', 'client', page)\n      const serverKey = getEntryKey('pages', 'server', page)\n\n      try {\n        // In the best case scenario, Turbopack chunks document, app, page separately in that order,\n        // so it can happen that the chunks of document change, but the chunks of app and page\n        // don't. We still need to reload the page chunks in that case though, otherwise the version\n        // of the document or app component export from the pages template is stale.\n        let documentOrAppChanged = false\n        if (entrypoints.global.app) {\n          const key = getEntryKey('pages', 'server', '_app')\n\n          const writtenEndpoint = await entrypoints.global.app.writeToDisk()\n          documentOrAppChanged ||=\n            hooks?.handleWrittenEndpoint(key, writtenEndpoint, false) ?? false\n          processIssues(\n            currentEntryIssues,\n            key,\n            writtenEndpoint,\n            false,\n            logErrors\n          )\n        }\n        await manifestLoader.loadBuildManifest('_app')\n        await manifestLoader.loadPagesManifest('_app')\n\n        if (entrypoints.global.document) {\n          const key = getEntryKey('pages', 'server', '_document')\n\n          const writtenEndpoint =\n            await entrypoints.global.document.writeToDisk()\n          documentOrAppChanged ||=\n            hooks?.handleWrittenEndpoint(key, writtenEndpoint, false) ?? false\n          processIssues(\n            currentEntryIssues,\n            key,\n            writtenEndpoint,\n            false,\n            logErrors\n          )\n        }\n        await manifestLoader.loadPagesManifest('_document')\n\n        const writtenEndpoint = await route.htmlEndpoint.writeToDisk()\n        hooks?.handleWrittenEndpoint(\n          serverKey,\n          writtenEndpoint,\n          documentOrAppChanged\n        )\n\n        const type = writtenEndpoint?.type\n\n        await manifestLoader.loadClientBuildManifest(page)\n        await manifestLoader.loadBuildManifest(page)\n        await manifestLoader.loadPagesManifest(page)\n        if (type === 'edge') {\n          warnAboutEdgeRuntime()\n          await manifestLoader.loadMiddlewareManifest(page, 'pages')\n        } else {\n          manifestLoader.deleteMiddlewareManifest(serverKey)\n        }\n        await manifestLoader.loadFontManifest('/_app', 'pages')\n        await manifestLoader.loadFontManifest(page, 'pages')\n\n        manifestLoader.writeManifests({\n          devRewrites,\n          productionRewrites,\n          entrypoints,\n        })\n\n        processIssues(\n          currentEntryIssues,\n          serverKey,\n          writtenEndpoint,\n          false,\n          logErrors\n        )\n      } finally {\n        if (dev) {\n          // TODO subscriptions should only be caused by the WebSocket connections\n          // otherwise we don't known when to unsubscribe and this leaking\n          hooks?.subscribeToChanges(\n            serverKey,\n            /** includeIssues=*/ false,\n            route.dataEndpoint,\n            () => {\n              // Report the next compilation again\n              readyIds?.delete(pathname)\n              return {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ONLY_CHANGES,\n                pages: [page],\n              }\n            },\n            (e) => {\n              return {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n                data: `error in ${page} data subscription: ${e}`,\n              }\n            }\n          )\n          hooks?.subscribeToChanges(\n            clientKey,\n            /** includeIssues=*/ false,\n            route.htmlEndpoint,\n            () => {\n              return {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES,\n              }\n            },\n            (e) => {\n              return {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n                data: `error in ${page} html subscription: ${e}`,\n              }\n            }\n          )\n          if (entrypoints.global.document) {\n            hooks?.subscribeToChanges(\n              getEntryKey('pages', 'server', '_document'),\n              /** includeIssues=*/ false,\n              entrypoints.global.document,\n              () => {\n                return {\n                  type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n                  data: '_document has changed (page route)',\n                }\n              },\n              (e) => {\n                return {\n                  type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n                  data: `error in _document subscription (page route): ${e}`,\n                }\n              }\n            )\n          }\n        }\n      }\n\n      break\n    }\n    case 'page-api': {\n      const key = getEntryKey('pages', 'server', page)\n\n      const writtenEndpoint = await route.endpoint.writeToDisk()\n      hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)\n\n      const type = writtenEndpoint.type\n\n      await manifestLoader.loadPagesManifest(page)\n      if (type === 'edge') {\n        warnAboutEdgeRuntime()\n        await manifestLoader.loadMiddlewareManifest(page, 'pages')\n      } else {\n        manifestLoader.deleteMiddlewareManifest(key)\n      }\n\n      manifestLoader.writeManifests({\n        devRewrites,\n        productionRewrites,\n        entrypoints,\n      })\n\n      processIssues(currentEntryIssues, key, writtenEndpoint, true, logErrors)\n\n      break\n    }\n    case 'app-page': {\n      const key = getEntryKey('app', 'server', page)\n\n      const writtenEndpoint = await route.htmlEndpoint.writeToDisk()\n      hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)\n\n      if (dev) {\n        // TODO subscriptions should only be caused by the WebSocket connections\n        // otherwise we don't known when to unsubscribe and this leaking\n        hooks?.subscribeToChanges(\n          key,\n          /** includeIssues=*/ true,\n          route.rscHmrEndpoint,\n          (change) => {\n            if (change.issues.some((issue) => issue.severity === 'error')) {\n              // Ignore any updates that has errors\n              // There will be another update without errors eventually\n              return\n            }\n            // Report the next compilation again\n            readyIds?.delete(pathname)\n            // When server fast refresh is enabled, the aggregate server-HMR\n            // subscription sends SERVER_COMPONENT_CHANGES after applying the\n            // update in-process. Sending here too would double the refresh.\n            //\n            // But the aggregate subscription only fires when there is a live\n            // server-HMR handler registered (i.e. the page has rendered at\n            // least once). When recovering from a build error the page never\n            // rendered, so no handler exists, the aggregate stays silent, and\n            // this per-page send is the only thing that clears the redbox.\n            // Only suppress when a handler is actually live to own the refresh.\n            const hasLiveServerHmrHandler =\n              (globalThis.__turbopack_server_hmr_handlers__?.size ?? 0) > 0\n            if (hooks?.serverFastRefresh && hasLiveServerHmrHandler) {\n              return\n            }\n            hooks?.handleServerComponentChanges?.()\n          },\n          (e) => {\n            return {\n              type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n              data: `error in ${page} app-page subscription: ${e}`,\n            }\n          }\n        )\n      }\n\n      const type = writtenEndpoint.type\n\n      if (type === 'edge') {\n        warnAboutEdgeRuntime()\n        manifestLoader.loadMiddlewareManifest(page, 'app')\n      } else {\n        manifestLoader.deleteMiddlewareManifest(key)\n      }\n\n      manifestLoader.loadBuildManifest(page, 'app')\n      manifestLoader.loadAppPathsManifest(page)\n      manifestLoader.loadActionManifest(page)\n      manifestLoader.loadFontManifest(page, 'app')\n\n      manifestLoader.writeManifests({\n        devRewrites,\n        productionRewrites,\n        entrypoints,\n      })\n\n      processIssues(currentEntryIssues, key, writtenEndpoint, dev, logErrors)\n\n      break\n    }\n    case 'app-route': {\n      const key = getEntryKey('app', 'server', page)\n\n      const writtenEndpoint = await route.endpoint.writeToDisk()\n      hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)\n\n      if (dev) {\n        // Advance the hot-reloader's HMR refresh hash whenever this route\n        // handler is recompiled, so its `\"use cache\"` entries are invalidated\n        // after an edit. Subscribing runs `subscribeToClientChanges`, which\n        // bumps the `hmrHash` counter on each change; that counter is returned\n        // by `getServerComponentsHmrRefreshHash` and folded into cache keys by\n        // `getHmrRefreshHash`. Unlike app pages there is no RSC for a connected\n        // browser to refetch, so `createMessage` returns nothing; the\n        // subscription exists only to advance the hash.\n        hooks?.subscribeToChanges(\n          key,\n          /** includeIssues= */ true,\n          route.endpoint,\n          () => undefined,\n          (error) => {\n            // This subscription only advances the refresh hash, so there is\n            // nothing to send the browser when it fails. `subscribeToChanges`\n            // drops the subscription on error and re-creates it the next time\n            // this route is ensured, so just log it.\n            console.error(\n              new Error(`Error in the \"${page}\" app-route HMR subscription`, {\n                cause: error,\n              })\n            )\n          }\n        )\n      }\n\n      const type = writtenEndpoint.type\n\n      manifestLoader.loadAppPathsManifest(page)\n\n      if (type === 'edge') {\n        warnAboutEdgeRuntime()\n        manifestLoader.loadMiddlewareManifest(page, 'app')\n      } else {\n        manifestLoader.deleteMiddlewareManifest(key)\n      }\n\n      manifestLoader.writeManifests({\n        devRewrites,\n        productionRewrites,\n        entrypoints,\n      })\n      processIssues(currentEntryIssues, key, writtenEndpoint, true, logErrors)\n\n      break\n    }\n    default: {\n      throw new Error(`unknown route type ${(route as any).type} for ${page}`)\n    }\n  }\n}\n\n/**\n * Maintains a mapping between entrypoins and the corresponding client asset paths.\n */\nexport class AssetMapper {\n  private entryMap: Map<EntryKey, Set<string>> = new Map()\n  private assetMap: Map<string, Set<EntryKey>> = new Map()\n\n  /**\n   * Overrides asset paths for a key and updates the mapping from path to key.\n   *\n   * @param key\n   * @param assetPaths asset paths relative to the .next directory\n   */\n  setPathsForKey(key: EntryKey, assetPaths: string[]): void {\n    this.delete(key)\n\n    const newAssetPaths = new Set(assetPaths)\n    this.entryMap.set(key, newAssetPaths)\n\n    for (const assetPath of newAssetPaths) {\n      let assetPathKeys = this.assetMap.get(assetPath)\n      if (!assetPathKeys) {\n        assetPathKeys = new Set()\n        this.assetMap.set(assetPath, assetPathKeys)\n      }\n\n      assetPathKeys!.add(key)\n    }\n  }\n\n  /**\n   * Deletes the key and any asset only referenced by this key.\n   *\n   * @param key\n   */\n  delete(key: EntryKey) {\n    for (const assetPath of this.getAssetPathsByKey(key)) {\n      const assetPathKeys = this.assetMap.get(assetPath)\n\n      assetPathKeys?.delete(key)\n\n      if (!assetPathKeys?.size) {\n        this.assetMap.delete(assetPath)\n      }\n    }\n\n    this.entryMap.delete(key)\n  }\n\n  getAssetPathsByKey(key: EntryKey): string[] {\n    return Array.from(this.entryMap.get(key) ?? [])\n  }\n\n  getKeysByAsset(path: string): EntryKey[] {\n    return Array.from(this.assetMap.get(path) ?? [])\n  }\n\n  keys(): IterableIterator<EntryKey> {\n    return this.entryMap.keys()\n  }\n}\n\nexport function hasEntrypointForKey(\n  entrypoints: Entrypoints,\n  key: EntryKey,\n  assetMapper: AssetMapper | undefined\n): boolean {\n  const { type, page } = splitEntryKey(key)\n\n  switch (type) {\n    case 'app':\n      return entrypoints.app.has(page)\n    case 'pages':\n      switch (page) {\n        case '_app':\n          return entrypoints.global.app != null\n        case '_document':\n          return entrypoints.global.document != null\n        case '_error':\n          return entrypoints.global.error != null\n        default:\n          return entrypoints.page.has(page)\n      }\n    case 'root':\n      switch (page) {\n        case 'middleware':\n          return entrypoints.global.middleware != null\n        case 'instrumentation':\n          return entrypoints.global.instrumentation != null\n        default:\n          return false\n      }\n    case 'assets':\n      if (!assetMapper) {\n        return false\n      }\n\n      return assetMapper\n        .getKeysByAsset(page)\n        .some((pageKey) =>\n          hasEntrypointForKey(entrypoints, pageKey, assetMapper)\n        )\n    default: {\n      // validation that we covered all cases, this should never run.\n      const _: never = type\n      return false\n    }\n  }\n}\n\n// hooks only used by the dev server.\ntype HandleEntrypointsHooks = {\n  handleWrittenEndpoint: HandleWrittenEndpoint\n  propagateServerField: (\n    field: PropagateToWorkersField,\n    args: any\n  ) => Promise<void>\n  sendHmr: SendHmr\n  startBuilding: StartBuilding\n  subscribeToChanges: StartChangeSubscription\n  unsubscribeFromChanges: StopChangeSubscription\n  unsubscribeFromHmrEvents: (client: ws, id: string) => void\n}\n\ntype HandleEntrypointsDevOpts = {\n  assetMapper: AssetMapper\n  changeSubscriptions: ChangeSubscriptions\n  clients: Array<ws>\n  clientStates: ClientStateMap\n  serverFields: ServerFields\n\n  hooks: HandleEntrypointsHooks\n}\n\nexport async function handleEntrypoints({\n  entrypoints,\n\n  currentEntrypoints,\n\n  currentEntryIssues,\n  manifestLoader,\n  devRewrites,\n  logErrors,\n  dev,\n}: {\n  entrypoints: TurbopackResult<RawEntrypoints>\n\n  currentEntrypoints: Entrypoints\n\n  currentEntryIssues: EntryIssuesMap\n  manifestLoader: TurbopackManifestLoader\n  devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n  productionRewrites: CustomRoutes['rewrites'] | undefined\n  logErrors: boolean\n\n  dev: HandleEntrypointsDevOpts\n}) {\n  currentEntrypoints.global.app = entrypoints.pagesAppEndpoint\n  currentEntrypoints.global.document = entrypoints.pagesDocumentEndpoint\n  currentEntrypoints.global.error = entrypoints.pagesErrorEndpoint\n\n  currentEntrypoints.global.instrumentation = entrypoints.instrumentation\n\n  currentEntrypoints.page.clear()\n  currentEntrypoints.app.clear()\n\n  for (const [pathname, route] of entrypoints.routes) {\n    switch (route.type) {\n      case 'page':\n      case 'page-api':\n        currentEntrypoints.page.set(pathname, route)\n        break\n      case 'app-page': {\n        route.pages.forEach((page) => {\n          currentEntrypoints.app.set(page.originalName, {\n            type: 'app-page',\n            ...page,\n          })\n        })\n        break\n      }\n      case 'app-route': {\n        currentEntrypoints.app.set(route.originalName, route)\n        break\n      }\n      case 'conflict':\n        Log.info(`skipping ${pathname} (${route.type})`)\n        break\n      default:\n        route satisfies never\n    }\n  }\n\n  if (dev) {\n    await handleEntrypointsDevCleanup({\n      currentEntryIssues,\n      currentEntrypoints,\n\n      ...dev,\n    })\n  }\n\n  const { middleware, instrumentation } = entrypoints\n\n  // We check for explicit true/false, since it's initialized to\n  // undefined during the first loop (middlewareChanges event is\n  // unnecessary during the first serve)\n  if (currentEntrypoints.global.middleware && !middleware) {\n    const key = getEntryKey('root', 'server', 'middleware')\n    // Went from middleware to no middleware\n    await dev?.hooks.unsubscribeFromChanges(key)\n    currentEntryIssues.delete(key)\n    dev.hooks.sendHmr('middleware', {\n      type: HMR_MESSAGE_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,\n    })\n  } else if (!currentEntrypoints.global.middleware && middleware) {\n    // Went from no middleware to middleware\n    dev.hooks.sendHmr('middleware', {\n      type: HMR_MESSAGE_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,\n    })\n  }\n\n  currentEntrypoints.global.middleware = middleware\n\n  if (instrumentation) {\n    const processInstrumentation = async (\n      name: string,\n      prop: 'nodeJs' | 'edge'\n    ) => {\n      const prettyName = {\n        nodeJs: 'Node.js',\n        edge: 'Edge',\n      }\n      const finishBuilding = dev.hooks.startBuilding(\n        `instrumentation ${prettyName[prop]}`,\n        undefined,\n        true\n      )\n      const key = getEntryKey('root', 'server', name)\n\n      const writtenEndpoint = await instrumentation[prop].writeToDisk()\n      dev.hooks.handleWrittenEndpoint(key, writtenEndpoint, false)\n      processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)\n      finishBuilding()\n    }\n    await processInstrumentation('instrumentation.nodeJs', 'nodeJs')\n    await processInstrumentation('instrumentation.edge', 'edge')\n    await manifestLoader.loadMiddlewareManifest(\n      'instrumentation',\n      'instrumentation'\n    )\n    manifestLoader.writeManifests({\n      devRewrites,\n      productionRewrites: undefined,\n      entrypoints: currentEntrypoints,\n    })\n\n    dev.serverFields.actualInstrumentationHookFile = '/instrumentation'\n    await dev.hooks.propagateServerField(\n      'actualInstrumentationHookFile',\n      dev.serverFields.actualInstrumentationHookFile\n    )\n  } else {\n    dev.serverFields.actualInstrumentationHookFile = undefined\n    await dev.hooks.propagateServerField(\n      'actualInstrumentationHookFile',\n      dev.serverFields.actualInstrumentationHookFile\n    )\n  }\n\n  if (middleware) {\n    const key = getEntryKey('root', 'server', 'middleware')\n\n    const endpoint = middleware.endpoint\n    const triggerName = middleware.isProxy\n      ? PROXY_FILENAME\n      : MIDDLEWARE_FILENAME\n\n    async function processMiddleware() {\n      const finishBuilding = dev.hooks.startBuilding(\n        triggerName,\n        undefined,\n        true\n      )\n      const writtenEndpoint = await endpoint.writeToDisk()\n      dev.hooks.handleWrittenEndpoint(key, writtenEndpoint, false)\n      processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)\n      await manifestLoader.loadMiddlewareManifest('middleware', 'middleware')\n      const middlewareConfig =\n        manifestLoader.getMiddlewareManifest(key)?.middleware['/']\n\n      if (dev && middlewareConfig) {\n        dev.serverFields.middleware = {\n          match: null as any,\n          page: '/',\n          matchers: middlewareConfig.matchers,\n        }\n      }\n      finishBuilding()\n    }\n    await processMiddleware()\n\n    if (dev) {\n      dev?.hooks.subscribeToChanges(\n        key,\n        /** includeIssues=*/ false,\n        endpoint,\n        async () => {\n          const finishBuilding = dev.hooks.startBuilding(\n            triggerName,\n            undefined,\n            true\n          )\n          await processMiddleware()\n          await dev.hooks.propagateServerField(\n            'actualMiddlewareFile',\n            dev.serverFields.actualMiddlewareFile\n          )\n          await dev.hooks.propagateServerField(\n            'middleware',\n            dev.serverFields.middleware\n          )\n          manifestLoader.writeManifests({\n            devRewrites,\n            productionRewrites: undefined,\n            entrypoints: currentEntrypoints,\n          })\n\n          finishBuilding?.()\n          return {\n            type: HMR_MESSAGE_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,\n          }\n        },\n        () => {\n          return {\n            type: HMR_MESSAGE_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,\n          }\n        }\n      )\n    }\n  } else {\n    manifestLoader.deleteMiddlewareManifest(\n      getEntryKey('root', 'server', 'middleware')\n    )\n    dev.serverFields.actualMiddlewareFile = undefined\n    dev.serverFields.middleware = undefined\n  }\n\n  await dev.hooks.propagateServerField(\n    'actualMiddlewareFile',\n    dev.serverFields.actualMiddlewareFile\n  )\n  await dev.hooks.propagateServerField(\n    'middleware',\n    dev.serverFields.middleware\n  )\n}\n\nasync function handleEntrypointsDevCleanup({\n  currentEntryIssues,\n  currentEntrypoints,\n\n  assetMapper,\n  changeSubscriptions,\n  clients,\n  clientStates,\n\n  hooks,\n}: {\n  currentEntrypoints: Entrypoints\n  currentEntryIssues: EntryIssuesMap\n} & HandleEntrypointsDevOpts) {\n  // this needs to be first as `hasEntrypointForKey` uses the `assetMapper`\n  for (const key of assetMapper.keys()) {\n    if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n      assetMapper.delete(key)\n    }\n  }\n\n  for (const key of changeSubscriptions.keys()) {\n    // middleware is handled separately\n    if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n      await hooks.unsubscribeFromChanges(key)\n    }\n  }\n\n  for (const [key] of currentEntryIssues) {\n    if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n      currentEntryIssues.delete(key)\n    }\n  }\n\n  for (const client of clients) {\n    const state = clientStates.get(client)\n    if (!state) {\n      continue\n    }\n\n    for (const key of state.clientIssues.keys()) {\n      if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n        state.clientIssues.delete(key)\n      }\n    }\n\n    for (const id of state.subscriptions.keys()) {\n      if (\n        !hasEntrypointForKey(\n          currentEntrypoints,\n          getEntryKey('assets', 'client', id),\n          assetMapper\n        )\n      ) {\n        hooks.unsubscribeFromHmrEvents(client, id)\n      }\n    }\n  }\n}\n\nexport async function handlePagesErrorRoute({\n  currentEntryIssues,\n  entrypoints,\n  manifestLoader,\n  devRewrites,\n  productionRewrites,\n  logErrors,\n  hooks,\n}: {\n  currentEntryIssues: EntryIssuesMap\n  entrypoints: Entrypoints\n  manifestLoader: TurbopackManifestLoader\n  devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n  productionRewrites: CustomRoutes['rewrites'] | undefined\n  logErrors: boolean\n  hooks: HandleRouteTypeHooks\n}) {\n  if (entrypoints.global.app) {\n    const key = getEntryKey('pages', 'server', '_app')\n\n    const writtenEndpoint = await entrypoints.global.app.writeToDisk()\n    hooks.handleWrittenEndpoint(key, writtenEndpoint, false)\n    hooks.subscribeToChanges(\n      key,\n      /** includeIssues=*/ false,\n      entrypoints.global.app,\n      () => {\n        // There's a special case for this in `../client/page-bootstrap.ts`.\n        // https://github.com/vercel/next.js/blob/08d7a7e5189a835f5dcb82af026174e587575c0e/packages/next/src/client/page-bootstrap.ts#L69-L71\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES,\n        }\n      },\n      () => {\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n          data: '_app has changed (error route)',\n        }\n      }\n    )\n    processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)\n  }\n  await manifestLoader.loadBuildManifest('_app')\n  await manifestLoader.loadPagesManifest('_app')\n  await manifestLoader.loadFontManifest('_app')\n\n  if (entrypoints.global.document) {\n    const key = getEntryKey('pages', 'server', '_document')\n\n    const writtenEndpoint = await entrypoints.global.document.writeToDisk()\n    hooks.handleWrittenEndpoint(key, writtenEndpoint, false)\n    hooks.subscribeToChanges(\n      key,\n      /** includeIssues=*/ false,\n      entrypoints.global.document,\n      () => {\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n          data: '_document has changed (error route)',\n        }\n      },\n      (e) => {\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n          data: `error in _document subscription (error route): ${e}`,\n        }\n      }\n    )\n    processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)\n  }\n  await manifestLoader.loadPagesManifest('_document')\n\n  if (entrypoints.global.error) {\n    const key = getEntryKey('pages', 'server', '_error')\n\n    const writtenEndpoint = await entrypoints.global.error.writeToDisk()\n    hooks.handleWrittenEndpoint(key, writtenEndpoint, false)\n    hooks.subscribeToChanges(\n      key,\n      /** includeIssues=*/ false,\n      entrypoints.global.error,\n      () => {\n        // There's a special case for this in `../client/page-bootstrap.ts`.\n        // https://github.com/vercel/next.js/blob/08d7a7e5189a835f5dcb82af026174e587575c0e/packages/next/src/client/page-bootstrap.ts#L69-L71\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES,\n        }\n      },\n      (e) => {\n        return {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n          data: `error in _error subscription: ${e}`,\n        }\n      }\n    )\n    processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)\n  }\n  await manifestLoader.loadClientBuildManifest('_error')\n  await manifestLoader.loadBuildManifest('_error')\n  await manifestLoader.loadPagesManifest('_error')\n  await manifestLoader.loadFontManifest('_error')\n\n  manifestLoader.writeManifests({\n    devRewrites,\n    productionRewrites,\n    entrypoints,\n  })\n}\n\nexport function removeRouteSuffix(route: string): string {\n  return route.replace(/\\/route$/, '')\n}\n\nexport function addRouteSuffix(route: string): string {\n  return route + '/route'\n}\n\nexport function addMetadataIdToRoute(route: string): string {\n  return route + '/[__metadata_id__]'\n}\n\n// Since turbopack will create app pages/route entries based on the structure,\n// which means the entry keys are based on file names.\n// But for special metadata conventions we'll change the page/pathname to a different path.\n// So we need this helper to map the new path back to original turbopack entry key.\nexport function normalizedPageToTurbopackStructureRoute(\n  route: string,\n  ext: string | false\n): string {\n  let entrypointKey = route\n  if (isMetadataRoute(entrypointKey)) {\n    entrypointKey = entrypointKey.endsWith('/route')\n      ? entrypointKey.slice(0, -'/route'.length)\n      : entrypointKey\n\n    if (ext) {\n      if (entrypointKey.endsWith('/[__metadata_id__]')) {\n        entrypointKey = entrypointKey.slice(0, -'/[__metadata_id__]'.length)\n      }\n      // After stripping [__metadata_id__], add .xml for dynamic sitemap routes\n      // to match the Turbopack entry key from normalize_metadata_route\n      if (entrypointKey.endsWith('/sitemap') && ext !== '.xml') {\n        entrypointKey = entrypointKey + '.xml'\n      }\n    }\n    entrypointKey = entrypointKey + '/route'\n  }\n  return entrypointKey\n}\n"],"names":["HMR_MESSAGE_SENT_TO_BROWSER","Log","warnAboutEdgeRuntime","getEntryKey","splitEntryKey","isMetadataRoute","formatIssue","getIssueKey","isRelevantWarning","processIssues","renderStyledStringToErrorAnsi","MIDDLEWARE_FILENAME","PROXY_FILENAME","onceErrorSet","Set","shouldEmitOnceWarning","issue","severity","title","stage","value","has","add","includes","printNonFatalIssue","warn","processTopLevelIssues","currentTopLevelIssues","result","clear","issues","issueKey","set","msToNs","handleRouteType","dev","page","pathname","route","currentEntryIssues","entrypoints","manifestLoader","readyIds","devRewrites","productionRewrites","hooks","logErrors","type","clientKey","serverKey","documentOrAppChanged","global","app","key","writtenEndpoint","writeToDisk","handleWrittenEndpoint","loadBuildManifest","loadPagesManifest","document","htmlEndpoint","loadClientBuildManifest","loadMiddlewareManifest","deleteMiddlewareManifest","loadFontManifest","writeManifests","subscribeToChanges","dataEndpoint","delete","SERVER_ONLY_CHANGES","pages","e","RELOAD_PAGE","data","CLIENT_CHANGES","endpoint","rscHmrEndpoint","change","globalThis","some","hasLiveServerHmrHandler","__turbopack_server_hmr_handlers__","size","serverFastRefresh","handleServerComponentChanges","loadAppPathsManifest","loadActionManifest","undefined","error","console","Error","cause","AssetMapper","setPathsForKey","assetPaths","newAssetPaths","entryMap","assetPath","assetPathKeys","assetMap","get","getAssetPathsByKey","Array","from","getKeysByAsset","path","keys","Map","hasEntrypointForKey","assetMapper","middleware","instrumentation","pageKey","_","handleEntrypoints","currentEntrypoints","pagesAppEndpoint","pagesDocumentEndpoint","pagesErrorEndpoint","routes","forEach","originalName","info","handleEntrypointsDevCleanup","unsubscribeFromChanges","sendHmr","MIDDLEWARE_CHANGES","processInstrumentation","name","prop","prettyName","nodeJs","edge","finishBuilding","startBuilding","serverFields","actualInstrumentationHookFile","propagateServerField","triggerName","isProxy","processMiddleware","middlewareConfig","getMiddlewareManifest","match","matchers","actualMiddlewareFile","changeSubscriptions","clients","clientStates","client","state","clientIssues","id","subscriptions","unsubscribeFromHmrEvents","handlePagesErrorRoute","removeRouteSuffix","replace","addRouteSuffix","addMetadataIdToRoute","normalizedPageToTurbopackStructureRoute","ext","entrypointKey","endsWith","slice","length"],"mappings":"AAYA,SAEEA,2BAA2B,QACtB,uBAAsB;AAC7B,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,oBAAoB,QAAQ,sCAAqC;AAI1E,SAEEC,WAAW,EACXC,aAAa,QACR,uCAAsC;AAE7C,SAASC,eAAe,QAAQ,uCAAsC;AAEtE,SACEC,WAAW,EACXC,WAAW,EACXC,iBAAiB,EACjBC,aAAa,EACbC,6BAA6B,QAGxB,mCAAkC;AACzC,SAASC,mBAAmB,EAAEC,cAAc,QAAQ,sBAAqB;AAEzE,MAAMC,eAAe,IAAIC;AACzB;;;;;CAKC,GACD,SAASC,sBAAsBC,KAAY;IACzC,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,KAAK,EAAE,GAAGH;IACnC,IAAIC,aAAa,aAAaC,MAAME,KAAK,KAAK,8BAA8B;QAC1E,IAAIP,aAAaQ,GAAG,CAACL,QAAQ;YAC3B,OAAO;QACT;QACAH,aAAaS,GAAG,CAACN;IACnB;IACA,IACEC,aAAa,aACbE,UAAU,YACVT,8BAA8BM,MAAME,KAAK,EAAEK,QAAQ,CAAC,sBACpD;QACA,IAAIV,aAAaQ,GAAG,CAACL,QAAQ;YAC3B,OAAO;QACT;QACAH,aAAaS,GAAG,CAACN;IACnB;IAEA,OAAO;AACT;AAEA,4DAA4D;AAC5D,wDAAwD;AACxD,OAAO,SAASQ,mBAAmBR,KAAY;IAC7C,IAAIR,kBAAkBQ,UAAUD,sBAAsBC,QAAQ;QAC5Df,IAAIwB,IAAI,CAACnB,YAAYU;IACvB;AACF;AAEA,OAAO,SAASU,sBACdC,qBAAwC,EACxCC,MAAuB;IAEvBD,sBAAsBE,KAAK;IAE3B,KAAK,MAAMb,SAASY,OAAOE,MAAM,CAAE;QACjC,MAAMC,WAAWxB,YAAY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