{"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["import type {\n  ExportAppResult,\n  ExportAppOptions,\n  WorkerRenderOptsPartial,\n  ExportPagesResult,\n  ExportPathEntry,\n} from './types'\nimport {\n  createStaticWorker,\n  type PrerenderManifest,\n  type StaticWorker,\n} from '../build'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\n\nimport { bold, yellow } from '../lib/picocolors'\nimport findUp from 'next/dist/compiled/find-up'\nimport { existsSync, promises as fs } from 'fs'\n\nimport '../server/require-hook'\n\nimport { dirname, join, resolve, sep, relative } from 'path'\nimport * as Log from '../build/output/log'\nimport {\n  RSC_SEGMENT_SUFFIX,\n  RSC_SEGMENTS_DIR_SUFFIX,\n  RSC_SUFFIX,\n  SSG_FALLBACK_EXPORT_ERROR,\n} from '../lib/constants'\nimport { recursiveCopy } from '../lib/recursive-copy'\nimport {\n  BUILD_ID_FILE,\n  CLIENT_PUBLIC_FILES_PATH,\n  CLIENT_STATIC_FILES_PATH,\n  EXPORT_DETAIL,\n  EXPORT_MARKER,\n  NEXT_FONT_MANIFEST,\n  MIDDLEWARE_MANIFEST,\n  PAGES_MANIFEST,\n  PHASE_EXPORT,\n  PRERENDER_MANIFEST,\n  SERVER_DIRECTORY,\n  SERVER_REFERENCE_MANIFEST,\n  APP_PATH_ROUTES_MANIFEST,\n  ROUTES_MANIFEST,\n  FUNCTIONS_CONFIG_MANIFEST,\n} from '../shared/lib/constants'\nimport loadConfig from '../server/config'\nimport type { ExportPathMap } from '../server/config-shared'\nimport { parseMaxPostponedStateSize } from '../server/config-shared'\nimport { eventCliSession } from '../telemetry/events'\nimport { hasNextSupport } from '../server/ci-info'\nimport { Telemetry } from '../telemetry/storage'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { loadEnvConfig } from '@next/env'\nimport { isAPIRoute } from '../lib/is-api-route'\nimport { getPagePath } from '../server/require'\nimport type { Span } from '../trace'\nimport type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { isAppPageRoute } from '../lib/is-app-page-route'\nimport isError from '../lib/is-error'\nimport { formatManifest } from '../build/manifests/formatter/format-manifest'\nimport { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'\nimport { createProgress } from '../build/progress'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\nimport { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info'\nimport { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding'\nimport { getNextBuildDebuggerPortOffset } from '../lib/worker'\nimport { getParams } from './helpers/get-params'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport type { Params } from '../server/request/params'\n\nexport class ExportError extends Error {\n  code = 'NEXT_EXPORT_ERROR'\n}\n\n/**\n * Picks an RDC seed by matching on the params that are\n * already known, so fallback shells use a seed that has already\n * computed those known params.\n */\nfunction buildRDCCacheByPage(\n  results: ExportPagesResult,\n  finalPhaseExportPaths: ExportPathEntry[]\n): Record<string, string> {\n  const renderResumeDataCachesByPage: Record<string, string> = {}\n  const seedCandidatesByPage = new Map<\n    string,\n    Array<{ path: string; renderResumeDataCache: string }>\n  >()\n\n  for (const { page, path, result } of results) {\n    if (!result) {\n      continue\n    }\n\n    if ('renderResumeDataCache' in result && result.renderResumeDataCache) {\n      // Collect all RDC seeds for this page so we can pick the best match\n      // for each fallback shell later (e.g. locale-specific variants).\n      const candidates = seedCandidatesByPage.get(page) ?? []\n      candidates.push({\n        path,\n        renderResumeDataCache: result.renderResumeDataCache,\n      })\n      seedCandidatesByPage.set(page, candidates)\n      // Remove the RDC string from the result so that it can be garbage\n      // collected, when there are more results for the same page.\n      result.renderResumeDataCache = undefined\n    }\n  }\n\n  const getKnownParamsKey = (\n    normalizedPage: string,\n    path: string,\n    fallbackParamNames: Set<string>\n  ): string | null => {\n    let params: Params\n    try {\n      params = getParams(normalizedPage, path)\n    } catch {\n      return null\n    }\n\n    // Only keep params that are known, then sort\n    // for a stable key so we can match a compatible seed.\n    const entries = Object.entries(params).filter(\n      ([key]) => !fallbackParamNames.has(key)\n    )\n\n    entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    return JSON.stringify(entries)\n  }\n\n  for (const exportPath of finalPhaseExportPaths) {\n    const { page, path, _fallbackRouteParams = [] } = exportPath\n    if (!isDynamicRoute(page)) {\n      continue\n    }\n\n    // Normalize app pages before param matching.\n    const normalizedPage = normalizeAppPath(page)\n    const pageKey = page !== path ? `${page}: ${path}` : path\n    const fallbackParamNames = new Set(\n      _fallbackRouteParams.map((param) => param.paramName)\n    )\n    // Build a key from the known params for this fallback shell so we can\n    // select a seed from a compatible prerendered route.\n    const targetKey = getKnownParamsKey(\n      normalizedPage,\n      path,\n      fallbackParamNames\n    )\n\n    if (!targetKey) {\n      continue\n    }\n\n    const candidates = seedCandidatesByPage.get(page)\n\n    // No suitable candidates, so there's no RDC seed to select\n    if (!candidates || candidates.length === 0) {\n      continue\n    }\n\n    let selected: string | null = null\n    for (const candidate of candidates) {\n      // Pick the seed whose known params match this fallback shell.\n      const candidateKey = getKnownParamsKey(\n        normalizedPage,\n        candidate.path,\n        fallbackParamNames\n      )\n      if (candidateKey === targetKey) {\n        selected = candidate.renderResumeDataCache\n        break\n      }\n    }\n\n    if (selected) {\n      renderResumeDataCachesByPage[pageKey] = selected\n    }\n  }\n\n  return renderResumeDataCachesByPage\n}\n\nasync function exportAppImpl(\n  dir: string,\n  options: Readonly<ExportAppOptions>,\n  span: Span,\n  staticWorker?: StaticWorker\n): Promise<ExportAppResult | null> {\n  dir = resolve(dir)\n\n  // attempt to load global env values so they are available in next.config.js\n  span.traceChild('load-dotenv').traceFn(() => loadEnvConfig(dir, false, Log))\n\n  const { enabledDirectories } = options\n\n  const nextConfig =\n    options.nextConfig ||\n    (await span.traceChild('load-next-config').traceAsyncFn(() =>\n      loadConfig(PHASE_EXPORT, dir, {\n        debugPrerender: options.debugPrerender,\n      })\n    ))\n\n  const distDir = join(dir, nextConfig.distDir)\n  const telemetry = options.buildExport ? null : new Telemetry({ distDir })\n\n  if (telemetry) {\n    telemetry.record(\n      eventCliSession(nextConfig, {\n        webpackVersion: null,\n        cliCommand: 'export',\n        isSrcDir: null,\n        hasNowJson: !!(await findUp('now.json', { cwd: dir })),\n        isCustomServer: null,\n        turboFlag: false,\n        pagesDir: null,\n        appDir: null,\n      })\n    )\n  }\n\n  const subFolders = nextConfig.trailingSlash && !options.buildExport\n\n  if (!options.silent && !options.buildExport) {\n    Log.info(`using build directory: ${distDir}`)\n  }\n\n  const buildIdFile = join(distDir, BUILD_ID_FILE)\n\n  if (!existsSync(buildIdFile)) {\n    throw new ExportError(\n      `Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id`\n    )\n  }\n\n  const customRoutes = (['rewrites', 'redirects', 'headers'] as const).filter(\n    (config) => typeof nextConfig[config] === 'function'\n  )\n\n  if (!hasNextSupport && !options.buildExport && customRoutes.length > 0) {\n    Log.warn(\n      `rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutes.join(\n        ', '\n      )}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`\n    )\n  }\n\n  const buildId = await fs.readFile(buildIdFile, 'utf8')\n\n  const pagesManifest =\n    !options.pages &&\n    (require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST)) as PagesManifest)\n\n  let prerenderManifest: DeepReadonly<PrerenderManifest> | undefined\n  try {\n    prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))\n  } catch {}\n\n  let appRoutePathManifest: Record<string, string> | undefined\n  try {\n    appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST))\n  } catch (err) {\n    if (\n      isError(err) &&\n      (err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND')\n    ) {\n      // the manifest doesn't exist which will happen when using\n      // \"pages\" dir instead of \"app\" dir.\n      appRoutePathManifest = undefined\n    } else {\n      // the manifest is malformed (invalid json)\n      throw err\n    }\n  }\n\n  const excludedPrerenderRoutes = new Set<string>()\n  const pages = options.pages || Object.keys(pagesManifest)\n  const defaultPathMap: ExportPathMap = {}\n\n  let hasApiRoutes = false\n  for (const page of pages) {\n    // _document and _app are not real pages\n    // _error is exported as 404.html later on\n    // API Routes are Node.js functions\n\n    if (isAPIRoute(page)) {\n      hasApiRoutes = true\n      continue\n    }\n\n    if (page === '/_document' || page === '/_app' || page === '/_error') {\n      continue\n    }\n\n    // iSSG pages that are dynamic should not export templated version by\n    // default. In most cases, this would never work. There is no server that\n    // could run `getStaticProps`. If users make their page work lazily, they\n    // can manually add it to the `exportPathMap`.\n    if (prerenderManifest?.dynamicRoutes[page]) {\n      excludedPrerenderRoutes.add(page)\n      continue\n    }\n\n    defaultPathMap[page] = { page }\n  }\n\n  const mapAppRouteToPage = new Map<string, string>()\n  if (!options.buildExport && appRoutePathManifest) {\n    for (const [pageName, routePath] of Object.entries(appRoutePathManifest)) {\n      mapAppRouteToPage.set(routePath, pageName)\n      if (\n        isAppPageRoute(pageName) &&\n        !prerenderManifest?.routes[routePath] &&\n        !prerenderManifest?.dynamicRoutes[routePath]\n      ) {\n        defaultPathMap[routePath] = {\n          page: pageName,\n          _isAppDir: true,\n        }\n      }\n    }\n  }\n\n  // Initialize the output directory\n  const outDir = options.outdir\n\n  if (outDir === join(dir, 'public')) {\n    throw new ExportError(\n      `The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-public`\n    )\n  }\n\n  if (outDir === join(dir, 'static')) {\n    throw new ExportError(\n      `The 'static' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-static`\n    )\n  }\n\n  await fs.rm(outDir, { recursive: true, force: true })\n  await fs.mkdir(join(outDir, '_next', buildId), { recursive: true })\n\n  await fs.writeFile(\n    join(distDir, EXPORT_DETAIL),\n    formatManifest({\n      version: 1,\n      outDirectory: outDir,\n      success: false,\n    }),\n    'utf8'\n  )\n\n  // Copy static directory\n  if (!options.buildExport && existsSync(join(dir, 'static'))) {\n    if (!options.silent) {\n      Log.info('Copying \"static\" directory')\n    }\n    await span\n      .traceChild('copy-static-directory')\n      .traceAsyncFn(() =>\n        recursiveCopy(join(dir, 'static'), join(outDir, 'static'))\n      )\n  }\n\n  // Copy .next/static directory\n  if (\n    !options.buildExport &&\n    existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))\n  ) {\n    if (!options.silent) {\n      Log.info('Copying \"static build\" directory')\n    }\n    await span\n      .traceChild('copy-next-static-directory')\n      .traceAsyncFn(() =>\n        recursiveCopy(\n          join(distDir, CLIENT_STATIC_FILES_PATH),\n          join(outDir, '_next', CLIENT_STATIC_FILES_PATH)\n        )\n      )\n  }\n\n  // Get the exportPathMap from the config file\n  if (typeof nextConfig.exportPathMap !== 'function') {\n    nextConfig.exportPathMap = async (defaultMap) => {\n      return defaultMap\n    }\n  }\n\n  const {\n    i18n,\n    images: { loader = 'default', unoptimized },\n  } = nextConfig\n\n  if (i18n && !options.buildExport) {\n    throw new ExportError(\n      `i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/messages/export-no-custom-routes`\n    )\n  }\n\n  if (!options.buildExport) {\n    const { isNextImageImported } = await span\n      .traceChild('is-next-image-imported')\n      .traceAsyncFn(() =>\n        fs\n          .readFile(join(distDir, EXPORT_MARKER), 'utf8')\n          .then((text) => JSON.parse(text))\n          .catch(() => ({}))\n      )\n\n    if (\n      isNextImageImported &&\n      loader === 'default' &&\n      !unoptimized &&\n      !hasNextSupport\n    ) {\n      throw new ExportError(\n        `Image Optimization using the default loader is not compatible with export.\n  Possible solutions:\n    - Use \\`next start\\` to run a server, which includes the Image Optimization API.\n    - Configure \\`images.unoptimized = true\\` in \\`next.config.js\\` to disable the Image Optimization API.\n  Read more: https://nextjs.org/docs/messages/export-image-api`\n      )\n    }\n  }\n\n  let serverActionsManifest: ActionManifest | undefined\n  if (enabledDirectories.app) {\n    serverActionsManifest = require(\n      join(distDir, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST + '.json')\n    ) as ActionManifest\n\n    if (nextConfig.output === 'export') {\n      const routesManifest = require(join(distDir, ROUTES_MANIFEST))\n\n      // We already prevent rewrites earlier in the process, however Next.js will insert rewrites\n      // for interception routes so we need to check for that here.\n      if (routesManifest?.rewrites?.beforeFiles?.length > 0) {\n        const hasInterceptionRouteRewrite =\n          routesManifest.rewrites.beforeFiles.some(isInterceptionRouteRewrite)\n\n        if (hasInterceptionRouteRewrite) {\n          throw new ExportError(\n            `Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features`\n          )\n        }\n      }\n\n      const actionIds = [\n        ...Object.keys(serverActionsManifest.node),\n        ...Object.keys(serverActionsManifest.edge),\n      ]\n\n      if (\n        actionIds.some(\n          (actionId) =>\n            extractInfoFromServerReferenceId(actionId).type === 'server-action'\n        )\n      ) {\n        throw new ExportError(\n          `Server Actions are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features`\n        )\n      }\n    }\n  }\n\n  // Start the rendering process\n  const renderOpts: WorkerRenderOptsPartial = {\n    previewProps: prerenderManifest?.preview,\n    isBuildTimePrerendering: true,\n    assetPrefix: nextConfig.assetPrefix.replace(/\\/$/, ''),\n    distDir,\n    basePath: nextConfig.basePath,\n    cacheComponents: nextConfig.cacheComponents ?? false,\n    trailingSlash: nextConfig.trailingSlash,\n    locales: i18n?.locales,\n    locale: i18n?.defaultLocale,\n    defaultLocale: i18n?.defaultLocale,\n    domainLocales: i18n?.domains,\n    disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,\n    // Exported pages do not currently support dynamic HTML.\n    supportsDynamicResponse: false,\n    crossOrigin: nextConfig.crossOrigin,\n    optimizeCss: nextConfig.experimental.optimizeCss,\n    nextConfigOutput: nextConfig.output,\n    nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,\n    largePageDataBytes: nextConfig.experimental.largePageDataBytes,\n    serverActions: nextConfig.experimental.serverActions,\n    serverComponents: enabledDirectories.app,\n    cacheLifeProfiles: nextConfig.cacheLife,\n    nextFontManifest: require(\n      join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)\n    ),\n    images: nextConfig.images,\n    htmlLimitedBots: nextConfig.htmlLimitedBots.source,\n    experimental: {\n      clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,\n      expireTime: nextConfig.expireTime,\n      staleTimes: nextConfig.experimental.staleTimes,\n      clientParamParsingOrigins:\n        nextConfig.experimental.clientParamParsingOrigins,\n      dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,\n      optimisticRouting: nextConfig.experimental.optimisticRouting ?? false,\n      inlineCss: nextConfig.experimental.inlineCss ?? false,\n      prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,\n      authInterrupts: !!nextConfig.experimental.authInterrupts,\n      cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,\n      maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n        nextConfig.experimental.maxPostponedStateSize\n      ),\n    },\n    reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,\n  }\n\n  // We need this for server rendering the Link component.\n  ;(globalThis as any).__NEXT_DATA__ = {\n    nextExport: true,\n  }\n\n  const exportPathMap = await span\n    .traceChild('run-export-path-map')\n    .traceAsyncFn(async () => {\n      const exportMap = await nextConfig.exportPathMap(defaultPathMap, {\n        dev: false,\n        dir,\n        outDir,\n        distDir,\n        buildId,\n      })\n      return exportMap\n    })\n\n  // During static export, remove export 404/500 of pages router\n  // when only app router presents\n  if (!options.buildExport && options.appDirOnly) {\n    delete exportPathMap['/404']\n    delete exportPathMap['/500']\n  }\n\n  // only add missing 404 page when `buildExport` is false\n  if (!options.buildExport && !options.appDirOnly) {\n    // only add missing /404 if not specified in `exportPathMap`\n    if (!exportPathMap['/404']) {\n      exportPathMap['/404'] = { page: '/_error' }\n    }\n\n    /**\n     * exports 404.html for backwards compat\n     * E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify\n     */\n    if (!exportPathMap['/404.html'] && exportPathMap['/404']) {\n      // alias /404.html to /404 to be compatible with custom 404 / _error page\n      exportPathMap['/404.html'] = exportPathMap['/404']\n    }\n  }\n\n  const allExportPaths: ExportPathEntry[] = []\n  const seenExportPaths = new Set<string>()\n  const fallbackEnabledPages = new Set<string>()\n\n  for (const [path, entry] of Object.entries(exportPathMap)) {\n    // make sure to prevent duplicates\n    const normalizedPath = denormalizePagePath(normalizePagePath(path))\n\n    if (seenExportPaths.has(normalizedPath)) {\n      continue\n    }\n\n    seenExportPaths.add(normalizedPath)\n\n    if (!entry._isAppDir && isAPIRoute(entry.page)) {\n      hasApiRoutes = true\n      continue\n    }\n\n    allExportPaths.push({ ...entry, path: normalizedPath })\n\n    if (prerenderManifest && !options.buildExport) {\n      const prerenderInfo = prerenderManifest.dynamicRoutes[entry.page]\n\n      if (prerenderInfo && prerenderInfo.fallback !== false) {\n        fallbackEnabledPages.add(entry.page)\n      }\n    }\n  }\n\n  if (allExportPaths.length === 0) {\n    if (!prerenderManifest) {\n      return null\n    }\n  }\n\n  if (fallbackEnabledPages.size > 0) {\n    throw new ExportError(\n      `Found pages with \\`fallback\\` enabled:\\n${[...fallbackEnabledPages].join(\n        '\\n'\n      )}\\n${SSG_FALLBACK_EXPORT_ERROR}\\n`\n    )\n  }\n\n  let hasMiddleware = false\n\n  if (!options.buildExport) {\n    try {\n      const middlewareManifest = require(\n        join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)\n      ) as MiddlewareManifest\n\n      const functionsConfigManifest = require(\n        join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST)\n      )\n\n      hasMiddleware =\n        Object.keys(middlewareManifest.middleware).length > 0 ||\n        Boolean(functionsConfigManifest.functions?.['/_middleware'])\n    } catch {}\n\n    // Warn if the user defines a path for an API page\n    if (hasApiRoutes || hasMiddleware) {\n      if (nextConfig.output === 'export') {\n        Log.warn(\n          yellow(\n            `Statically exporting a Next.js application via \\`next export\\` disables API routes and middleware.`\n          ) +\n            `\\n` +\n            yellow(\n              `This command is meant for static-only hosts, and is` +\n                ' ' +\n                bold(`not necessary to make your application static.`)\n            ) +\n            `\\n` +\n            yellow(\n              `Pages in your application without server-side data dependencies will be automatically statically exported by \\`next build\\`, including pages powered by \\`getStaticProps\\`.`\n            ) +\n            `\\n` +\n            yellow(\n              `Learn more: https://nextjs.org/docs/messages/api-routes-static-export`\n            )\n        )\n      }\n    }\n  }\n\n  const pagesDataDir = options.buildExport\n    ? outDir\n    : join(outDir, '_next/data', buildId)\n\n  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)\n  // Copy public directory\n  if (!options.buildExport && existsSync(publicDir)) {\n    if (!options.silent) {\n      Log.info('Copying \"public\" directory')\n    }\n    await span.traceChild('copy-public-directory').traceAsyncFn(() =>\n      recursiveCopy(publicDir, outDir, {\n        filter(path) {\n          // Exclude paths used by pages\n          return !exportPathMap[path]\n        },\n      })\n    )\n  }\n\n  const exportPagesInBatches = async (\n    worker: StaticWorker,\n    exportPaths: ExportPathEntry[],\n    renderResumeDataCachesByPage?: Record<string, string>\n  ): Promise<ExportPagesResult> => {\n    // Batch filtered pages into smaller batches, and call the export worker on\n    // each batch. We've set a default minimum of 25 pages per batch to ensure\n    // that even setups with only a few static pages can leverage a shared\n    // incremental cache, however this value can be configured.\n    const minPageCountPerBatch =\n      nextConfig.experimental.staticGenerationMinPagesPerWorker ?? 25\n\n    // Calculate the number of workers needed to ensure each batch has at least\n    // minPageCountPerBatch pages.\n    const numWorkers = Math.min(\n      options.numWorkers,\n      Math.ceil(exportPaths.length / minPageCountPerBatch)\n    )\n\n    // Calculate the page count per batch based on the number of workers.\n    const pageCountPerBatch = Math.ceil(exportPaths.length / numWorkers)\n\n    const batches = Array.from({ length: numWorkers }, (_, i) =>\n      exportPaths.slice(i * pageCountPerBatch, (i + 1) * pageCountPerBatch)\n    )\n\n    // Distribute remaining pages.\n    const remainingPages = exportPaths.slice(numWorkers * pageCountPerBatch)\n    remainingPages.forEach((page, index) => {\n      batches[index % batches.length].push(page)\n    })\n\n    return (\n      await Promise.all(\n        batches.map(async (batch) =>\n          worker.exportPages({\n            buildId,\n            deploymentId: nextConfig.deploymentId,\n            clientAssetToken:\n              nextConfig.experimental.immutableAssetToken ||\n              nextConfig.deploymentId,\n            exportPaths: batch,\n            parentSpanId: span.getId(),\n            pagesDataDir,\n            renderOpts,\n            options,\n            dir,\n            distDir,\n            outDir,\n            nextConfig,\n            cacheHandler: nextConfig.cacheHandler,\n            cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,\n            fetchCache: true,\n            fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,\n            renderResumeDataCachesByPage,\n          })\n        )\n      )\n    ).flat()\n  }\n\n  let initialPhaseExportPaths: ExportPathEntry[] = []\n  const finalPhaseExportPaths: ExportPathEntry[] = []\n\n  if (renderOpts.cacheComponents) {\n    // Only run instant validation once per route, even if multiple param sets from generateStaticParams exist.\n    const routesWithInstantValidation = new Set<string>()\n\n    for (const exportPath of allExportPaths) {\n      if (exportPath._allowEmptyStaticShell) {\n        finalPhaseExportPaths.push(exportPath)\n      } else {\n        initialPhaseExportPaths.push(exportPath)\n      }\n\n      const route = exportPath.page\n      if (!routesWithInstantValidation.has(route)) {\n        exportPath._runInstantValidation = true\n        routesWithInstantValidation.add(route)\n      }\n    }\n  } else {\n    initialPhaseExportPaths = allExportPaths\n  }\n\n  const totalExportPaths =\n    initialPhaseExportPaths.length + finalPhaseExportPaths.length\n  let worker: StaticWorker | null = null\n  let results: ExportPagesResult = []\n\n  if (totalExportPaths > 0) {\n    const progress = createProgress(\n      totalExportPaths,\n      options.statusMessage ??\n        `Exporting using ${options.numWorkers} worker${options.numWorkers > 1 ? 's' : ''}`\n    )\n\n    if (staticWorker) {\n      // TODO: progress shouldn't rely on \"activity\" event sent from `exportPage`.\n      staticWorker.setOnActivity(progress.run)\n      staticWorker.setOnActivityAbort(progress.clear)\n      worker = staticWorker\n    } else {\n      worker = createStaticWorker(nextConfig, {\n        debuggerPortOffset: getNextBuildDebuggerPortOffset({\n          kind: 'export-page',\n        }),\n        numberOfWorkers: options.numWorkers,\n        progress,\n      })\n    }\n\n    results = await exportPagesInBatches(worker, initialPhaseExportPaths)\n\n    if (finalPhaseExportPaths.length > 0) {\n      const renderResumeDataCachesByPage = buildRDCCacheByPage(\n        results,\n        finalPhaseExportPaths\n      )\n\n      const finalPhaseResults = await exportPagesInBatches(\n        worker,\n        finalPhaseExportPaths,\n        renderResumeDataCachesByPage\n      )\n\n      results.push(...finalPhaseResults)\n    }\n  }\n\n  const collector: ExportAppResult = {\n    byPath: new Map(),\n    byPage: new Map(),\n    ssgNotFoundPaths: new Set(),\n    turborepoAccessTraceResults: new Map(),\n  }\n\n  const failedExportAttemptsByPage: Map<string, boolean> = new Map()\n\n  for (const { result, path, page, pageKey } of results) {\n    if (!result) continue\n    if ('error' in result) {\n      failedExportAttemptsByPage.set(pageKey, true)\n      continue\n    }\n\n    if (result.turborepoAccessTraceResult) {\n      collector.turborepoAccessTraceResults?.set(\n        path,\n        TurborepoAccessTraceResult.fromSerialized(\n          result.turborepoAccessTraceResult\n        )\n      )\n    }\n\n    if (options.buildExport) {\n      // Update path info by path.\n      const info = collector.byPath.get(path) ?? {}\n      if (result.cacheControl) {\n        info.cacheControl = result.cacheControl\n      }\n      if (typeof result.metadata !== 'undefined') {\n        info.metadata = result.metadata\n      }\n\n      if (typeof result.hasEmptyStaticShell !== 'undefined') {\n        info.hasEmptyStaticShell = result.hasEmptyStaticShell\n      }\n\n      if (typeof result.hasPostponed !== 'undefined') {\n        info.hasPostponed = result.hasPostponed\n      }\n\n      if (typeof result.hasStaticRsc !== 'undefined') {\n        info.hasStaticRsc = result.hasStaticRsc\n      }\n\n      if (typeof result.fetchMetrics !== 'undefined') {\n        info.fetchMetrics = result.fetchMetrics\n      }\n\n      collector.byPath.set(path, info)\n\n      // Update not found.\n      if (result.ssgNotFound === true) {\n        collector.ssgNotFoundPaths.add(path)\n      }\n\n      // Update durations.\n      const durations = collector.byPage.get(page) ?? {\n        durationsByPath: new Map<string, number>(),\n      }\n      durations.durationsByPath.set(path, result.duration)\n      collector.byPage.set(page, durations)\n    }\n  }\n\n  // Export mode provide static outputs that are not compatible with PPR mode.\n  if (!options.buildExport && nextConfig.experimental.ppr) {\n    // TODO: add message\n    throw new Error('Invariant: PPR cannot be enabled in export mode')\n  }\n\n  // copy prerendered routes to outDir\n  if (!options.buildExport && prerenderManifest) {\n    await Promise.all(\n      Object.keys(prerenderManifest.routes).map(async (unnormalizedRoute) => {\n        // Special handling: map app /_not-found to 404.html (and 404/index.html when trailingSlash)\n        if (unnormalizedRoute === '/_not-found') {\n          const { srcRoute } = prerenderManifest!.routes[unnormalizedRoute]\n          const appPageName = mapAppRouteToPage.get(srcRoute || '')\n          const pageName = appPageName || srcRoute || unnormalizedRoute\n          const isAppPath = Boolean(appPageName)\n          const route = normalizePagePath(unnormalizedRoute)\n\n          const pagePath = getPagePath(pageName, distDir, undefined, isAppPath)\n          const distPagesDir = join(\n            pagePath,\n            pageName\n              .slice(1)\n              .split('/')\n              .map(() => '..')\n              .join('/')\n          )\n\n          const orig = join(distPagesDir, route)\n          const htmlSrc = `${orig}.html`\n\n          // write 404.html at root\n          const htmlDest404 = join(outDir, '404.html')\n          await fs.mkdir(dirname(htmlDest404), { recursive: true })\n          await fs.copyFile(htmlSrc, htmlDest404)\n\n          // When trailingSlash, also write 404/index.html\n          if (subFolders) {\n            const htmlDest404Index = join(outDir, '404', 'index.html')\n            await fs.mkdir(dirname(htmlDest404Index), { recursive: true })\n            await fs.copyFile(htmlSrc, htmlDest404Index)\n          }\n        }\n        // Skip 500.html in static export\n        if (unnormalizedRoute === '/_global-error') {\n          return\n        }\n        const { srcRoute } = prerenderManifest!.routes[unnormalizedRoute]\n        const appPageName = mapAppRouteToPage.get(srcRoute || '')\n        const pageName = appPageName || srcRoute || unnormalizedRoute\n        const isAppPath = Boolean(appPageName)\n        const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName)\n\n        // returning notFound: true from getStaticProps will not\n        // output html/json files during the build\n        if (prerenderManifest!.notFoundRoutes.includes(unnormalizedRoute)) {\n          return\n        }\n        // TODO: This rewrites /index/foo to /index/index/foo. Investigate and\n        // fix. I presume this was because normalizePagePath was designed for\n        // some other use case and then reused here for static exports without\n        // realizing the implications.\n        const route = normalizePagePath(unnormalizedRoute)\n\n        const pagePath = getPagePath(pageName, distDir, undefined, isAppPath)\n        const distPagesDir = join(\n          pagePath,\n          // strip leading / and then recurse number of nested dirs\n          // to place from base folder\n          pageName\n            .slice(1)\n            .split('/')\n            .map(() => '..')\n            .join('/')\n        )\n\n        const orig = join(distPagesDir, route)\n        const handlerSrc = `${orig}.body`\n        const handlerDest = join(outDir, route)\n\n        if (isAppRouteHandler && existsSync(handlerSrc)) {\n          await fs.mkdir(dirname(handlerDest), { recursive: true })\n          await fs.copyFile(handlerSrc, handlerDest)\n          return\n        }\n\n        const htmlDest = join(\n          outDir,\n          `${route}${\n            subFolders && route !== '/index' ? `${sep}index` : ''\n          }.html`\n        )\n        const jsonDest = isAppPath\n          ? join(\n              outDir,\n              `${route}${\n                subFolders && route !== '/index' ? `${sep}index` : ''\n              }.txt`\n            )\n          : join(pagesDataDir, `${route}.json`)\n\n        await fs.mkdir(dirname(htmlDest), { recursive: true })\n        await fs.mkdir(dirname(jsonDest), { recursive: true })\n\n        const htmlSrc = `${orig}.html`\n        const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : '.json'}`\n\n        await fs.copyFile(htmlSrc, htmlDest)\n        await fs.copyFile(jsonSrc, jsonDest)\n\n        const segmentsDir = `${orig}${RSC_SEGMENTS_DIR_SUFFIX}`\n\n        if (isAppPath && existsSync(segmentsDir)) {\n          // Output a data file for each of this page's segments\n          //\n          // These files are requested by the client router's internal\n          // prefetcher, not the user directly. So we don't need to account for\n          // things like trailing slash handling.\n          //\n          // To keep the protocol simple, we can use the non-normalized route\n          // path instead of the normalized one (which, among other things,\n          // rewrites `/` to `/index`).\n          const segmentsDirDest = join(outDir, unnormalizedRoute)\n          const segmentPaths = await collectSegmentPaths(segmentsDir)\n          await Promise.all(\n            segmentPaths.map(async (segmentFileSrc) => {\n              const segmentPath =\n                '/' + segmentFileSrc.slice(0, -RSC_SEGMENT_SUFFIX.length)\n              const segmentFilename =\n                convertSegmentPathToStaticExportFilename(segmentPath)\n              const segmentFileDest = join(segmentsDirDest, segmentFilename)\n              await fs.mkdir(dirname(segmentFileDest), { recursive: true })\n              await fs.copyFile(\n                join(segmentsDir, segmentFileSrc),\n                segmentFileDest\n              )\n            })\n          )\n        }\n      })\n    )\n  }\n\n  if (failedExportAttemptsByPage.size > 0) {\n    const failedPages = Array.from(failedExportAttemptsByPage.keys())\n    throw new ExportError(\n      `Export encountered errors on ${failedPages.length} ${failedPages.length === 1 ? 'path' : 'paths'}:\\n\\t${failedPages\n        .sort()\n        .join('\\n\\t')}`\n    )\n  }\n\n  await fs.writeFile(\n    join(distDir, EXPORT_DETAIL),\n    formatManifest({\n      version: 1,\n      outDirectory: outDir,\n      success: true,\n    }),\n    'utf8'\n  )\n\n  if (telemetry) {\n    await telemetry.flush()\n  }\n\n  // Clean up activity listeners for progress.\n  if (staticWorker) {\n    staticWorker.setOnActivity(undefined)\n    staticWorker.setOnActivityAbort(undefined)\n  }\n\n  if (!staticWorker && worker) {\n    await worker.end()\n  }\n\n  return collector\n}\n\nasync function collectSegmentPaths(segmentsDirectory: string) {\n  const results: Array<string> = []\n  await collectSegmentPathsImpl(segmentsDirectory, segmentsDirectory, results)\n  return results\n}\n\nasync function collectSegmentPathsImpl(\n  segmentsDirectory: string,\n  directory: string,\n  results: Array<string>\n) {\n  const segmentFiles = await fs.readdir(directory, {\n    withFileTypes: true,\n  })\n  await Promise.all(\n    segmentFiles.map(async (segmentFile) => {\n      if (segmentFile.isDirectory()) {\n        await collectSegmentPathsImpl(\n          segmentsDirectory,\n          join(directory, segmentFile.name),\n          results\n        )\n        return\n      }\n      if (!segmentFile.name.endsWith(RSC_SEGMENT_SUFFIX)) {\n        return\n      }\n      results.push(\n        relative(segmentsDirectory, join(directory, segmentFile.name))\n      )\n    })\n  )\n}\n\nexport default async function exportApp(\n  dir: string,\n  options: ExportAppOptions,\n  span: Span,\n  staticWorker?: StaticWorker\n): Promise<ExportAppResult | null> {\n  const nextExportSpan = span.traceChild('next-export')\n\n  return nextExportSpan.traceAsyncFn(async () => {\n    return await exportAppImpl(dir, options, nextExportSpan, staticWorker)\n  })\n}\n"],"names":["createStaticWorker","bold","yellow","findUp","existsSync","promises","fs","dirname","join","resolve","sep","relative","Log","RSC_SEGMENT_SUFFIX","RSC_SEGMENTS_DIR_SUFFIX","RSC_SUFFIX","SSG_FALLBACK_EXPORT_ERROR","recursiveCopy","BUILD_ID_FILE","CLIENT_PUBLIC_FILES_PATH","CLIENT_STATIC_FILES_PATH","EXPORT_DETAIL","EXPORT_MARKER","NEXT_FONT_MANIFEST","MIDDLEWARE_MANIFEST","PAGES_MANIFEST","PHASE_EXPORT","PRERENDER_MANIFEST","SERVER_DIRECTORY","SERVER_REFERENCE_MANIFEST","APP_PATH_ROUTES_MANIFEST","ROUTES_MANIFEST","FUNCTIONS_CONFIG_MANIFEST","loadConfig","parseMaxPostponedStateSize","eventCliSession","hasNextSupport","Telemetry","normalizePagePath","denormalizePagePath","loadEnvConfig","isAPIRoute","getPagePath","isAppRouteRoute","isAppPageRoute","isError","formatManifest","TurborepoAccessTraceResult","createProgress","isInterceptionRouteRewrite","extractInfoFromServerReferenceId","convertSegmentPathToStaticExportFilename","getNextBuildDebuggerPortOffset","getParams","isDynamicRoute","normalizeAppPath","ExportError","Error","code","buildRDCCacheByPage","results","finalPhaseExportPaths","renderResumeDataCachesByPage","seedCandidatesByPage","Map","page","path","result","renderResumeDataCache","candidates","get","push","set","undefined","getKnownParamsKey","normalizedPage","fallbackParamNames","params","entries","Object","filter","key","has","sort","a","b","JSON","stringify","exportPath","_fallbackRouteParams","pageKey","Set","map","param","paramName","targetKey","length","selected","candidate","candidateKey","exportAppImpl","dir","options","span","staticWorker","traceChild","traceFn","enabledDirectories","nextConfig","traceAsyncFn","debugPrerender","distDir","telemetry","buildExport","record","webpackVersion","cliCommand","isSrcDir","hasNowJson","cwd","isCustomServer","turboFlag","pagesDir","appDir","subFolders","trailingSlash","silent","info","buildIdFile","customRoutes","config","warn","buildId","readFile","pagesManifest","pages","require","prerenderManifest","appRoutePathManifest","err","excludedPrerenderRoutes","keys","defaultPathMap","hasApiRoutes","dynamicRoutes","add","mapAppRouteToPage","pageName","routePath","routes","_isAppDir","outDir","outdir","rm","recursive","force","mkdir","writeFile","version","outDirectory","success","exportPathMap","defaultMap","i18n","images","loader","unoptimized","isNextImageImported","then","text","parse","catch","serverActionsManifest","app","output","routesManifest","rewrites","beforeFiles","hasInterceptionRouteRewrite","some","actionIds","node","edge","actionId","type","renderOpts","previewProps","preview","isBuildTimePrerendering","assetPrefix","replace","basePath","cacheComponents","locales","locale","defaultLocale","domainLocales","domains","disableOptimizedLoading","experimental","supportsDynamicResponse","crossOrigin","optimizeCss","nextConfigOutput","nextScriptWorkers","largePageDataBytes","serverActions","serverComponents","cacheLifeProfiles","cacheLife","nextFontManifest","htmlLimitedBots","source","clientTraceMetadata","expireTime","staleTimes","clientParamParsingOrigins","dynamicOnHover","optimisticRouting","inlineCss","prefetchInlining","authInterrupts","cachedNavigations","maxPostponedStateSizeBytes","maxPostponedStateSize","reactMaxHeadersLength","globalThis","__NEXT_DATA__","nextExport","exportMap","dev","appDirOnly","allExportPaths","seenExportPaths","fallbackEnabledPages","entry","normalizedPath","prerenderInfo","fallback","size","hasMiddleware","functionsConfigManifest","middlewareManifest","middleware","Boolean","functions","pagesDataDir","publicDir","exportPagesInBatches","worker","exportPaths","minPageCountPerBatch","staticGenerationMinPagesPerWorker","numWorkers","Math","min","ceil","pageCountPerBatch","batches","Array","from","_","i","slice","remainingPages","forEach","index","Promise","all","batch","exportPages","deploymentId","clientAssetToken","immutableAssetToken","parentSpanId","getId","cacheHandler","cacheMaxMemorySize","fetchCache","fetchCacheKeyPrefix","flat","initialPhaseExportPaths","routesWithInstantValidation","_allowEmptyStaticShell","route","_runInstantValidation","totalExportPaths","progress","statusMessage","setOnActivity","run","setOnActivityAbort","clear","debuggerPortOffset","kind","numberOfWorkers","finalPhaseResults","collector","byPath","byPage","ssgNotFoundPaths","turborepoAccessTraceResults","failedExportAttemptsByPage","turborepoAccessTraceResult","fromSerialized","cacheControl","metadata","hasEmptyStaticShell","hasPostponed","hasStaticRsc","fetchMetrics","ssgNotFound","durations","durationsByPath","duration","ppr","unnormalizedRoute","srcRoute","appPageName","isAppPath","pagePath","distPagesDir","split","orig","htmlSrc","htmlDest404","copyFile","htmlDest404Index","isAppRouteHandler","notFoundRoutes","includes","handlerSrc","handlerDest","htmlDest","jsonDest","jsonSrc","segmentsDir","segmentsDirDest","segmentPaths","collectSegmentPaths","segmentFileSrc","segmentPath","segmentFilename","segmentFileDest","failedPages","flush","end","segmentsDirectory","collectSegmentPathsImpl","directory","segmentFiles","readdir","withFileTypes","segmentFile","isDirectory","name","endsWith","exportApp","nextExportSpan"],"mappings":"AAOA,SACEA,kBAAkB,QAGb,WAAU;AAGjB,SAASC,IAAI,EAAEC,MAAM,QAAQ,oBAAmB;AAChD,OAAOC,YAAY,6BAA4B;AAC/C,SAASC,UAAU,EAAEC,YAAYC,EAAE,QAAQ,KAAI;AAE/C,OAAO,yBAAwB;AAE/B,SAASC,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAEC,GAAG,EAAEC,QAAQ,QAAQ,OAAM;AAC5D,YAAYC,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