next 15.4.2-canary.51 → 15.4.2-canary.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of next might be problematic. Click here for more details.

Files changed (43) hide show
  1. package/dist/bin/next +1 -1
  2. package/dist/build/index.js +2 -2
  3. package/dist/build/swc/index.js +1 -1
  4. package/dist/build/webpack-config.js +2 -2
  5. package/dist/client/app-bootstrap.js +1 -1
  6. package/dist/client/index.js +1 -1
  7. package/dist/compiled/next-server/pages-api-turbo.runtime.dev.js +1 -1
  8. package/dist/compiled/next-server/pages-api-turbo.runtime.dev.js.map +1 -1
  9. package/dist/compiled/next-server/pages-api-turbo.runtime.prod.js +1 -1
  10. package/dist/compiled/next-server/pages-api-turbo.runtime.prod.js.map +1 -1
  11. package/dist/compiled/next-server/pages-turbo.runtime.dev.js +1 -1
  12. package/dist/compiled/next-server/pages-turbo.runtime.dev.js.map +1 -1
  13. package/dist/compiled/next-server/pages-turbo.runtime.prod.js +1 -1
  14. package/dist/compiled/next-server/pages-turbo.runtime.prod.js.map +1 -1
  15. package/dist/esm/build/index.js +2 -2
  16. package/dist/esm/build/swc/index.js +1 -1
  17. package/dist/esm/build/webpack-config.js +2 -2
  18. package/dist/esm/client/app-bootstrap.js +1 -1
  19. package/dist/esm/client/index.js +1 -1
  20. package/dist/esm/server/dev/hot-reloader-turbopack.js +3 -2
  21. package/dist/esm/server/dev/hot-reloader-turbopack.js.map +1 -1
  22. package/dist/esm/server/dev/hot-reloader-webpack.js +1 -1
  23. package/dist/esm/server/lib/app-info-log.js +1 -1
  24. package/dist/esm/server/lib/router-utils/route-types-utils.js +10 -10
  25. package/dist/esm/server/lib/router-utils/route-types-utils.js.map +1 -1
  26. package/dist/esm/server/lib/router-utils/typegen.js +87 -33
  27. package/dist/esm/server/lib/router-utils/typegen.js.map +1 -1
  28. package/dist/esm/server/lib/start-server.js +1 -1
  29. package/dist/esm/shared/lib/canary-only.js +1 -1
  30. package/dist/server/dev/hot-reloader-turbopack.js +3 -2
  31. package/dist/server/dev/hot-reloader-turbopack.js.map +1 -1
  32. package/dist/server/dev/hot-reloader-webpack.js +1 -1
  33. package/dist/server/lib/app-info-log.js +1 -1
  34. package/dist/server/lib/router-utils/route-types-utils.js +10 -10
  35. package/dist/server/lib/router-utils/route-types-utils.js.map +1 -1
  36. package/dist/server/lib/router-utils/typegen.js +87 -33
  37. package/dist/server/lib/router-utils/typegen.js.map +1 -1
  38. package/dist/server/lib/start-server.js +1 -1
  39. package/dist/shared/lib/canary-only.js +1 -1
  40. package/dist/telemetry/anonymous-meta.js +1 -1
  41. package/dist/telemetry/events/session-stopped.js +2 -2
  42. package/dist/telemetry/events/version.js +2 -2
  43. package/package.json +15 -15
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/dev/hot-reloader-turbopack.ts"],"sourcesContent":["import type { Socket } from 'net'\nimport { mkdir, writeFile } from 'fs/promises'\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 HMR_ACTION_TYPES,\n NextJsHotReloaderInterface,\n ReloadPageAction,\n SyncAction,\n TurbopackConnectedAction,\n} from './hot-reloader-types'\nimport { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'\nimport type {\n Update as TurbopackUpdate,\n Endpoint,\n WrittenEndpoint,\n TurbopackResult,\n Project,\n Entrypoints,\n} from '../../build/swc/types'\nimport { createDefineEnv } from '../../build/swc'\nimport * as Log from '../../build/output/log'\nimport {\n getVersionInfo,\n matchNextPageBundleRequest,\n} from './hot-reloader-webpack'\nimport { BLOCKED_PAGES } from '../../shared/lib/constants'\nimport {\n getOverlayMiddleware,\n getSourceMapMiddleware,\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 { FAST_REFRESH_RUNTIME_RELOAD } 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 { getNodeDebugType } from '../lib/utils'\nimport { isMetadataRouteFile } 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 getTurbopackJsConfig,\n isPersistentCachingEnabled,\n isWellKnownError,\n processIssues,\n renderStyledStringToErrorAnsi,\n type EntryIssuesMap,\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/utils'\nimport { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'\nimport { normalizePath } from '../../lib/normalize-path'\nimport {\n devToolsConfigMiddleware,\n getDevToolsConfig,\n} from '../../next-devtools/server/devtools-config-middleware'\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\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): Promise<NextJsHotReloaderInterface> {\n const dev = true\n const buildId = 'development'\n const { nextConfig, dir: projectPath } = opts\n\n const { loadBindings } =\n require('../../build/swc') as typeof import('../../build/swc')\n\n let bindings = await loadBindings()\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 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 persistent caching 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 jsConfig: await getTurbopackJsConfig(projectPath, 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.prerenderManifest.preview,\n browserslistQuery: supportedBrowsers.join(', '),\n noMangling: false,\n currentNodeJsVersion,\n },\n {\n persistentCaching: isPersistentCachingEnabled(opts.nextConfig),\n memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,\n isShortSession: false,\n }\n )\n backgroundLogCompilationEvents(project, {\n eventTypes: ['StartupCacheInvalidationEvent'],\n })\n setBundlerFindSourceMapImplementation(\n getSourceMapFromTurbopack.bind(null, project, projectPath)\n )\n opts.onDevServerCleanup?.(async () => {\n setBundlerFindSourceMapImplementation(() => undefined)\n await project.onExit()\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 })\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 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 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(key, contentHash)\n serverPathState.set(path, contentHash)\n } else {\n if (!localHash) {\n serverPathState.set(key, contentHash)\n }\n if (!globalHash) {\n serverPathState.set(path, contentHash)\n }\n }\n }\n\n if (!hasChange) {\n return false\n }\n }\n\n resetFetch()\n\n // Not available in:\n // - Pages Router (no server-side HMR)\n // - Edge Runtime (uses browser runtime which already disposes chunks individually)\n if (typeof __next__clear_chunk_cache__ === 'function') {\n __next__clear_chunk_cache__()\n }\n\n const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>\n join(distDir, p)\n )\n\n for (const file of serverPaths) {\n clearModuleContext(file)\n deleteCache(file)\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 hmrEventHappened = false\n let hmrHash = 0\n\n const clients = new Set<ws>()\n const clientStates = new WeakMap<ws, ClientState>()\n\n function sendToClient(client: ws, payload: HMR_ACTION_TYPES) {\n client.send(JSON.stringify(payload))\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 clients) {\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 payload of state.hmrPayloads.values()) {\n sendToClient(client, payload)\n }\n state.hmrPayloads.clear()\n\n if (state.turbopackUpdates.length > 0) {\n sendToClient(client, {\n action: HMR_ACTIONS_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, payload: HMR_ACTION_TYPES) => {\n for (const client of clients) {\n clientStates.get(client)?.hmrPayloads.set(id, payload)\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 clients) {\n clientStates.get(client)?.turbopackUpdates.push(payload)\n }\n\n hmrEventHappened = true\n sendEnqueuedMessagesDebounce()\n }\n\n async function subscribeToChanges(\n key: EntryKey,\n includeIssues: boolean,\n endpoint: Endpoint,\n makePayload: (\n change: TurbopackResult,\n hash: string\n ) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | void,\n onError?: (\n error: Error\n ) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | 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 payload = await makePayload(change, String(++hmrHash))\n if (payload) {\n sendHmr(key, payload)\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 unsubscribeFromChanges(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 subscribeToHmrEvents(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)\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)\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 reloadAction: ReloadPageAction = {\n action: HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE,\n data: `error in HMR event subscription for ${id}: ${e}`,\n }\n sendToClient(client, reloadAction)\n client.close()\n return\n }\n }\n\n function unsubscribeFromHmrEvents(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 processTopLevelIssues(currentTopLevelIssues, entrypoints)\n\n await handleEntrypoints({\n entrypoints,\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 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,\n unsubscribeFromChanges,\n unsubscribeFromHmrEvents,\n },\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 action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG,\n data,\n })\n },\n }),\n ]\n\n const versionInfoPromise = getVersionInfo()\n\n let devtoolsFrontendUrl: string | undefined\n const nodeDebugType = getNodeDebugType()\n if (nodeDebugType) {\n const debugPort = process.debugPort\n let debugInfo\n try {\n // It requires to use 127.0.0.1 instead of localhost for server-side fetching.\n const debugInfoList = await fetch(\n `http://127.0.0.1:${debugPort}/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 onUpgrade(client)\n const clientIssues: EntryIssuesMap = new Map()\n const subscriptions: Map<string, AsyncIterator<any>> = new Map()\n\n clients.add(client)\n clientStates.set(client, {\n clientIssues,\n hmrPayloads: 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 clients.delete(client)\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 if (nextConfig.experimental.browserDebugInfoInTerminal) {\n await receiveBrowserLogsTurbopack({\n entries: parsedData.entries,\n router: parsedData.router,\n sourceType: parsedData.sourceType,\n project,\n projectPath,\n distDir,\n config: nextConfig.experimental.browserDebugInfoInTerminal,\n })\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 subscribeToHmrEvents(client, parsedData.path)\n break\n\n case 'turbopack-unsubscribe':\n unsubscribeFromHmrEvents(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 turbopackConnected: TurbopackConnectedAction = {\n action: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,\n data: { sessionId },\n }\n sendToClient(client, turbopackConnected)\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 versionInfoPromise\n const devToolsConfig = await getDevToolsConfig(distDir)\n\n const sync: SyncAction = {\n action: HMR_ACTIONS_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, sync)\n })()\n })\n },\n\n send(action) {\n const payload = JSON.stringify(action)\n for (const client of clients) {\n client.send(payload)\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 action: HMR_ACTIONS_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 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,\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 === '/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,\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 })\n },\n close() {\n for (const wsClient of clients) {\n // it's okay to not cleanly close these websocket connections, this is dev\n wsClient.terminate()\n }\n clients.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({ action: HMR_ACTIONS_SENT_TO_BROWSER.BUILDING })\n break\n }\n case 'end': {\n sendEnqueuedMessages()\n\n function addErrors(\n errorsMap: Map<string, CompilationError>,\n issues: EntryIssuesMap\n ) {\n for (const issueMap of issues.values()) {\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\n const errors = new Map<string, CompilationError>()\n addErrors(errors, currentEntryIssues)\n\n for (const client of clients) {\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 action: HMR_ACTIONS_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 break\n }\n default:\n }\n }\n }\n\n handleProjectUpdates().catch((err) => {\n console.error(err)\n process.exit(1)\n })\n\n return hotReloader\n}\n"],"names":["createHotReloaderTurbopack","wsServer","ws","Server","noServer","isTestMode","process","env","NEXT_TEST_MODE","__NEXT_TEST_MODE","DEBUG","sessionId","Math","floor","Number","MAX_SAFE_INTEGER","random","rewriteTurbopackSources","projectRoot","sourceMap","section","sections","map","i","sources","length","pathToFileURL","join","replace","toString","getSourceMapFromTurbopack","project","sourceURL","sourceMapJson","getSourceMapSync","err","undefined","payload","JSON","parse","opts","serverFields","distDir","resetFetch","nextConfig","dev","buildId","dir","projectPath","loadBindings","require","bindings","log","testMode","hasRewrites","fsChecker","rewrites","afterFiles","beforeFiles","fallback","hotReloaderSpan","trace","version","__NEXT_VERSION","stop","encryptionKey","generateEncryptionKeyBase64","isBuild","clientRouterFilters","experimental","clientRouterFilter","supportedBrowsers","getSupportedBrowsers","currentNodeJsVersion","versions","node","rootPath","turbopack","root","outputFileTracingRoot","turbo","createProject","normalizePath","relative","jsConfig","getTurbopackJsConfig","watch","enable","pollIntervalMs","watchOptions","defineEnv","createDefineEnv","isTurbopack","config","fetchCacheKeyPrefix","middlewareMatchers","previewProps","prerenderManifest","preview","browserslistQuery","noMangling","persistentCaching","isPersistentCachingEnabled","memoryLimit","turbopackMemoryLimit","isShortSession","backgroundLogCompilationEvents","eventTypes","setBundlerFindSourceMapImplementation","bind","onDevServerCleanup","onExit","entrypointsSubscription","entrypointsSubscribe","currentWrittenEntrypoints","Map","currentEntrypoints","global","app","document","error","middleware","instrumentation","page","currentTopLevelIssues","currentEntryIssues","manifestLoader","TurbopackManifestLoader","changeSubscriptions","serverPathState","readyIds","Set","currentEntriesHandlingResolve","currentEntriesHandling","Promise","resolve","assetMapper","AssetMapper","clearRequireCache","key","writtenEndpoint","force","path","contentHash","serverPaths","set","hasChange","endsWith","localKey","localHash","get","globalHash","__next__clear_chunk_cache__","p","file","clearModuleContext","deleteCache","buildingIds","startBuilding","id","requestUrl","forceRebuild","has","size","consoleStore","setState","loading","trigger","url","add","finishBuilding","delete","hmrEventHappened","hmrHash","clients","clientStates","WeakMap","sendToClient","client","send","stringify","sendEnqueuedMessages","issueMap","values","filter","severity","state","clientIssues","hmrPayloads","clear","turbopackUpdates","action","HMR_ACTIONS_SENT_TO_BROWSER","TURBOPACK_MESSAGE","data","sendEnqueuedMessagesDebounce","debounce","sendHmr","sendTurbopackMessage","diagnostics","issues","push","subscribeToChanges","includeIssues","endpoint","makePayload","onError","side","splitEntryKey","changedPromise","changed","change","processIssues","String","e","unsubscribeFromChanges","subscription","return","subscribeToHmrEvents","getEntryKey","hasEntrypointForKey","subscriptions","hmrEvents","next","type","reloadAction","RELOAD_PAGE","close","unsubscribeFromHmrEvents","handleEntrypointsSubscription","entrypoints","processTopLevelIssues","handleEntrypoints","devRewrites","productionRewrites","logErrors","hooks","handleWrittenEndpoint","result","forceDeleteCache","propagateServerField","mkdir","recursive","writeFile","middlewares","getOverlayMiddleware","isSrcDir","getSourceMapMiddleware","getNextErrorFeedbackMiddleware","telemetry","getDevOverlayFontMiddleware","getDisableDevIndicatorMiddleware","getRestartDevServerMiddleware","turbopackProject","devToolsConfigMiddleware","sendUpdateSignal","hotReloader","DEVTOOLS_CONFIG","versionInfoPromise","getVersionInfo","devtoolsFrontendUrl","nodeDebugType","getNodeDebugType","debugPort","debugInfo","debugInfoList","fetch","then","res","json","activeWebpackConfigs","serverStats","edgeServerStats","run","req","_parsedUrl","startsWith","params","matchNextPageBundleRequest","decodedPagePath","param","decodeURIComponent","denormalizedPagePath","denormalizePagePath","ensurePage","clientOnly","definition","catch","console","calledNext","finished","onHMR","socket","head","onUpgrade","handleUpgrade","on","addEventListener","parsedData","event","manualTraceChild","spanName","msToNs","startTime","endTime","attributes","updatedModules","isPageHidden","hadRuntimeError","dependencyChain","Log","warn","FAST_REFRESH_RUNTIME_RELOAD","Array","isArray","cleanedModulePath","browserDebugInfoInTerminal","receiveBrowserLogsTurbopack","entries","router","sourceType","Error","turbopackConnected","TURBOPACK_CONNECTED","errors","entryIssues","issue","message","formatIssue","printNonFatalIssue","devIndicatorServerState","disabledUntil","Date","now","versionInfo","devToolsConfig","getDevToolsConfig","sync","SYNC","warnings","hash","debug","devIndicator","setHmrServerError","_error","clearHmrServerError","start","getCompilationErrors","appEntryKey","pagesEntryKey","topLevelIssues","thisEntryIssues","formattedIssue","isWellKnownError","invalidate","reloadAfterInvalidation","entrypoint","clearAllModuleContexts","SERVER_COMPONENT_CHANGES","buildFallbackError","inputPage","appPaths","isApp","traceChild","traceAsyncFn","BLOCKED_PAGES","includes","routeDef","findPagePathData","pageExtensions","pagesDir","appDir","globalNotFound","isAppPageRouteDefinition","normalizedPage","normalizeAppPath","matchingAppPaths","pathname","handlePagesErrorRoute","setPathsForKey","clientPaths","isInsideAppDir","bundlePath","isEntryMetadataRouteFile","isMetadataRouteFile","filename","normalizedAppPage","normalizedPageToTurbopackStructureRoute","extname","route","PageNotFoundError","handleRouteType","wsClient","terminate","exit","writeManifests","handleProjectUpdates","updateMessage","updateInfoSubscribe","updateType","BUILDING","addErrors","errorsMap","details","detail","renderStyledStringToErrorAnsi","clientErrors","BUILT","time","value","duration","timeMessage","round"],"mappings":";;;;+BAmKsBA;;;eAAAA;;;0BAlKW;sBACO;qBACV;2DAEf;uBAGuB;kCASM;qBASZ;6DACX;oCAId;2BACuB;qCAIvB;uBAC2B;wBACT;8BACG;8BAIrB;qCAC6B;uBACd;gCAgBf;iCAKA;gCACiC;sCACP;0BAM1B;0BACqC;uCACA;wCACH;0BACR;wBAEA;iCACG;mCACkB;gDACP;wBAUxC;6CACqC;yCACJ;wCACS;4CACH;mCACC;wBACV;6BACO;+BACd;0CAIvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,MAAMC,WAAW,IAAIC,WAAE,CAACC,MAAM,CAAC;IAAEC,UAAU;AAAK;AAChD,MAAMC,aAAa,C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AAMgS,SAAS,IAAIjN;wBACnB8R,UAAU7E,QAAQvM;wBAElB,KAAK,MAAMqD,UAAUJ,QAAS;4BAC5B,MAAMY,QAAQX,aAAazB,GAAG,CAAC4B;4BAC/B,IAAI,CAACQ,OAAO;gCACV;4BACF;4BAEA,MAAM4N,eAAe,IAAInS,IAAIiN;4BAC7B6E,UAAUK,cAAc5N,MAAMC,YAAY;4BAE1CV,aAAaC,QAAQ;gCACnBa,QAAQC,6CAA2B,CAACuN,KAAK;gCACzCnE,MAAM/H,OAAO,EAAExC;gCACfuJ,QAAQ;uCAAIkF,aAAa/N,MAAM;iCAAG;gCAClC4J,UAAU,EAAE;4BACd;wBACF;wBAEA,IAAIvK,kBAAkB;4BACpB,MAAM4O,OAAOX,cAAcY,KAAK,CAACC,QAAQ;4BACzC,MAAMC,cACJH,OAAO,OAAO,GAAG5Y,KAAKgZ,KAAK,CAACJ,OAAO,OAAO,GAAG,CAAC,CAAC,GAAG,GAAGA,KAAK,EAAE,CAAC;4BAC/DlG,KAAIX,KAAK,CAAC,CAAC,YAAY,EAAEgH,aAAa;4BACtC/O,mBAAmB;wBACrB;wBACA;oBACF;gBACA;YACF;QACF;IACF;IAEAgO,uBAAuB7G,KAAK,CAAC,CAAC5P;QAC5B6P,QAAQxK,KAAK,CAACrF;QACd7B,QAAQoY,IAAI,CAAC;IACf;IAEA,OAAO1I;AACT","ignoreList":[0]}
1
+ {"version":3,"sources":["../../../src/server/dev/hot-reloader-turbopack.ts"],"sourcesContent":["import type { Socket } from 'net'\nimport { mkdir, writeFile } from 'fs/promises'\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 HMR_ACTION_TYPES,\n NextJsHotReloaderInterface,\n ReloadPageAction,\n SyncAction,\n TurbopackConnectedAction,\n} from './hot-reloader-types'\nimport { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'\nimport type {\n Update as TurbopackUpdate,\n Endpoint,\n WrittenEndpoint,\n TurbopackResult,\n Project,\n Entrypoints,\n} from '../../build/swc/types'\nimport { createDefineEnv } from '../../build/swc'\nimport * as Log from '../../build/output/log'\nimport {\n getVersionInfo,\n matchNextPageBundleRequest,\n} from './hot-reloader-webpack'\nimport { BLOCKED_PAGES } from '../../shared/lib/constants'\nimport {\n getOverlayMiddleware,\n getSourceMapMiddleware,\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 { FAST_REFRESH_RUNTIME_RELOAD } 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 { getNodeDebugType } from '../lib/utils'\nimport { isMetadataRouteFile } 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 getTurbopackJsConfig,\n isPersistentCachingEnabled,\n isWellKnownError,\n processIssues,\n renderStyledStringToErrorAnsi,\n type EntryIssuesMap,\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/utils'\nimport { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'\nimport { normalizePath } from '../../lib/normalize-path'\nimport {\n devToolsConfigMiddleware,\n getDevToolsConfig,\n} from '../../next-devtools/server/devtools-config-middleware'\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\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): Promise<NextJsHotReloaderInterface> {\n const dev = true\n const buildId = 'development'\n const { nextConfig, dir: projectPath } = opts\n\n const { loadBindings } =\n require('../../build/swc') as typeof import('../../build/swc')\n\n let bindings = await loadBindings()\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 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 persistent caching 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 jsConfig: await getTurbopackJsConfig(projectPath, 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.prerenderManifest.preview,\n browserslistQuery: supportedBrowsers.join(', '),\n noMangling: false,\n currentNodeJsVersion,\n },\n {\n persistentCaching: isPersistentCachingEnabled(opts.nextConfig),\n memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,\n isShortSession: false,\n }\n )\n backgroundLogCompilationEvents(project, {\n eventTypes: ['StartupCacheInvalidationEvent', 'TimingEvent'],\n })\n setBundlerFindSourceMapImplementation(\n getSourceMapFromTurbopack.bind(null, project, projectPath)\n )\n opts.onDevServerCleanup?.(async () => {\n setBundlerFindSourceMapImplementation(() => undefined)\n await project.onExit()\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 })\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 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 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(key, contentHash)\n serverPathState.set(path, contentHash)\n } else {\n if (!localHash) {\n serverPathState.set(key, contentHash)\n }\n if (!globalHash) {\n serverPathState.set(path, contentHash)\n }\n }\n }\n\n if (!hasChange) {\n return false\n }\n }\n\n resetFetch()\n\n // Not available in:\n // - Pages Router (no server-side HMR)\n // - Edge Runtime (uses browser runtime which already disposes chunks individually)\n if (typeof __next__clear_chunk_cache__ === 'function') {\n __next__clear_chunk_cache__()\n }\n\n const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>\n join(distDir, p)\n )\n\n for (const file of serverPaths) {\n clearModuleContext(file)\n deleteCache(file)\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 hmrEventHappened = false\n let hmrHash = 0\n\n const clients = new Set<ws>()\n const clientStates = new WeakMap<ws, ClientState>()\n\n function sendToClient(client: ws, payload: HMR_ACTION_TYPES) {\n client.send(JSON.stringify(payload))\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 clients) {\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 payload of state.hmrPayloads.values()) {\n sendToClient(client, payload)\n }\n state.hmrPayloads.clear()\n\n if (state.turbopackUpdates.length > 0) {\n sendToClient(client, {\n action: HMR_ACTIONS_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, payload: HMR_ACTION_TYPES) => {\n for (const client of clients) {\n clientStates.get(client)?.hmrPayloads.set(id, payload)\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 clients) {\n clientStates.get(client)?.turbopackUpdates.push(payload)\n }\n\n hmrEventHappened = true\n sendEnqueuedMessagesDebounce()\n }\n\n async function subscribeToChanges(\n key: EntryKey,\n includeIssues: boolean,\n endpoint: Endpoint,\n makePayload: (\n change: TurbopackResult,\n hash: string\n ) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | void,\n onError?: (\n error: Error\n ) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | 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 payload = await makePayload(change, String(++hmrHash))\n if (payload) {\n sendHmr(key, payload)\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 unsubscribeFromChanges(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 subscribeToHmrEvents(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)\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)\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 reloadAction: ReloadPageAction = {\n action: HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE,\n data: `error in HMR event subscription for ${id}: ${e}`,\n }\n sendToClient(client, reloadAction)\n client.close()\n return\n }\n }\n\n function unsubscribeFromHmrEvents(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 processTopLevelIssues(currentTopLevelIssues, entrypoints)\n\n await handleEntrypoints({\n entrypoints,\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 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,\n unsubscribeFromChanges,\n unsubscribeFromHmrEvents,\n },\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 action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG,\n data,\n })\n },\n }),\n ]\n\n const versionInfoPromise = getVersionInfo()\n\n let devtoolsFrontendUrl: string | undefined\n const nodeDebugType = getNodeDebugType()\n if (nodeDebugType) {\n const debugPort = process.debugPort\n let debugInfo\n try {\n // It requires to use 127.0.0.1 instead of localhost for server-side fetching.\n const debugInfoList = await fetch(\n `http://127.0.0.1:${debugPort}/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 onUpgrade(client)\n const clientIssues: EntryIssuesMap = new Map()\n const subscriptions: Map<string, AsyncIterator<any>> = new Map()\n\n clients.add(client)\n clientStates.set(client, {\n clientIssues,\n hmrPayloads: 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 clients.delete(client)\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 if (nextConfig.experimental.browserDebugInfoInTerminal) {\n await receiveBrowserLogsTurbopack({\n entries: parsedData.entries,\n router: parsedData.router,\n sourceType: parsedData.sourceType,\n project,\n projectPath,\n distDir,\n config: nextConfig.experimental.browserDebugInfoInTerminal,\n })\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 subscribeToHmrEvents(client, parsedData.path)\n break\n\n case 'turbopack-unsubscribe':\n unsubscribeFromHmrEvents(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 turbopackConnected: TurbopackConnectedAction = {\n action: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,\n data: { sessionId },\n }\n sendToClient(client, turbopackConnected)\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 versionInfoPromise\n const devToolsConfig = await getDevToolsConfig(distDir)\n\n const sync: SyncAction = {\n action: HMR_ACTIONS_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, sync)\n })()\n })\n },\n\n send(action) {\n const payload = JSON.stringify(action)\n for (const client of clients) {\n client.send(payload)\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 action: HMR_ACTIONS_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 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,\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 === '/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,\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 })\n },\n close() {\n for (const wsClient of clients) {\n // it's okay to not cleanly close these websocket connections, this is dev\n wsClient.terminate()\n }\n clients.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({ action: HMR_ACTIONS_SENT_TO_BROWSER.BUILDING })\n break\n }\n case 'end': {\n sendEnqueuedMessages()\n\n function addErrors(\n errorsMap: Map<string, CompilationError>,\n issues: EntryIssuesMap\n ) {\n for (const issueMap of issues.values()) {\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\n const errors = new Map<string, CompilationError>()\n addErrors(errors, currentEntryIssues)\n\n for (const client of clients) {\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 action: HMR_ACTIONS_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 break\n }\n default:\n }\n }\n }\n\n handleProjectUpdates().catch((err) => {\n console.error(err)\n process.exit(1)\n })\n\n return hotReloader\n}\n"],"names":["createHotReloaderTurbopack","wsServer","ws","Server","noServer","isTestMode","process","env","NEXT_TEST_MODE","__NEXT_TEST_MODE","DEBUG","sessionId","Math","floor","Number","MAX_SAFE_INTEGER","random","rewriteTurbopackSources","projectRoot","sourceMap","section","sections","map","i","sources","length","pathToFileURL","join","replace","toString","getSourceMapFromTurbopack","project","sourceURL","sourceMapJson","getSourceMapSync","err","undefined","payload","JSON","parse","opts","serverFields","distDir","resetFetch","nextConfig","dev","buildId","dir","projectPath","loadBindings","require","bindings","log","testMode","hasRewrites","fsChecker","rewrites","afterFiles","beforeFiles","fallback","hotReloaderSpan","trace","version","__NEXT_VERSION","stop","encryptionKey","generateEncryptionKeyBase64","isBuild","clientRouterFilters","experimental","clientRouterFilter","supportedBrowsers","getSupportedBrowsers","currentNodeJsVersion","versions","node","rootPath","turbopack","root","outputFileTracingRoot","turbo","createProject","normalizePath","relative","jsConfig","getTurbopackJsConfig","watch","enable","pollIntervalMs","watchOptions","defineEnv","createDefineEnv","isTurbopack","config","fetchCacheKeyPrefix","middlewareMatchers","previewProps","prerenderManifest","preview","browserslistQuery","noMangling","persistentCaching","isPersistentCachingEnabled","memoryLimit","turbopackMemoryLimit","isShortSession","backgroundLogCompilationEvents","eventTypes","setBundlerFindSourceMapImplementation","bind","onDevServerCleanup","onExit","entrypointsSubscription","entrypointsSubscribe","currentWrittenEntrypoints","Map","currentEntrypoints","global","app","document","error","middleware","instrumentation","page","currentTopLevelIssues","currentEntryIssues","manifestLoader","TurbopackManifestLoader","changeSubscriptions","serverPathState","readyIds","Set","currentEntriesHandlingResolve","currentEntriesHandling","Promise","resolve","assetMapper","AssetMapper","clearRequireCache","key","writtenEndpoint","force","path","contentHash","serverPaths","set","hasChange","endsWith","localKey","localHash","get","globalHash","__next__clear_chunk_cache__","p","file","clearModuleContext","deleteCache","buildingIds","startBuilding","id","requestUrl","forceRebuild","has","size","consoleStore","setState","loading","trigger","url","add","finishBuilding","delete","hmrEventHappened","hmrHash","clients","clientStates","WeakMap","sendToClient","client","send","stringify","sendEnqueuedMessages","issueMap","values","filter","severity","state","clientIssues","hmrPayloads","clear","turbopackUpdates","action","HMR_ACTIONS_SENT_TO_BROWSER","TURBOPACK_MESSAGE","data","sendEnqueuedMessagesDebounce","debounce","sendHmr","sendTurbopackMessage","diagnostics","issues","push","subscribeToChanges","includeIssues","endpoint","makePayload","onError","side","splitEntryKey","changedPromise","changed","change","processIssues","String","e","unsubscribeFromChanges","subscription","return","subscribeToHmrEvents","getEntryKey","hasEntrypointForKey","subscriptions","hmrEvents","next","type","reloadAction","RELOAD_PAGE","close","unsubscribeFromHmrEvents","handleEntrypointsSubscription","entrypoints","processTopLevelIssues","handleEntrypoints","devRewrites","productionRewrites","logErrors","hooks","handleWrittenEndpoint","result","forceDeleteCache","propagateServerField","mkdir","recursive","writeFile","middlewares","getOverlayMiddleware","isSrcDir","getSourceMapMiddleware","getNextErrorFeedbackMiddleware","telemetry","getDevOverlayFontMiddleware","getDisableDevIndicatorMiddleware","getRestartDevServerMiddleware","turbopackProject","devToolsConfigMiddleware","sendUpdateSignal","hotReloader","DEVTOOLS_CONFIG","versionInfoPromise","getVersionInfo","devtoolsFrontendUrl","nodeDebugType","getNodeDebugType","debugPort","debugInfo","debugInfoList","fetch","then","res","json","activeWebpackConfigs","serverStats","edgeServerStats","run","req","_parsedUrl","startsWith","params","matchNextPageBundleRequest","decodedPagePath","param","decodeURIComponent","denormalizedPagePath","denormalizePagePath","ensurePage","clientOnly","definition","catch","console","calledNext","finished","onHMR","socket","head","onUpgrade","handleUpgrade","on","addEventListener","parsedData","event","manualTraceChild","spanName","msToNs","startTime","endTime","attributes","updatedModules","isPageHidden","hadRuntimeError","dependencyChain","Log","warn","FAST_REFRESH_RUNTIME_RELOAD","Array","isArray","cleanedModulePath","browserDebugInfoInTerminal","receiveBrowserLogsTurbopack","entries","router","sourceType","Error","turbopackConnected","TURBOPACK_CONNECTED","errors","entryIssues","issue","message","formatIssue","printNonFatalIssue","devIndicatorServerState","disabledUntil","Date","now","versionInfo","devToolsConfig","getDevToolsConfig","sync","SYNC","warnings","hash","debug","devIndicator","setHmrServerError","_error","clearHmrServerError","start","getCompilationErrors","appEntryKey","pagesEntryKey","topLevelIssues","thisEntryIssues","formattedIssue","isWellKnownError","invalidate","reloadAfterInvalidation","entrypoint","clearAllModuleContexts","SERVER_COMPONENT_CHANGES","buildFallbackError","inputPage","appPaths","isApp","traceChild","traceAsyncFn","BLOCKED_PAGES","includes","routeDef","findPagePathData","pageExtensions","pagesDir","appDir","globalNotFound","isAppPageRouteDefinition","normalizedPage","normalizeAppPath","matchingAppPaths","pathname","handlePagesErrorRoute","setPathsForKey","clientPaths","isInsideAppDir","bundlePath","isEntryMetadataRouteFile","isMetadataRouteFile","filename","normalizedAppPage","normalizedPageToTurbopackStructureRoute","extname","route","PageNotFoundError","handleRouteType","wsClient","terminate","exit","writeManifests","handleProjectUpdates","updateMessage","updateInfoSubscribe","updateType","BUILDING","addErrors","errorsMap","details","detail","renderStyledStringToErrorAnsi","clientErrors","BUILT","time","value","duration","timeMessage","round"],"mappings":";;;;+BAmKsBA;;;eAAAA;;;0BAlKW;sBACO;qBACV;2DAEf;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;IACf;IAEA,OAAO1I;AACT","ignoreList":[0]}
@@ -262,7 +262,7 @@ class HotReloaderWebpack {
262
262
  this.previewProps = previewProps;
263
263
  this.rewrites = rewrites;
264
264
  this.hotReloaderSpan = (0, _trace.trace)('hot-reloader', undefined, {
265
- version: "15.4.2-canary.51"
265
+ version: "15.4.2-canary.53"
266
266
  });
267
267
  // Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing
268
268
  // of the current `next dev` invocation.
@@ -80,7 +80,7 @@ function logStartInfo({ networkUrl, appUrl, envInfo, experimentalFeatures, maxEx
80
80
  } else {
81
81
  bundlerSuffix = '';
82
82
  }
83
- _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"15.4.2-canary.51"}`))}${bundlerSuffix}`);
83
+ _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"15.4.2-canary.53"}`))}${bundlerSuffix}`);
84
84
  if (appUrl) {
85
85
  _log.bootstrap(`- Local: ${appUrl}`);
86
86
  }
@@ -142,30 +142,30 @@ async function createRouteTypesManifest({ dir, pageRoutes, appRoutes, appRouteHa
142
142
  appRouteHandlerRoutes: {},
143
143
  redirectRoutes: {},
144
144
  rewriteRoutes: {},
145
- appRouteHandlers: new Set(appRouteHandlers.map(({ filePath })=>filePath)),
146
- pageApiRoutes: new Set(pageApiRoutes.map(({ filePath })=>filePath)),
147
- appPagePaths: new Set(appRoutes.map(({ filePath })=>filePath)),
148
- pagesRouterPagePaths: new Set(pageRoutes.map(({ filePath })=>filePath)),
149
- layoutPaths: new Set(layoutRoutes.map(({ filePath })=>filePath)),
145
+ appRouteHandlers: new Set(appRouteHandlers.map(({ filePath })=>getRelativePath(filePath))),
146
+ pageApiRoutes: new Set(pageApiRoutes.map(({ filePath })=>getRelativePath(filePath))),
147
+ appPagePaths: new Set(appRoutes.map(({ filePath })=>getRelativePath(filePath))),
148
+ pagesRouterPagePaths: new Set(pageRoutes.map(({ filePath })=>getRelativePath(filePath))),
149
+ layoutPaths: new Set(layoutRoutes.map(({ filePath })=>getRelativePath(filePath))),
150
150
  filePathToRoute: new Map([
151
151
  ...appRoutes.map(({ route, filePath })=>[
152
- filePath,
152
+ getRelativePath(filePath),
153
153
  resolveInterceptingRoute(route)
154
154
  ]),
155
155
  ...layoutRoutes.map(({ route, filePath })=>[
156
- filePath,
156
+ getRelativePath(filePath),
157
157
  resolveInterceptingRoute(route)
158
158
  ]),
159
159
  ...appRouteHandlers.map(({ route, filePath })=>[
160
- filePath,
160
+ getRelativePath(filePath),
161
161
  resolveInterceptingRoute(route)
162
162
  ]),
163
163
  ...pageRoutes.map(({ route, filePath })=>[
164
- filePath,
164
+ getRelativePath(filePath),
165
165
  route
166
166
  ]),
167
167
  ...pageApiRoutes.map(({ route, filePath })=>[
168
- filePath,
168
+ getRelativePath(filePath),
169
169
  route
170
170
  ])
171
171
  ])
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/server/lib/router-utils/route-types-utils.ts"],"sourcesContent":["import path from 'path'\nimport {\n getRouteRegex,\n type Group,\n} from '../../../shared/lib/router/utils/route-regex'\nimport type { NextConfigComplete } from '../../config-shared'\n\nimport fs from 'fs'\nimport {\n generateRouteTypesFile,\n generateLinkTypesFile,\n generateValidatorFile,\n} from './typegen'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from '../../../shared/lib/router/utils/interception-routes'\n\ninterface RouteInfo {\n path: string\n groups: { [groupName: string]: Group }\n}\n\nexport interface RouteTypesManifest {\n appRoutes: Record<string, RouteInfo>\n pageRoutes: Record<string, RouteInfo>\n layoutRoutes: Record<string, RouteInfo & { slots: string[] }>\n appRouteHandlerRoutes: Record<string, RouteInfo>\n /** Map of redirect source => RouteInfo */\n redirectRoutes: Record<string, RouteInfo>\n /** Map of rewrite source => RouteInfo */\n rewriteRoutes: Record<string, RouteInfo>\n /** File paths for validation */\n appPagePaths: Set<string>\n pagesRouterPagePaths: Set<string>\n layoutPaths: Set<string>\n appRouteHandlers: Set<string>\n pageApiRoutes: Set<string>\n /** Direct mapping from file paths to routes for validation */\n filePathToRoute: Map<string, string>\n}\n\n// Convert a custom-route source string (`/blog/:slug`, `/docs/:path*`, ...)\n// into the bracket-syntax used by other Next.js route helpers so that we can\n// reuse `getRouteRegex()` to extract groups.\nexport function convertCustomRouteSource(source: string): string[] {\n const parseResult = tryToParsePath(source)\n\n if (parseResult.error || !parseResult.tokens) {\n // Fallback to original source if parsing fails\n return source.startsWith('/') ? [source] : ['/' + source]\n }\n\n const possibleNormalizedRoutes = ['']\n let slugCnt = 1\n\n function append(suffix: string) {\n for (let i = 0; i < possibleNormalizedRoutes.length; i++) {\n possibleNormalizedRoutes[i] += suffix\n }\n }\n\n function fork(suffix: string) {\n const currentLength = possibleNormalizedRoutes.length\n for (let i = 0; i < currentLength; i++) {\n possibleNormalizedRoutes.push(possibleNormalizedRoutes[i] + suffix)\n }\n }\n\n for (const token of parseResult.tokens) {\n if (typeof token === 'object') {\n // Make sure the slug is always named.\n const slug = token.name || (slugCnt++ === 1 ? 'slug' : `slug${slugCnt}`)\n if (token.modifier === '*') {\n append(`${token.prefix}[[...${slug}]]`)\n } else if (token.modifier === '+') {\n append(`${token.prefix}[...${slug}]`)\n } else if (token.modifier === '') {\n if (token.pattern === '[^\\\\/#\\\\?]+?') {\n // A safe slug\n append(`${token.prefix}[${slug}]`)\n } else if (token.pattern === '.*') {\n // An optional catch-all slug\n append(`${token.prefix}[[...${slug}]]`)\n } else if (token.pattern === '.+') {\n // A catch-all slug\n append(`${token.prefix}[...${slug}]`)\n } else {\n // Other regex patterns are not supported. Skip this route.\n return []\n }\n } else if (token.modifier === '?') {\n if (/^[a-zA-Z0-9_/]*$/.test(token.pattern)) {\n // An optional slug with plain text only, fork the route.\n append(token.prefix)\n fork(token.pattern)\n } else {\n // Optional modifier `?` and regex patterns are not supported.\n return []\n }\n }\n } else if (typeof token === 'string') {\n append(token)\n }\n }\n\n // Ensure leading slash\n return possibleNormalizedRoutes.map((route) =>\n route.startsWith('/') ? route : '/' + route\n )\n}\n\n/**\n * Extracts route parameters from a route pattern\n */\nexport function extractRouteParams(route: string) {\n const regex = getRouteRegex(route)\n return regex.groups\n}\n\n/**\n * Resolves an intercepting route to its canonical equivalent\n * Example: /gallery/test/(..)photo/[id] -> /gallery/photo/[id]\n */\nfunction resolveInterceptingRoute(route: string): string {\n // Reuse centralized interception route normalization logic\n try {\n if (!isInterceptionRouteAppPath(route)) return route\n const { interceptedRoute } = extractInterceptionRouteInformation(route)\n return interceptedRoute\n } catch {\n // If parsing fails, fall back to the original route\n return route\n }\n}\n\n/**\n * Creates a route types manifest from processed route data\n * (used for both build and dev)\n */\nexport async function createRouteTypesManifest({\n dir,\n pageRoutes,\n appRoutes,\n appRouteHandlers,\n pageApiRoutes,\n layoutRoutes,\n slots,\n redirects,\n rewrites,\n validatorFilePath,\n}: {\n dir: string\n pageRoutes: Array<{ route: string; filePath: string }>\n appRoutes: Array<{ route: string; filePath: string }>\n appRouteHandlers: Array<{ route: string; filePath: string }>\n pageApiRoutes: Array<{ route: string; filePath: string }>\n layoutRoutes: Array<{ route: string; filePath: string }>\n slots: Array<{ name: string; parent: string }>\n redirects?: NextConfigComplete['redirects']\n rewrites?: NextConfigComplete['rewrites']\n validatorFilePath?: string\n}): Promise<RouteTypesManifest> {\n // Helper function to calculate the correct relative path\n const getRelativePath = (filePath: string) => {\n if (validatorFilePath) {\n // For validator generation, calculate path relative to validator directory\n return path.relative(path.dirname(validatorFilePath), filePath)\n }\n // For other uses, calculate path relative to project directory\n return path.relative(dir, filePath)\n }\n\n const manifest: RouteTypesManifest = {\n appRoutes: {},\n pageRoutes: {},\n layoutRoutes: {},\n appRouteHandlerRoutes: {},\n redirectRoutes: {},\n rewriteRoutes: {},\n appRouteHandlers: new Set(appRouteHandlers.map(({ filePath }) => filePath)),\n pageApiRoutes: new Set(pageApiRoutes.map(({ filePath }) => filePath)),\n appPagePaths: new Set(appRoutes.map(({ filePath }) => filePath)),\n pagesRouterPagePaths: new Set(pageRoutes.map(({ filePath }) => filePath)),\n layoutPaths: new Set(layoutRoutes.map(({ filePath }) => filePath)),\n filePathToRoute: new Map([\n ...appRoutes.map(\n ({ route, filePath }) =>\n [filePath, resolveInterceptingRoute(route)] as [string, string]\n ),\n ...layoutRoutes.map(\n ({ route, filePath }) =>\n [filePath, resolveInterceptingRoute(route)] as [string, string]\n ),\n ...appRouteHandlers.map(\n ({ route, filePath }) =>\n [filePath, resolveInterceptingRoute(route)] as [string, string]\n ),\n ...pageRoutes.map(\n ({ route, filePath }) => [filePath, route] as [string, string]\n ),\n ...pageApiRoutes.map(\n ({ route, filePath }) => [filePath, route] as [string, string]\n ),\n ]),\n }\n\n // Process page routes\n for (const { route, filePath } of pageRoutes) {\n manifest.pageRoutes[route] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(route),\n }\n }\n\n // Process layout routes\n for (const { route, filePath } of layoutRoutes) {\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.layoutRoutes[resolvedRoute]) {\n manifest.layoutRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n slots: [],\n }\n }\n }\n\n // Process slots\n for (const slot of slots) {\n if (manifest.layoutRoutes[slot.parent]) {\n manifest.layoutRoutes[slot.parent].slots.push(slot.name)\n }\n }\n\n // Process app routes\n for (const { route, filePath } of appRoutes) {\n // Don't include metadata routes or pages\n if (\n !filePath.endsWith('page.ts') &&\n !filePath.endsWith('page.tsx') &&\n !filePath.endsWith('.mdx') &&\n !filePath.endsWith('.md')\n ) {\n continue\n }\n\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.appRoutes[resolvedRoute]) {\n manifest.appRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n }\n }\n }\n\n // Process app route handlers\n for (const { route, filePath } of appRouteHandlers) {\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.appRouteHandlerRoutes[resolvedRoute]) {\n manifest.appRouteHandlerRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n }\n }\n }\n\n // Process redirects\n if (typeof redirects === 'function') {\n const rd = await redirects()\n\n for (const item of rd) {\n const possibleRoutes = convertCustomRouteSource(item.source)\n for (const route of possibleRoutes) {\n manifest.redirectRoutes[route] = {\n path: route,\n groups: extractRouteParams(route),\n }\n }\n }\n }\n\n // Process rewrites\n if (typeof rewrites === 'function') {\n const rw = await rewrites()\n\n const allSources = Array.isArray(rw)\n ? rw\n : [\n ...(rw?.beforeFiles || []),\n ...(rw?.afterFiles || []),\n ...(rw?.fallback || []),\n ]\n\n for (const item of allSources) {\n const possibleRoutes = convertCustomRouteSource(item.source)\n for (const route of possibleRoutes) {\n manifest.rewriteRoutes[route] = {\n path: route,\n groups: extractRouteParams(route),\n }\n }\n }\n }\n\n return manifest\n}\n\nexport async function writeRouteTypesManifest(\n manifest: RouteTypesManifest,\n filePath: string,\n config: NextConfigComplete\n) {\n const dirname = path.dirname(filePath)\n\n if (!fs.existsSync(dirname)) {\n await fs.promises.mkdir(dirname, { recursive: true })\n }\n\n // Write the main routes.d.ts file\n await fs.promises.writeFile(filePath, generateRouteTypesFile(manifest))\n\n // Write the link.d.ts file if typedRoutes is enabled\n if (config.experimental?.typedRoutes === true) {\n const linkTypesPath = path.join(dirname, 'link.d.ts')\n await fs.promises.writeFile(linkTypesPath, generateLinkTypesFile(manifest))\n }\n}\n\nexport async function writeValidatorFile(\n manifest: RouteTypesManifest,\n filePath: string\n) {\n const dirname = path.dirname(filePath)\n\n if (!fs.existsSync(dirname)) {\n await fs.promises.mkdir(dirname, { recursive: true })\n }\n\n await fs.promises.writeFile(filePath, generateValidatorFile(manifest))\n}\n"],"names":["convertCustomRouteSource","createRouteTypesManifest","extractRouteParams","writeRouteTypesManifest","writeValidatorFile","source","parseResult","tryToParsePath","error","tokens","startsWith","possibleNormalizedRoutes","slugCnt","append","suffix","i","length","fork","currentLength","push","token","slug","name","modifier","prefix","pattern","test","map","route","regex","getRouteRegex","groups","resolveInterceptingRoute","isInterceptionRouteAppPath","interceptedRoute","extractInterceptionRouteInformation","dir","pageRoutes","appRoutes","appRouteHandlers","pageApiRoutes","layoutRoutes","slots","redirects","rewrites","validatorFilePath","getRelativePath","filePath","path","relative","dirname","manifest","appRouteHandlerRoutes","redirectRoutes","rewriteRoutes","Set","appPagePaths","pagesRouterPagePaths","layoutPaths","filePathToRoute","Map","resolvedRoute","slot","parent","endsWith","rd","item","possibleRoutes","rw","allSources","Array","isArray","beforeFiles","afterFiles","fallback","config","fs","existsSync","promises","mkdir","recursive","writeFile","generateRouteTypesFile","experimental","typedRoutes","linkTypesPath","join","generateLinkTypesFile","generateValidatorFile"],"mappings":";;;;;;;;;;;;;;;;;;IA8CgBA,wBAAwB;eAAxBA;;IA+FMC,wBAAwB;eAAxBA;;IAzBNC,kBAAkB;eAAlBA;;IAsMMC,uBAAuB;eAAvBA;;IAqBAC,kBAAkB;eAAlBA;;;6DA/UL;4BAIV;2DAGQ;yBAKR;gCACwB;oCAIxB;;;;;;AA6BA,SAASJ,yBAAyBK,MAAc;IACrD,MAAMC,cAAcC,IAAAA,8BAAc,EAACF;IAEnC,IAAIC,YAAYE,KAAK,IAAI,CAACF,YAAYG,MAAM,EAAE;QAC5C,+CAA+C;QAC/C,OAAOJ,OAAOK,UAAU,CAAC,OAAO;YAACL;SAAO,GAAG;YAAC,MAAMA;SAAO;IAC3D;IAEA,MAAMM,2BAA2B;QAAC;KAAG;IACrC,IAAIC,UAAU;IAEd,SAASC,OAAOC,MAAc;QAC5B,IAAK,IAAIC,IAAI,GAAGA,IAAIJ,yBAAyBK,MAAM,EAA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AAY,qBAAnBR,qBAAqBS,WAAW,MAAK,MAAM;QAC7C,MAAMC,gBAAgBrC,aAAI,CAACsC,IAAI,CAACpC,SAAS;QACzC,MAAM0B,WAAE,CAACE,QAAQ,CAACG,SAAS,CAACI,eAAeE,IAAAA,8BAAqB,EAACpC;IACnE;AACF;AAEO,eAAe/C,mBACpB+C,QAA4B,EAC5BJ,QAAgB;IAEhB,MAAMG,UAAUF,aAAI,CAACE,OAAO,CAACH;IAE7B,IAAI,CAAC6B,WAAE,CAACC,UAAU,CAAC3B,UAAU;QAC3B,MAAM0B,WAAE,CAACE,QAAQ,CAACC,KAAK,CAAC7B,SAAS;YAAE8B,WAAW;QAAK;IACrD;IAEA,MAAMJ,WAAE,CAACE,QAAQ,CAACG,SAAS,CAAClC,UAAUyC,IAAAA,8BAAqB,EAACrC;AAC9D","ignoreList":[0]}
1
+ {"version":3,"sources":["../../../../src/server/lib/router-utils/route-types-utils.ts"],"sourcesContent":["import path from 'path'\nimport {\n getRouteRegex,\n type Group,\n} from '../../../shared/lib/router/utils/route-regex'\nimport type { NextConfigComplete } from '../../config-shared'\n\nimport fs from 'fs'\nimport {\n generateRouteTypesFile,\n generateLinkTypesFile,\n generateValidatorFile,\n} from './typegen'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from '../../../shared/lib/router/utils/interception-routes'\n\ninterface RouteInfo {\n path: string\n groups: { [groupName: string]: Group }\n}\n\nexport interface RouteTypesManifest {\n appRoutes: Record<string, RouteInfo>\n pageRoutes: Record<string, RouteInfo>\n layoutRoutes: Record<string, RouteInfo & { slots: string[] }>\n appRouteHandlerRoutes: Record<string, RouteInfo>\n /** Map of redirect source => RouteInfo */\n redirectRoutes: Record<string, RouteInfo>\n /** Map of rewrite source => RouteInfo */\n rewriteRoutes: Record<string, RouteInfo>\n /** File paths for validation */\n appPagePaths: Set<string>\n pagesRouterPagePaths: Set<string>\n layoutPaths: Set<string>\n appRouteHandlers: Set<string>\n pageApiRoutes: Set<string>\n /** Direct mapping from file paths to routes for validation */\n filePathToRoute: Map<string, string>\n}\n\n// Convert a custom-route source string (`/blog/:slug`, `/docs/:path*`, ...)\n// into the bracket-syntax used by other Next.js route helpers so that we can\n// reuse `getRouteRegex()` to extract groups.\nexport function convertCustomRouteSource(source: string): string[] {\n const parseResult = tryToParsePath(source)\n\n if (parseResult.error || !parseResult.tokens) {\n // Fallback to original source if parsing fails\n return source.startsWith('/') ? [source] : ['/' + source]\n }\n\n const possibleNormalizedRoutes = ['']\n let slugCnt = 1\n\n function append(suffix: string) {\n for (let i = 0; i < possibleNormalizedRoutes.length; i++) {\n possibleNormalizedRoutes[i] += suffix\n }\n }\n\n function fork(suffix: string) {\n const currentLength = possibleNormalizedRoutes.length\n for (let i = 0; i < currentLength; i++) {\n possibleNormalizedRoutes.push(possibleNormalizedRoutes[i] + suffix)\n }\n }\n\n for (const token of parseResult.tokens) {\n if (typeof token === 'object') {\n // Make sure the slug is always named.\n const slug = token.name || (slugCnt++ === 1 ? 'slug' : `slug${slugCnt}`)\n if (token.modifier === '*') {\n append(`${token.prefix}[[...${slug}]]`)\n } else if (token.modifier === '+') {\n append(`${token.prefix}[...${slug}]`)\n } else if (token.modifier === '') {\n if (token.pattern === '[^\\\\/#\\\\?]+?') {\n // A safe slug\n append(`${token.prefix}[${slug}]`)\n } else if (token.pattern === '.*') {\n // An optional catch-all slug\n append(`${token.prefix}[[...${slug}]]`)\n } else if (token.pattern === '.+') {\n // A catch-all slug\n append(`${token.prefix}[...${slug}]`)\n } else {\n // Other regex patterns are not supported. Skip this route.\n return []\n }\n } else if (token.modifier === '?') {\n if (/^[a-zA-Z0-9_/]*$/.test(token.pattern)) {\n // An optional slug with plain text only, fork the route.\n append(token.prefix)\n fork(token.pattern)\n } else {\n // Optional modifier `?` and regex patterns are not supported.\n return []\n }\n }\n } else if (typeof token === 'string') {\n append(token)\n }\n }\n\n // Ensure leading slash\n return possibleNormalizedRoutes.map((route) =>\n route.startsWith('/') ? route : '/' + route\n )\n}\n\n/**\n * Extracts route parameters from a route pattern\n */\nexport function extractRouteParams(route: string) {\n const regex = getRouteRegex(route)\n return regex.groups\n}\n\n/**\n * Resolves an intercepting route to its canonical equivalent\n * Example: /gallery/test/(..)photo/[id] -> /gallery/photo/[id]\n */\nfunction resolveInterceptingRoute(route: string): string {\n // Reuse centralized interception route normalization logic\n try {\n if (!isInterceptionRouteAppPath(route)) return route\n const { interceptedRoute } = extractInterceptionRouteInformation(route)\n return interceptedRoute\n } catch {\n // If parsing fails, fall back to the original route\n return route\n }\n}\n\n/**\n * Creates a route types manifest from processed route data\n * (used for both build and dev)\n */\nexport async function createRouteTypesManifest({\n dir,\n pageRoutes,\n appRoutes,\n appRouteHandlers,\n pageApiRoutes,\n layoutRoutes,\n slots,\n redirects,\n rewrites,\n validatorFilePath,\n}: {\n dir: string\n pageRoutes: Array<{ route: string; filePath: string }>\n appRoutes: Array<{ route: string; filePath: string }>\n appRouteHandlers: Array<{ route: string; filePath: string }>\n pageApiRoutes: Array<{ route: string; filePath: string }>\n layoutRoutes: Array<{ route: string; filePath: string }>\n slots: Array<{ name: string; parent: string }>\n redirects?: NextConfigComplete['redirects']\n rewrites?: NextConfigComplete['rewrites']\n validatorFilePath?: string\n}): Promise<RouteTypesManifest> {\n // Helper function to calculate the correct relative path\n const getRelativePath = (filePath: string) => {\n if (validatorFilePath) {\n // For validator generation, calculate path relative to validator directory\n return path.relative(path.dirname(validatorFilePath), filePath)\n }\n // For other uses, calculate path relative to project directory\n return path.relative(dir, filePath)\n }\n\n const manifest: RouteTypesManifest = {\n appRoutes: {},\n pageRoutes: {},\n layoutRoutes: {},\n appRouteHandlerRoutes: {},\n redirectRoutes: {},\n rewriteRoutes: {},\n appRouteHandlers: new Set(\n appRouteHandlers.map(({ filePath }) => getRelativePath(filePath))\n ),\n pageApiRoutes: new Set(\n pageApiRoutes.map(({ filePath }) => getRelativePath(filePath))\n ),\n appPagePaths: new Set(\n appRoutes.map(({ filePath }) => getRelativePath(filePath))\n ),\n pagesRouterPagePaths: new Set(\n pageRoutes.map(({ filePath }) => getRelativePath(filePath))\n ),\n layoutPaths: new Set(\n layoutRoutes.map(({ filePath }) => getRelativePath(filePath))\n ),\n filePathToRoute: new Map([\n ...appRoutes.map(\n ({ route, filePath }) =>\n [getRelativePath(filePath), resolveInterceptingRoute(route)] as [\n string,\n string,\n ]\n ),\n ...layoutRoutes.map(\n ({ route, filePath }) =>\n [getRelativePath(filePath), resolveInterceptingRoute(route)] as [\n string,\n string,\n ]\n ),\n ...appRouteHandlers.map(\n ({ route, filePath }) =>\n [getRelativePath(filePath), resolveInterceptingRoute(route)] as [\n string,\n string,\n ]\n ),\n ...pageRoutes.map(\n ({ route, filePath }) =>\n [getRelativePath(filePath), route] as [string, string]\n ),\n ...pageApiRoutes.map(\n ({ route, filePath }) =>\n [getRelativePath(filePath), route] as [string, string]\n ),\n ]),\n }\n\n // Process page routes\n for (const { route, filePath } of pageRoutes) {\n manifest.pageRoutes[route] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(route),\n }\n }\n\n // Process layout routes\n for (const { route, filePath } of layoutRoutes) {\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.layoutRoutes[resolvedRoute]) {\n manifest.layoutRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n slots: [],\n }\n }\n }\n\n // Process slots\n for (const slot of slots) {\n if (manifest.layoutRoutes[slot.parent]) {\n manifest.layoutRoutes[slot.parent].slots.push(slot.name)\n }\n }\n\n // Process app routes\n for (const { route, filePath } of appRoutes) {\n // Don't include metadata routes or pages\n if (\n !filePath.endsWith('page.ts') &&\n !filePath.endsWith('page.tsx') &&\n !filePath.endsWith('.mdx') &&\n !filePath.endsWith('.md')\n ) {\n continue\n }\n\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.appRoutes[resolvedRoute]) {\n manifest.appRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n }\n }\n }\n\n // Process app route handlers\n for (const { route, filePath } of appRouteHandlers) {\n // Use the resolved route (for interception routes, this gives us the canonical route)\n const resolvedRoute = resolveInterceptingRoute(route)\n\n if (!manifest.appRouteHandlerRoutes[resolvedRoute]) {\n manifest.appRouteHandlerRoutes[resolvedRoute] = {\n path: getRelativePath(filePath),\n groups: extractRouteParams(resolvedRoute),\n }\n }\n }\n\n // Process redirects\n if (typeof redirects === 'function') {\n const rd = await redirects()\n\n for (const item of rd) {\n const possibleRoutes = convertCustomRouteSource(item.source)\n for (const route of possibleRoutes) {\n manifest.redirectRoutes[route] = {\n path: route,\n groups: extractRouteParams(route),\n }\n }\n }\n }\n\n // Process rewrites\n if (typeof rewrites === 'function') {\n const rw = await rewrites()\n\n const allSources = Array.isArray(rw)\n ? rw\n : [\n ...(rw?.beforeFiles || []),\n ...(rw?.afterFiles || []),\n ...(rw?.fallback || []),\n ]\n\n for (const item of allSources) {\n const possibleRoutes = convertCustomRouteSource(item.source)\n for (const route of possibleRoutes) {\n manifest.rewriteRoutes[route] = {\n path: route,\n groups: extractRouteParams(route),\n }\n }\n }\n }\n\n return manifest\n}\n\nexport async function writeRouteTypesManifest(\n manifest: RouteTypesManifest,\n filePath: string,\n config: NextConfigComplete\n) {\n const dirname = path.dirname(filePath)\n\n if (!fs.existsSync(dirname)) {\n await fs.promises.mkdir(dirname, { recursive: true })\n }\n\n // Write the main routes.d.ts file\n await fs.promises.writeFile(filePath, generateRouteTypesFile(manifest))\n\n // Write the link.d.ts file if typedRoutes is enabled\n if (config.experimental?.typedRoutes === true) {\n const linkTypesPath = path.join(dirname, 'link.d.ts')\n await fs.promises.writeFile(linkTypesPath, generateLinkTypesFile(manifest))\n }\n}\n\nexport async function writeValidatorFile(\n manifest: RouteTypesManifest,\n filePath: string\n) {\n const dirname = path.dirname(filePath)\n\n if (!fs.existsSync(dirname)) {\n await fs.promises.mkdir(dirname, { recursive: true })\n }\n\n await fs.promises.writeFile(filePath, generateValidatorFile(manifest))\n}\n"],"names":["convertCustomRouteSource","createRouteTypesManifest","extractRouteParams","writeRouteTypesManifest","writeValidatorFile","source","parseResult","tryToParsePath","error","tokens","startsWith","possibleNormalizedRoutes","slugCnt","append","suffix","i","length","fork","currentLength","push","token","slug","name","modifier","prefix","pattern","test","map","route","regex","getRouteRegex","groups","resolveInterceptingRoute","isInterceptionRouteAppPath","interceptedRoute","extractInterceptionRouteInformation","dir","pageRoutes","appRoutes","appRouteHandlers","pageApiRoutes","layoutRoutes","slots","redirects","rewrites","validatorFilePath","getRelativePath","filePath","path","relative","dirname","manifest","appRouteHandlerRoutes","redirectRoutes","rewriteRoutes","Set","appPagePaths","pagesRouterPagePaths","layoutPaths","filePathToRoute","Map","resolvedRoute","slot","parent","endsWith","rd","item","possibleRoutes","rw","allSources","Array","isArray","beforeFiles","afterFiles","fallback","config","fs","existsSync","promises","mkdir","recursive","writeFile","generateRouteTypesFile","experimental","typedRoutes","linkTypesPath","join","generateLinkTypesFile","generateValidatorFile"],"mappings":";;;;;;;;;;;;;;;;;;IA8CgBA,wBAAwB;eAAxBA;;IA+FMC,wBAAwB;eAAxBA;;IAzBNC,kBAAkB;eAAlBA;;IA2NMC,uBAAuB;eAAvBA;;IAqBAC,kBAAkB;eAAlBA;;;6DApWL;4BAIV;2DAGQ;yBAKR;gCACwB;oCAIxB;;;;;;AA6BA,SAASJ,yBAAyBK,MAAc;IACrD,MAAMC,cAAcC,IAAAA,8BAAc,EAACF;IAEnC,IAAIC,YAAYE,KAAK,IAAI,CAACF,YAAYG,MAAM,EAAE;QAC5C,+CAA+C;QAC/C,OAAOJ,OAAOK,UAAU,CAAC,OAAO;YAACL;SAAO,GAAG;YAAC,MAAMA;SAAO;IAC3D;IAEA,MAAMM,2BAA2B;QAAC;KAAG;IACrC,IAAIC,UAA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