next
Version:
The React Framework
903 lines (902 loc) • 140 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createStaticWorker: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createStaticWorker: function() {
return createStaticWorker;
},
default: function() {
return build;
}
});
require("../lib/setup-exception-listeners");
const _env = require("@next/env");
const _picocolors = require("../lib/picocolors");
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
const _picomatch = require("next/dist/compiled/picomatch");
const _fs = require("fs");
const _os = /*#__PURE__*/ _interop_require_default(require("os"));
const _worker = require("../lib/worker");
const _configshared = require("../server/config-shared");
const _devalue = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/devalue"));
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _indexcjs = require("next/dist/compiled/nanoid/index.cjs");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _constants = require("../lib/constants");
const _fileexists = require("../lib/file-exists");
const _findpagesdir = require("../lib/find-pages-dir");
const _loadcustomroutes = /*#__PURE__*/ _interop_require_wildcard(require("../lib/load-custom-routes"));
const _nonnullable = require("../lib/non-nullable");
const _recursivedelete = require("../lib/recursive-delete");
const _verifypartytownsetup = require("../lib/verify-partytown-setup");
const _constants1 = require("../shared/lib/constants");
const _utils = require("../shared/lib/router/utils");
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
const _require = require("../server/require");
const _ciinfo = /*#__PURE__*/ _interop_require_wildcard(require("../server/ci-info"));
const _turborepoaccesstrace = require("./turborepo-access-trace");
const _events = require("../telemetry/events");
const _storage = require("../telemetry/storage");
const _getpagestaticinfo = require("./analysis/get-page-static-info");
const _entries = require("./entries");
const _pagetypes = require("../lib/page-types");
const _generatebuildid = require("./generate-build-id");
const _iswriteable = require("./is-writeable");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("./output/log"));
const _spinner = /*#__PURE__*/ _interop_require_default(require("./spinner"));
const _trace = require("../trace");
const _utils1 = require("./utils");
const _writebuildid = require("./write-build-id");
const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path");
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
const _isedgeruntime = require("../lib/is-edge-runtime");
const _recursivecopy = require("../lib/recursive-copy");
const _recursivereaddir = require("../lib/recursive-readdir");
const _swc = require("./swc");
const _routeregex = require("../shared/lib/router/utils/route-regex");
const _getfilesindir = require("../lib/get-files-in-dir");
const _swcplugins = require("../telemetry/events/swc-plugins");
const _apppaths = require("../shared/lib/router/utils/app-paths");
const _approuterheaders = require("../client/components/app-router-headers");
const _webpackbuild = require("./webpack-build");
const _buildcontext = require("./build-context");
const _normalizepathsep = require("../shared/lib/page-path/normalize-path-sep");
const _isapprouteroute = require("../lib/is-app-route-route");
const _createclientrouterfilter = require("../lib/create-client-router-filter");
const _findpagefile = require("../server/lib/find-page-file");
const _typecheck = require("./type-check");
const _generateinterceptionroutesrewrites = require("../lib/generate-interception-routes-rewrites");
const _builddataroute = require("../server/lib/router-utils/build-data-route");
const _collectbuildtraces = require("./collect-build-traces");
const _formatmanifest = require("./manifests/formatter/format-manifest");
const _builddiagnostics = require("../diagnostics/build-diagnostics");
const _appinfolog = require("../server/lib/app-info-log");
const _utils2 = require("../export/utils");
const _buildcustomroute = require("../lib/build-custom-route");
const _trace1 = require("../lib/memory/trace");
const _encryptionutilsserver = require("../server/app-render/encryption-utils-server");
const _uploadtrace = /*#__PURE__*/ _interop_require_default(require("../trace/upload-trace"));
const _ppr = require("../server/lib/experimental/ppr");
const _fallback = require("../lib/fallback");
const _renderingmode = require("./rendering-mode");
const _fallbackparams = require("../server/request/fallback-params");
const _utils3 = require("../server/lib/utils");
const _invarianterror = require("../shared/lib/invariant-error");
const _isbot = require("../shared/lib/router/utils/is-bot");
const _buildprefetchsegmentdataroute = require("../server/lib/router-utils/build-prefetch-segment-data-route");
const _turbopackbuild = require("./turbopack-build");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* The headers that are allowed to be used when revalidating routes. Currently
* this includes both headers used by the pages and app routers.
*/ const ALLOWED_HEADERS = [
'host',
_constants.MATCHED_PATH_HEADER,
_constants.PRERENDER_REVALIDATE_HEADER,
_constants.PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER,
_constants.NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER
];
function pageToRoute(page) {
const routeRegex = (0, _routeregex.getNamedRouteRegex)(page, {
prefixRouteKeys: true
});
return {
page,
regex: (0, _loadcustomroutes.normalizeRouteRegex)(routeRegex.re.source),
routeKeys: routeRegex.routeKeys,
namedRegex: routeRegex.namedRegex
};
}
function getCacheDir(distDir) {
const cacheDir = _path.default.join(distDir, 'cache');
if (_ciinfo.isCI && !_ciinfo.hasNextSupport) {
const hasCache = (0, _fs.existsSync)(cacheDir);
if (!hasCache) {
// Intentionally not piping to stderr which is what `Log.warn` does in case people fail in CI when
// stderr is detected.
console.log(`${_log.prefixes.warn} No build cache found. Please configure build caching for faster rebuilds. Read more: https://nextjs.org/docs/messages/no-cache`);
}
}
return cacheDir;
}
async function writeFileUtf8(filePath, content) {
await _fs.promises.writeFile(filePath, content, 'utf-8');
}
function readFileUtf8(filePath) {
return _fs.promises.readFile(filePath, 'utf8');
}
async function writeManifest(filePath, manifest) {
await writeFileUtf8(filePath, (0, _formatmanifest.formatManifest)(manifest));
}
async function readManifest(filePath) {
return JSON.parse(await readFileUtf8(filePath));
}
async function writePrerenderManifest(distDir, manifest) {
await writeManifest(_path.default.join(distDir, _constants1.PRERENDER_MANIFEST), manifest);
}
async function writeClientSsgManifest(prerenderManifest, { buildId, distDir, locales }) {
const ssgPages = new Set([
...Object.entries(prerenderManifest.routes)// Filter out dynamic routes
.filter(([, { srcRoute }])=>srcRoute == null).map(([route])=>(0, _normalizelocalepath.normalizeLocalePath)(route, locales).pathname),
...Object.keys(prerenderManifest.dynamicRoutes)
].sort());
const clientSsgManifestContent = `self.__SSG_MANIFEST=${(0, _devalue.default)(ssgPages)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`;
await writeFileUtf8(_path.default.join(distDir, _constants1.CLIENT_STATIC_FILES_PATH, buildId, '_ssgManifest.js'), clientSsgManifestContent);
}
async function writeFunctionsConfigManifest(distDir, manifest) {
await writeManifest(_path.default.join(distDir, _constants1.SERVER_DIRECTORY, _constants1.FUNCTIONS_CONFIG_MANIFEST), manifest);
}
async function writeRequiredServerFilesManifest(distDir, requiredServerFiles) {
await writeManifest(_path.default.join(distDir, _constants1.SERVER_FILES_MANIFEST), requiredServerFiles);
}
async function writeImagesManifest(distDir, config) {
var _config_images, _config_images1;
const images = {
...config.images
};
const { deviceSizes, imageSizes } = images;
images.sizes = [
...deviceSizes,
...imageSizes
];
// By default, remotePatterns will allow no remote images ([])
images.remotePatterns = ((config == null ? void 0 : (_config_images = config.images) == null ? void 0 : _config_images.remotePatterns) || []).map((p)=>({
// Modifying the manifest should also modify matchRemotePattern()
protocol: p.protocol,
hostname: (0, _picomatch.makeRe)(p.hostname).source,
port: p.port,
pathname: (0, _picomatch.makeRe)(p.pathname ?? '**', {
dot: true
}).source,
search: p.search
}));
// By default, localPatterns will allow all local images (undefined)
if (config == null ? void 0 : (_config_images1 = config.images) == null ? void 0 : _config_images1.localPatterns) {
images.localPatterns = config.images.localPatterns.map((p)=>({
// Modifying the manifest should also modify matchLocalPattern()
pathname: (0, _picomatch.makeRe)(p.pathname ?? '**', {
dot: true
}).source,
search: p.search
}));
}
await writeManifest(_path.default.join(distDir, _constants1.IMAGES_MANIFEST), {
version: 1,
images
});
}
const STANDALONE_DIRECTORY = 'standalone';
async function writeStandaloneDirectory(nextBuildSpan, distDir, pageKeys, denormalizedAppPages, outputFileTracingRoot, requiredServerFiles, middlewareManifest, hasNodeMiddleware, hasInstrumentationHook, staticPages, loadedEnvFiles, appDir) {
await nextBuildSpan.traceChild('write-standalone-directory').traceAsyncFn(async ()=>{
await (0, _utils1.copyTracedFiles)(// requiredServerFiles.appDir Refers to the application directory, not App Router.
requiredServerFiles.appDir, distDir, pageKeys.pages, denormalizedAppPages, outputFileTracingRoot, requiredServerFiles.config, middlewareManifest, hasNodeMiddleware, hasInstrumentationHook, staticPages);
for (const file of [
...requiredServerFiles.files,
_path.default.join(requiredServerFiles.config.distDir, _constants1.SERVER_FILES_MANIFEST),
...loadedEnvFiles.reduce((acc, envFile)=>{
if ([
'.env',
'.env.production'
].includes(envFile.path)) {
acc.push(envFile.path);
}
return acc;
}, [])
]){
// requiredServerFiles.appDir Refers to the application directory, not App Router.
const filePath = _path.default.join(requiredServerFiles.appDir, file);
const outputPath = _path.default.join(distDir, STANDALONE_DIRECTORY, _path.default.relative(outputFileTracingRoot, filePath));
await _fs.promises.mkdir(_path.default.dirname(outputPath), {
recursive: true
});
await _fs.promises.copyFile(filePath, outputPath);
}
if (hasNodeMiddleware) {
const middlewareOutput = _path.default.join(distDir, STANDALONE_DIRECTORY, _path.default.relative(outputFileTracingRoot, distDir), _constants1.SERVER_DIRECTORY, 'middleware.js');
await _fs.promises.mkdir(_path.default.dirname(middlewareOutput), {
recursive: true
});
await _fs.promises.copyFile(_path.default.join(distDir, _constants1.SERVER_DIRECTORY, 'middleware.js'), middlewareOutput);
}
await (0, _recursivecopy.recursiveCopy)(_path.default.join(distDir, _constants1.SERVER_DIRECTORY, 'pages'), _path.default.join(distDir, STANDALONE_DIRECTORY, _path.default.relative(outputFileTracingRoot, distDir), _constants1.SERVER_DIRECTORY, 'pages'), {
overwrite: true
});
if (appDir) {
const originalServerApp = _path.default.join(distDir, _constants1.SERVER_DIRECTORY, 'app');
if ((0, _fs.existsSync)(originalServerApp)) {
await (0, _recursivecopy.recursiveCopy)(originalServerApp, _path.default.join(distDir, STANDALONE_DIRECTORY, _path.default.relative(outputFileTracingRoot, distDir), _constants1.SERVER_DIRECTORY, 'app'), {
overwrite: true
});
}
}
});
}
function getNumberOfWorkers(config) {
if (config.experimental.cpus && config.experimental.cpus !== _configshared.defaultConfig.experimental.cpus) {
return config.experimental.cpus;
}
if (config.experimental.memoryBasedWorkersCount) {
return Math.max(Math.min(config.experimental.cpus || 1, Math.floor(_os.default.freemem() / 1e9)), // enforce a minimum of 4 workers
4);
}
if (config.experimental.cpus) {
return config.experimental.cpus;
}
// Fall back to 4 workers if a count is not specified
return 4;
}
const staticWorkerPath = require.resolve('./worker');
const staticWorkerExposedMethods = [
'hasCustomGetInitialProps',
'isPageStatic',
'getDefinedNamedExports',
'exportPages'
];
function createStaticWorker(config, progress) {
// Get the node options without inspect and also remove the
// --max-old-space-size flag as it can cause memory issues.
const nodeOptions = (0, _utils3.getParsedNodeOptionsWithoutInspect)();
delete nodeOptions['max-old-space-size'];
delete nodeOptions['max_old_space_size'];
return new _worker.Worker(staticWorkerPath, {
logger: _log,
numWorkers: getNumberOfWorkers(config),
onActivity: ()=>{
progress == null ? void 0 : progress.run();
},
onActivityAbort: ()=>{
progress == null ? void 0 : progress.clear();
},
forkOptions: {
env: {
...process.env,
NODE_OPTIONS: (0, _utils3.formatNodeOptions)(nodeOptions)
}
},
enableWorkerThreads: config.experimental.workerThreads,
exposedMethods: staticWorkerExposedMethods
});
}
async function writeFullyStaticExport(config, dir, enabledDirectories, configOutDir, nextBuildSpan) {
const exportApp = require('../export').default;
const pagesWorker = createStaticWorker(config);
const appWorker = createStaticWorker(config);
await exportApp(dir, {
buildExport: false,
nextConfig: config,
enabledDirectories,
silent: true,
outdir: _path.default.join(dir, configOutDir),
numWorkers: getNumberOfWorkers(config)
}, nextBuildSpan);
pagesWorker.end();
appWorker.end();
}
async function getBuildId(isGenerateMode, distDir, nextBuildSpan, config) {
if (isGenerateMode) {
return await _fs.promises.readFile(_path.default.join(distDir, 'BUILD_ID'), 'utf8');
}
return await nextBuildSpan.traceChild('generate-buildid').traceAsyncFn(()=>(0, _generatebuildid.generateBuildId)(config.generateBuildId, _indexcjs.nanoid));
}
async function build(dir, reactProductionProfiling = false, debugOutput = false, runLint = true, noMangling = false, appDirOnly = false, turboNextBuild = false, experimentalBuildMode, traceUploadUrl) {
const isCompileMode = experimentalBuildMode === 'compile';
const isGenerateMode = experimentalBuildMode === 'generate';
let loadedConfig;
try {
const nextBuildSpan = (0, _trace.trace)('next-build', undefined, {
buildMode: experimentalBuildMode,
isTurboBuild: String(turboNextBuild),
version: "15.2.4"
});
_buildcontext.NextBuildContext.nextBuildSpan = nextBuildSpan;
_buildcontext.NextBuildContext.dir = dir;
_buildcontext.NextBuildContext.appDirOnly = appDirOnly;
_buildcontext.NextBuildContext.reactProductionProfiling = reactProductionProfiling;
_buildcontext.NextBuildContext.noMangling = noMangling;
await nextBuildSpan.traceAsyncFn(async ()=>{
var _mappedPages_404;
// attempt to load global env values so they are available in next.config.js
const { loadedEnvFiles } = nextBuildSpan.traceChild('load-dotenv').traceFn(()=>(0, _env.loadEnvConfig)(dir, false, _log));
_buildcontext.NextBuildContext.loadedEnvFiles = loadedEnvFiles;
const turborepoAccessTraceResult = new _turborepoaccesstrace.TurborepoAccessTraceResult();
const config = await nextBuildSpan.traceChild('load-next-config').traceAsyncFn(()=>(0, _turborepoaccesstrace.turborepoTraceAccess)(()=>(0, _config.default)(_constants1.PHASE_PRODUCTION_BUILD, dir, {
// Log for next.config loading process
silent: false,
reactProductionProfiling
}), turborepoAccessTraceResult));
loadedConfig = config;
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || '';
_buildcontext.NextBuildContext.config = config;
let configOutDir = 'out';
if ((0, _utils2.hasCustomExportOutput)(config)) {
configOutDir = config.distDir;
config.distDir = '.next';
}
const distDir = _path.default.join(dir, config.distDir);
_buildcontext.NextBuildContext.distDir = distDir;
(0, _trace.setGlobal)('phase', _constants1.PHASE_PRODUCTION_BUILD);
(0, _trace.setGlobal)('distDir', distDir);
const buildId = await getBuildId(isGenerateMode, distDir, nextBuildSpan, config);
_buildcontext.NextBuildContext.buildId = buildId;
const customRoutes = await nextBuildSpan.traceChild('load-custom-routes').traceAsyncFn(()=>(0, _loadcustomroutes.default)(config));
const { headers, rewrites, redirects } = customRoutes;
const combinedRewrites = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
...rewrites.fallback
];
const hasRewrites = combinedRewrites.length > 0;
_buildcontext.NextBuildContext.hasRewrites = hasRewrites;
_buildcontext.NextBuildContext.originalRewrites = config._originalRewrites;
_buildcontext.NextBuildContext.originalRedirects = config._originalRedirects;
const cacheDir = getCacheDir(distDir);
const telemetry = new _storage.Telemetry({
distDir
});
(0, _trace.setGlobal)('telemetry', telemetry);
const publicDir = _path.default.join(dir, 'public');
const { pagesDir, appDir } = (0, _findpagesdir.findPagesDir)(dir);
_buildcontext.NextBuildContext.pagesDir = pagesDir;
_buildcontext.NextBuildContext.appDir = appDir;
const enabledDirectories = {
app: typeof appDir === 'string',
pages: typeof pagesDir === 'string'
};
// Generate a random encryption key for this build.
// This key is used to encrypt cross boundary values and can be used to generate hashes.
const encryptionKey = await (0, _encryptionutilsserver.generateEncryptionKeyBase64)({
isBuild: true,
distDir
});
_buildcontext.NextBuildContext.encryptionKey = encryptionKey;
const isSrcDir = _path.default.relative(dir, pagesDir || appDir || '').startsWith('src');
const hasPublicDir = (0, _fs.existsSync)(publicDir);
telemetry.record((0, _events.eventCliSession)(dir, config, {
webpackVersion: 5,
cliCommand: 'build',
isSrcDir,
hasNowJson: !!await (0, _findup.default)('now.json', {
cwd: dir
}),
isCustomServer: null,
turboFlag: false,
pagesDir: !!pagesDir,
appDir: !!appDir
}));
(0, _events.eventNextPlugins)(_path.default.resolve(dir)).then((events)=>telemetry.record(events));
(0, _swcplugins.eventSwcPlugins)(_path.default.resolve(dir), config).then((events)=>telemetry.record(events));
// Always log next version first then start rest jobs
const { envInfo, experimentalFeatures } = await (0, _appinfolog.getStartServerInfo)(dir, false);
(0, _appinfolog.logStartInfo)({
networkUrl: null,
appUrl: null,
envInfo,
experimentalFeatures
});
const ignoreESLint = Boolean(config.eslint.ignoreDuringBuilds);
const shouldLint = !ignoreESLint && runLint;
const typeCheckingOptions = {
dir,
appDir,
pagesDir,
runLint,
shouldLint,
ignoreESLint,
telemetry,
nextBuildSpan,
config,
cacheDir
};
const distDirCreated = await nextBuildSpan.traceChild('create-dist-dir').traceAsyncFn(async ()=>{
try {
await _fs.promises.mkdir(distDir, {
recursive: true
});
return true;
} catch (err) {
if ((0, _iserror.default)(err) && err.code === 'EPERM') {
return false;
}
throw err;
}
});
if (!distDirCreated || !await (0, _iswriteable.isWriteable)(distDir)) {
throw Object.defineProperty(new Error('> Build directory is not writeable. https://nextjs.org/docs/messages/build-dir-not-writeable'), "__NEXT_ERROR_CODE", {
value: "E202",
enumerable: false,
configurable: true
});
}
if (config.cleanDistDir && !isGenerateMode) {
await (0, _recursivedelete.recursiveDelete)(distDir, /^cache/);
}
// For app directory, we run type checking after build. That's because
// we dynamically generate types for each layout and page in the app
// directory.
if (!appDir && !isCompileMode) await (0, _typecheck.startTypeChecking)(typeCheckingOptions);
if (appDir && 'exportPathMap' in config) {
_log.error('The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.');
await telemetry.flush();
process.exit(1);
}
const buildLintEvent = {
featureName: 'build-lint',
invocationCount: shouldLint ? 1 : 0
};
telemetry.record({
eventName: _events.EVENT_BUILD_FEATURE_USAGE,
payload: buildLintEvent
});
const validFileMatcher = (0, _findpagefile.createValidFileMatcher)(config.pageExtensions, appDir);
const providedPagePaths = JSON.parse(process.env.NEXT_PRIVATE_PAGE_PATHS || '[]');
let pagesPaths = Boolean(process.env.NEXT_PRIVATE_PAGE_PATHS) ? providedPagePaths : !appDirOnly && pagesDir ? await nextBuildSpan.traceChild('collect-pages').traceAsyncFn(()=>(0, _recursivereaddir.recursiveReadDir)(pagesDir, {
pathnameFilter: validFileMatcher.isPageFile
})) : [];
const middlewareDetectionRegExp = new RegExp(`^${_constants.MIDDLEWARE_FILENAME}\\.(?:${config.pageExtensions.join('|')})$`);
const instrumentationHookDetectionRegExp = new RegExp(`^${_constants.INSTRUMENTATION_HOOK_FILENAME}\\.(?:${config.pageExtensions.join('|')})$`);
const rootDir = _path.default.join(pagesDir || appDir, '..');
const includes = [
middlewareDetectionRegExp,
instrumentationHookDetectionRegExp
];
const rootPaths = Array.from(await (0, _getfilesindir.getFilesInDir)(rootDir)).filter((file)=>includes.some((include)=>include.test(file))).sort((0, _entries.sortByPageExts)(config.pageExtensions)).map((file)=>_path.default.join(rootDir, file).replace(dir, ''));
const hasInstrumentationHook = rootPaths.some((p)=>p.includes(_constants.INSTRUMENTATION_HOOK_FILENAME));
const hasMiddlewareFile = rootPaths.some((p)=>p.includes(_constants.MIDDLEWARE_FILENAME));
_buildcontext.NextBuildContext.hasInstrumentationHook = hasInstrumentationHook;
const previewProps = {
previewModeId: _crypto.default.randomBytes(16).toString('hex'),
previewModeSigningKey: _crypto.default.randomBytes(32).toString('hex'),
previewModeEncryptionKey: _crypto.default.randomBytes(32).toString('hex')
};
_buildcontext.NextBuildContext.previewProps = previewProps;
const mappedPages = await nextBuildSpan.traceChild('create-pages-mapping').traceAsyncFn(()=>(0, _entries.createPagesMapping)({
isDev: false,
pageExtensions: config.pageExtensions,
pagesType: _pagetypes.PAGE_TYPES.PAGES,
pagePaths: pagesPaths,
pagesDir,
appDir
}));
_buildcontext.NextBuildContext.mappedPages = mappedPages;
let mappedAppPages;
let denormalizedAppPages;
if (appDir) {
const providedAppPaths = JSON.parse(process.env.NEXT_PRIVATE_APP_PATHS || '[]');
let appPaths = Boolean(process.env.NEXT_PRIVATE_APP_PATHS) ? providedAppPaths : await nextBuildSpan.traceChild('collect-app-paths').traceAsyncFn(()=>(0, _recursivereaddir.recursiveReadDir)(appDir, {
pathnameFilter: (absolutePath)=>validFileMatcher.isAppRouterPage(absolutePath) || // For now we only collect the root /not-found page in the app
// directory as the 404 fallback
validFileMatcher.isRootNotFound(absolutePath),
ignorePartFilter: (part)=>part.startsWith('_')
}));
mappedAppPages = await nextBuildSpan.traceChild('create-app-mapping').traceAsyncFn(()=>(0, _entries.createPagesMapping)({
pagePaths: appPaths,
isDev: false,
pagesType: _pagetypes.PAGE_TYPES.APP,
pageExtensions: config.pageExtensions,
pagesDir,
appDir
}));
_buildcontext.NextBuildContext.mappedAppPages = mappedAppPages;
}
const mappedRootPaths = await (0, _entries.createPagesMapping)({
isDev: false,
pageExtensions: config.pageExtensions,
pagePaths: rootPaths,
pagesType: _pagetypes.PAGE_TYPES.ROOT,
pagesDir: pagesDir,
appDir
});
_buildcontext.NextBuildContext.mappedRootPaths = mappedRootPaths;
const pagesPageKeys = Object.keys(mappedPages);
const conflictingAppPagePaths = [];
const appPageKeys = new Set();
if (mappedAppPages) {
denormalizedAppPages = Object.keys(mappedAppPages);
for (const appKey of denormalizedAppPages){
const normalizedAppPageKey = (0, _apppaths.normalizeAppPath)(appKey);
const pagePath = mappedPages[normalizedAppPageKey];
if (pagePath) {
const appPath = mappedAppPages[appKey];
conflictingAppPagePaths.push([
pagePath.replace(/^private-next-pages/, 'pages'),
appPath.replace(/^private-next-app-dir/, 'app')
]);
}
appPageKeys.add(normalizedAppPageKey);
}
}
const appPaths = Array.from(appPageKeys);
// Interception routes are modelled as beforeFiles rewrites
rewrites.beforeFiles.push(...(0, _generateinterceptionroutesrewrites.generateInterceptionRoutesRewrites)(appPaths, config.basePath));
_buildcontext.NextBuildContext.rewrites = rewrites;
const totalAppPagesCount = appPaths.length;
const pageKeys = {
pages: pagesPageKeys,
app: appPaths.length > 0 ? appPaths : undefined
};
// Turbopack already handles conflicting app and page routes.
if (!turboNextBuild) {
const numConflictingAppPaths = conflictingAppPagePaths.length;
if (mappedAppPages && numConflictingAppPaths > 0) {
_log.error(`Conflicting app and page file${numConflictingAppPaths === 1 ? ' was' : 's were'} found, please remove the conflicting files to continue:`);
for (const [pagePath, appPath] of conflictingAppPagePaths){
_log.error(` "${pagePath}" - "${appPath}"`);
}
await telemetry.flush();
process.exit(1);
}
}
const conflictingPublicFiles = [];
const hasPages404 = (_mappedPages_404 = mappedPages['/404']) == null ? void 0 : _mappedPages_404.startsWith(_constants.PAGES_DIR_ALIAS);
const hasApp404 = !!(mappedAppPages == null ? void 0 : mappedAppPages[_constants1.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY]);
const hasCustomErrorPage = mappedPages['/_error'].startsWith(_constants.PAGES_DIR_ALIAS);
if (hasPublicDir) {
const hasPublicUnderScoreNextDir = (0, _fs.existsSync)(_path.default.join(publicDir, '_next'));
if (hasPublicUnderScoreNextDir) {
throw Object.defineProperty(new Error(_constants.PUBLIC_DIR_MIDDLEWARE_CONFLICT), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
}
await nextBuildSpan.traceChild('public-dir-conflict-check').traceAsyncFn(async ()=>{
// Check if pages conflict with files in `public`
// Only a page of public file can be served, not both.
for(const page in mappedPages){
const hasPublicPageFile = await (0, _fileexists.fileExists)(_path.default.join(publicDir, page === '/' ? '/index' : page), _fileexists.FileType.File);
if (hasPublicPageFile) {
conflictingPublicFiles.push(page);
}
}
const numConflicting = conflictingPublicFiles.length;
if (numConflicting) {
throw Object.defineProperty(new Error(`Conflicting public and page file${numConflicting === 1 ? ' was' : 's were'} found. https://nextjs.org/docs/messages/conflicting-public-file-page\n${conflictingPublicFiles.join('\n')}`), "__NEXT_ERROR_CODE", {
value: "E270",
enumerable: false,
configurable: true
});
}
});
const nestedReservedPages = pageKeys.pages.filter((page)=>{
return page.match(/\/(_app|_document|_error)$/) && _path.default.dirname(page) !== '/';
});
if (nestedReservedPages.length) {
_log.warn(`The following reserved Next.js pages were detected not directly under the pages directory:\n` + nestedReservedPages.join('\n') + `\nSee more info here: https://nextjs.org/docs/messages/nested-reserved-page\n`);
}
const restrictedRedirectPaths = [
'/_next'
].map((p)=>config.basePath ? `${config.basePath}${p}` : p);
const isAppDynamicIOEnabled = Boolean(config.experimental.dynamicIO);
const isAuthInterruptsEnabled = Boolean(config.experimental.authInterrupts);
const isAppPPREnabled = (0, _ppr.checkIsAppPPREnabled)(config.experimental.ppr);
const routesManifestPath = _path.default.join(distDir, _constants1.ROUTES_MANIFEST);
const routesManifest = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(()=>{
const sortedRoutes = (0, _utils.getSortedRoutes)([
...pageKeys.pages,
...pageKeys.app ?? []
]);
const dynamicRoutes = [];
const staticRoutes = [];
for (const route of sortedRoutes){
if ((0, _utils.isDynamicRoute)(route)) {
dynamicRoutes.push(pageToRoute(route));
} else if (!(0, _utils1.isReservedPage)(route)) {
staticRoutes.push(pageToRoute(route));
}
}
return {
version: 3,
pages404: true,
caseSensitive: !!config.experimental.caseSensitiveRoutes,
basePath: config.basePath,
redirects: redirects.map((r)=>(0, _buildcustomroute.buildCustomRoute)('redirect', r, restrictedRedirectPaths)),
headers: headers.map((r)=>(0, _buildcustomroute.buildCustomRoute)('header', r)),
dynamicRoutes,
staticRoutes,
dataRoutes: [],
i18n: config.i18n || undefined,
rsc: {
header: _approuterheaders.RSC_HEADER,
// This vary header is used as a default. It is technically re-assigned in `base-server`,
// and may include an additional Vary option for `Next-URL`.
varyHeader: `${_approuterheaders.RSC_HEADER}, ${_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER}, ${_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER}, ${_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`,
prefetchHeader: _approuterheaders.NEXT_ROUTER_PREFETCH_HEADER,
didPostponeHeader: _approuterheaders.NEXT_DID_POSTPONE_HEADER,
contentTypeHeader: _approuterheaders.RSC_CONTENT_TYPE_HEADER,
suffix: _constants.RSC_SUFFIX,
prefetchSuffix: _constants.RSC_PREFETCH_SUFFIX,
prefetchSegmentHeader: _approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
prefetchSegmentSuffix: _constants.RSC_SEGMENT_SUFFIX,
prefetchSegmentDirSuffix: _constants.RSC_SEGMENTS_DIR_SUFFIX
},
rewriteHeaders: {
pathHeader: _approuterheaders.NEXT_REWRITTEN_PATH_HEADER,
queryHeader: _approuterheaders.NEXT_REWRITTEN_QUERY_HEADER
},
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize,
ppr: isAppPPREnabled ? {
chain: {
headers: {
[_constants.NEXT_RESUME_HEADER]: '1'
}
}
} : undefined
};
});
if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
routesManifest.rewrites = rewrites.afterFiles.map((r)=>(0, _buildcustomroute.buildCustomRoute)('rewrite', r));
} else {
routesManifest.rewrites = {
beforeFiles: rewrites.beforeFiles.map((r)=>(0, _buildcustomroute.buildCustomRoute)('rewrite', r)),
afterFiles: rewrites.afterFiles.map((r)=>(0, _buildcustomroute.buildCustomRoute)('rewrite', r)),
fallback: rewrites.fallback.map((r)=>(0, _buildcustomroute.buildCustomRoute)('rewrite', r))
};
}
let clientRouterFilters;
if (config.experimental.clientRouterFilter) {
const nonInternalRedirects = (config._originalRedirects || []).filter((r)=>!r.internal);
clientRouterFilters = (0, _createclientrouterfilter.createClientRouterFilter)([
...appPaths
], config.experimental.clientRouterFilterRedirects ? nonInternalRedirects : [], config.experimental.clientRouterFilterAllowedRate);
_buildcontext.NextBuildContext.clientRouterFilters = clientRouterFilters;
}
// Ensure commonjs handling is used for files in the distDir (generally .next)
// Files outside of the distDir can be "type": "module"
await writeFileUtf8(_path.default.join(distDir, 'package.json'), '{"type": "commonjs"}');
// These are written to distDir, so they need to come after creating and cleaning distDr.
await (0, _builddiagnostics.recordFrameworkVersion)("15.2.4");
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'start'
});
const outputFileTracingRoot = config.outputFileTracingRoot || dir;
const pagesManifestPath = _path.default.join(distDir, _constants1.SERVER_DIRECTORY, _constants1.PAGES_MANIFEST);
let buildTraceContext;
let buildTracesPromise = undefined;
// If there's has a custom webpack config and disable the build worker.
// Otherwise respect the option if it's set.
const useBuildWorker = config.experimental.webpackBuildWorker || config.experimental.webpackBuildWorker === undefined && !config.webpack;
const runServerAndEdgeInParallel = config.experimental.parallelServerCompiles;
const collectServerBuildTracesInParallel = config.experimental.parallelServerBuildTraces || config.experimental.parallelServerBuildTraces === undefined && isCompileMode;
nextBuildSpan.setAttribute('has-custom-webpack-config', String(!!config.webpack));
nextBuildSpan.setAttribute('use-build-worker', String(useBuildWorker));
if (!useBuildWorker && (runServerAndEdgeInParallel || collectServerBuildTracesInParallel)) {
throw Object.defineProperty(new Error('The "parallelServerBuildTraces" and "parallelServerCompiles" options may only be used when build workers can be used. Read more: https://nextjs.org/docs/messages/parallel-build-without-worker'), "__NEXT_ERROR_CODE", {
value: "E101",
enumerable: false,
configurable: true
});
}
_log.info('Creating an optimized production build ...');
(0, _trace1.traceMemoryUsage)('Starting build', nextBuildSpan);
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'compile',
buildOptions: {
useBuildWorker: String(useBuildWorker)
}
});
let shutdownPromise = Promise.resolve();
if (!isGenerateMode) {
if (turboNextBuild) {
const { duration: compilerDuration, shutdownPromise: p, ...rest } = await (0, _turbopackbuild.turbopackBuild)(process.env.NEXT_TURBOPACK_USE_WORKER === undefined || process.env.NEXT_TURBOPACK_USE_WORKER !== '0');
shutdownPromise = p;
(0, _trace1.traceMemoryUsage)('Finished build', nextBuildSpan);
buildTraceContext = rest.buildTraceContext;
const durationString = durationToString(compilerDuration);
_log.event(`Compiled successfully in ${durationString}`);
telemetry.record((0, _events.eventBuildCompleted)(pagesPaths, {
durationInSeconds: Math.round(compilerDuration),
totalAppPagesCount
}));
} else {
if (runServerAndEdgeInParallel || collectServerBuildTracesInParallel) {
let durationInSeconds = 0;
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'compile-server'
});
const serverBuildPromise = (0, _webpackbuild.webpackBuild)(useBuildWorker, [
'server'
]).then((res)=>{
(0, _trace1.traceMemoryUsage)('Finished server compilation', nextBuildSpan);
buildTraceContext = res.buildTraceContext;
durationInSeconds += res.duration;
if (collectServerBuildTracesInParallel) {
const buildTraceWorker = new _worker.Worker(require.resolve('./collect-build-traces'), {
numWorkers: 1,
exposedMethods: [
'collectBuildTraces'
]
});
buildTracesPromise = buildTraceWorker.collectBuildTraces({
dir,
config,
distDir,
// Serialize Map as this is sent to the worker.
edgeRuntimeRoutes: (0, _utils1.collectRoutesUsingEdgeRuntime)(new Map()),
staticPages: [],
hasSsrAmpPages: false,
buildTraceContext,
outputFileTracingRoot
}).catch((err)=>{
console.error(err);
process.exit(1);
});
}
});
if (!runServerAndEdgeInParallel) {
await serverBuildPromise;
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'webpack-compile-edge-server'
});
}
const edgeBuildPromise = (0, _webpackbuild.webpackBuild)(useBuildWorker, [
'edge-server'
]).then((res)=>{
durationInSeconds += res.duration;
(0, _trace1.traceMemoryUsage)('Finished edge-server compilation', nextBuildSpan);
});
if (runServerAndEdgeInParallel) {
await serverBuildPromise;
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'webpack-compile-edge-server'
});
}
await edgeBuildPromise;
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'webpack-compile-client'
});
await (0, _webpackbuild.webpackBuild)(useBuildWorker, [
'client'
]).then((res)=>{
durationInSeconds += res.duration;
(0, _trace1.traceMemoryUsage)('Finished client compilation', nextBuildSpan);
});
const durationString = durationToString(durationInSeconds);
_log.event(`Compiled successfully in ${durationString}`);
telemetry.record((0, _events.eventBuildCompleted)(pagesPaths, {
durationInSeconds,
totalAppPagesCount
}));
} else {
const { duration: compilerDuration, ...rest } = await (0, _webpackbuild.webpackBuild)(useBuildWorker, null);
(0, _trace1.traceMemoryUsage)('Finished build', nextBuildSpan);
buildTraceContext = rest.buildTraceContext;
telemetry.record((0, _events.eventBuildCompleted)(pagesPaths, {
durationInSeconds: compilerDuration,
totalAppPagesCount
}));
}
}
}
// For app directory, we run type checking after build.
if (appDir && !isCompileMode && !isGenerateMode) {
await (0, _builddiagnostics.updateBuildDiagnostics)({
buildStage: 'type-checking'
});
await (0, _typecheck.startTypeChecking)(typeCheckingOptions);
(0, _trace1.traceMemoryUsage)('Finished type checking', nextBuildSpan);
}
const postCompileSpinner = (0, _spinner.default)('Collecting page data');
const buildManifestPath = _path.default.join(distDir, _constants1.BUILD_MANIFEST);
const appBuildManifestPath = _path.default.join(distDir, _constants1.APP_BUILD_MANIFEST);
let staticAppPagesCount = 0;
let serverAppPagesCount = 0;
let edgeRuntimeAppCount = 0;
let edgeRuntimePagesCount = 0;
const ssgPages = new Set();
const ssgStaticFallbackPages = new Set();
const ssgBlockingFallbackPages = new Set();
const staticPages = new Set();
const invalidPages = new Set();
const hybridAmpPages = new Set();
const serverPropsPages = new Set();
const additionalPaths = new Map();
const staticPaths = new Map();
const prospectiveRenders = new Map();
const appNormalizedPaths = new Map();
const fallbackModes = new Map();
const appDefaultConfigs = new Map();
const pageInfos = new Map();
let pagesManifest = await readManifest(pagesManifestPath);
const buildManifest = await readManifest(buildManifestPath);
const appBuildManifest = appDir ? await readManifest(appBuildManifestPath) : undefined;
const appPathRoutes = {};
if (appDir) {
const appPathsManifest = await readManifest(_path.default.join(distDir, _constants1.SERVER_DIRECTORY, _constants1.APP_PATHS_MANIFEST));
for(const key in appPathsManifest){
appPathRoutes[key] = (0, _apppaths.normalizeAppPath)(key);
}
await writeManifest(_path.default.join(distDir, _constants1.APP_PATH_ROUTES_MANIFEST), appPathRoutes);
}
process.env.NEXT_PHASE = _constants1.PHASE_PRODUCTION_BUILD;
const worker = createStaticWorker(config);
const analysisBegin = process.hrtime();
const staticCheckSpan = nextBuildSpan.traceChild('static-check');
const functionsConfigManifest = {
version: 1,
functions: {}
};
const { customAppGetInitialProps, namedExports, isNextImageImported, hasSsrAmpPages, hasNonStaticErrorPage } = await staticCheckSpan.traceAsyncFn(async ()=>{
var _config_experimental_sri;
if (isCompileMode) {
return {
customAppGetInitialProps: false,
namedExports: [],