main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

23
node_modules/next/dist/export/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import '../server/require-hook';
import { NextConfigComplete } from '../server/config-shared';
import { Span } from '../trace';
export declare class ExportError extends Error {
code: string;
}
export interface ExportOptions {
outdir: string;
isInvokedFromCli: boolean;
hasAppDir: boolean;
silent?: boolean;
threads?: number;
debugOutput?: boolean;
pages?: string[];
buildExport: boolean;
statusMessage?: string;
exportPageWorker?: typeof import('./worker').default;
exportAppPageWorker?: typeof import('./worker').default;
endWorker?: () => Promise<void>;
nextConfig?: NextConfigComplete;
hasOutdirFromCli?: boolean;
}
export default function exportApp(dir: string, options: ExportOptions, span: Span): Promise<void>;

644
node_modules/next/dist/export/index.js generated vendored Normal file
View File

@@ -0,0 +1,644 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ExportError: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ExportError: function() {
return ExportError;
},
default: function() {
return exportApp;
}
});
const _chalk = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/chalk"));
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _fs = require("fs");
require("../server/require-hook");
const _worker = require("../lib/worker");
const _path = require("path");
const _util = require("util");
const _index = require("../build/output/index");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log"));
const _spinner = /*#__PURE__*/ _interop_require_default(require("../build/spinner"));
const _constants = require("../lib/constants");
const _recursivecopy = require("../lib/recursive-copy");
const _constants1 = require("../shared/lib/constants");
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
const _events = require("../telemetry/events");
const _ciinfo = require("../telemetry/ci-info");
const _storage = require("../telemetry/storage");
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path");
const _env = require("@next/env");
const _isapiroute = require("../lib/is-api-route");
const _require = require("../server/require");
const _isapprouteroute = require("../lib/is-app-route-route");
const _isapppageroute = require("../lib/is-app-page-route");
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
const _needsexperimentalreact = require("../lib/needs-experimental-react");
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 = {};
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;
}
const exists = (0, _util.promisify)(_fs.exists);
function divideSegments(number, segments) {
const result = [];
while(number > 0 && segments > 0){
const dividedNumber = number < segments ? number : Math.floor(number / segments);
number -= dividedNumber;
segments--;
result.push(dividedNumber);
}
return result;
}
const createProgress = (total, label)=>{
const segments = divideSegments(total, 4);
if (total === 0) {
throw new Error("invariant: progress total can not be zero");
}
let currentSegmentTotal = segments.shift();
let currentSegmentCount = 0;
let lastProgressOutput = Date.now();
let curProgress = 0;
let progressSpinner = (0, _spinner.default)(`${label} (${curProgress}/${total})`, {
spinner: {
frames: [
"[ ]",
"[= ]",
"[== ]",
"[=== ]",
"[ ===]",
"[ ==]",
"[ =]",
"[ ]",
"[ =]",
"[ ==]",
"[ ===]",
"[====]",
"[=== ]",
"[== ]",
"[= ]"
],
interval: 200
}
});
return ()=>{
curProgress++;
// Make sure we only log once
// - per fully generated segment, or
// - per minute
// when not showing the spinner
if (!progressSpinner) {
currentSegmentCount++;
if (currentSegmentCount === currentSegmentTotal) {
currentSegmentTotal = segments.shift();
currentSegmentCount = 0;
} else if (lastProgressOutput + 60000 > Date.now()) {
return;
}
lastProgressOutput = Date.now();
}
const isFinished = curProgress === total;
// Use \r to reset current line with spinner.
// If it's 100% progressed, then we don't need to break a new line to avoid logging from routes while building.
const newText = `\r ${isFinished ? _log.prefixes.event : _log.prefixes.info} ${label} (${curProgress}/${total})${isFinished ? "" : "\n"}`;
if (progressSpinner) {
progressSpinner.text = newText;
} else {
console.log(newText);
}
if (isFinished && progressSpinner) {
progressSpinner.stop();
console.log(newText);
}
};
};
class ExportError extends Error {
constructor(...args){
super(...args);
this.code = "NEXT_EXPORT_ERROR";
}
}
async function exportApp(dir, options, span) {
const nextExportSpan = span.traceChild("next-export");
return nextExportSpan.traceAsyncFn(async ()=>{
var _nextConfig_amp, _nextConfig_experimental_amp, _nextConfig_experimental_amp1, _nextConfig_experimental_amp2;
dir = (0, _path.resolve)(dir);
// attempt to load global env values so they are available in next.config.js
nextExportSpan.traceChild("load-dotenv").traceFn(()=>(0, _env.loadEnvConfig)(dir, false, _log));
const nextConfig = options.nextConfig || await nextExportSpan.traceChild("load-next-config").traceAsyncFn(()=>(0, _config.default)(_constants1.PHASE_EXPORT, dir));
const threads = options.threads || nextConfig.experimental.cpus;
const distDir = (0, _path.join)(dir, nextConfig.distDir);
const isExportOutput = nextConfig.output === "export";
// Running 'next export'
if (options.isInvokedFromCli) {
if (isExportOutput) {
if (options.hasOutdirFromCli) {
throw new ExportError('"next export -o <dir>" cannot be used when "output: export" is configured in next.config.js. Instead add "distDir" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export');
}
_log.warn('"next export" is no longer needed when "output: export" is configured in next.config.js https://nextjs.org/docs/advanced-features/static-html-export');
return;
}
if ((0, _fs.existsSync)((0, _path.join)(distDir, "server", "app"))) {
throw new ExportError('"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export');
}
_log.warn('"next export" is deprecated in favor of "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export');
}
// Running 'next export' or output is set to 'export'
if (options.isInvokedFromCli || isExportOutput) {
if (nextConfig.experimental.serverActions) {
throw new ExportError(`Server Actions are not supported with static export.`);
}
}
const telemetry = options.buildExport ? null : new _storage.Telemetry({
distDir
});
if (telemetry) {
telemetry.record((0, _events.eventCliSession)(distDir, nextConfig, {
webpackVersion: null,
cliCommand: "export",
isSrcDir: null,
hasNowJson: !!await (0, _findup.default)("now.json", {
cwd: dir
}),
isCustomServer: null,
turboFlag: false,
pagesDir: null,
appDir: null
}));
}
const subFolders = nextConfig.trailingSlash && !options.buildExport;
if (!options.silent && !options.buildExport) {
_log.info(`using build directory: ${distDir}`);
}
const buildIdFile = (0, _path.join)(distDir, _constants1.BUILD_ID_FILE);
if (!(0, _fs.existsSync)(buildIdFile)) {
throw new ExportError(`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`);
}
const customRoutesDetected = [
"rewrites",
"redirects",
"headers"
].filter((config)=>typeof nextConfig[config] === "function");
if (!_ciinfo.hasNextSupport && !options.buildExport && customRoutesDetected.length > 0) {
_log.warn(`rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutesDetected.join(", ")}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`);
}
const buildId = (0, _fs.readFileSync)(buildIdFile, "utf8");
const pagesManifest = !options.pages && require((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.PAGES_MANIFEST));
let prerenderManifest = undefined;
try {
prerenderManifest = require((0, _path.join)(distDir, _constants1.PRERENDER_MANIFEST));
} catch {}
let appRoutePathManifest = undefined;
try {
appRoutePathManifest = require((0, _path.join)(distDir, _constants1.APP_PATH_ROUTES_MANIFEST));
} catch (err) {
if ((0, _iserror.default)(err) && (err.code === "ENOENT" || err.code === "MODULE_NOT_FOUND")) {
// the manifest doesn't exist which will happen when using
// "pages" dir instead of "app" dir.
appRoutePathManifest = undefined;
} else {
// the manifest is malformed (invalid json)
throw err;
}
}
const excludedPrerenderRoutes = new Set();
const pages = options.pages || Object.keys(pagesManifest);
const defaultPathMap = {};
let hasApiRoutes = false;
for (const page of pages){
// _document and _app are not real pages
// _error is exported as 404.html later on
// API Routes are Node.js functions
if ((0, _isapiroute.isAPIRoute)(page)) {
hasApiRoutes = true;
continue;
}
if (page === "/_document" || page === "/_app" || page === "/_error") {
continue;
}
// iSSG pages that are dynamic should not export templated version by
// default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`.
if (prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[page]) {
excludedPrerenderRoutes.add(page);
continue;
}
defaultPathMap[page] = {
page
};
}
const mapAppRouteToPage = new Map();
if (!options.buildExport && appRoutePathManifest) {
for (const [pageName, routePath] of Object.entries(appRoutePathManifest)){
mapAppRouteToPage.set(routePath, pageName);
if ((0, _isapppageroute.isAppPageRoute)(pageName) && !(prerenderManifest == null ? void 0 : prerenderManifest.routes[routePath]) && !(prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[routePath])) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true
};
}
}
}
// Initialize the output directory
const outDir = options.outdir;
if (outDir === (0, _path.join)(dir, "public")) {
throw new ExportError(`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`);
}
if (outDir === (0, _path.join)(dir, "static")) {
throw new ExportError(`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`);
}
await _fs.promises.rm(outDir, {
recursive: true,
force: true
});
await _fs.promises.mkdir((0, _path.join)(outDir, "_next", buildId), {
recursive: true
});
(0, _fs.writeFileSync)((0, _path.join)(distDir, _constants1.EXPORT_DETAIL), JSON.stringify({
version: 1,
outDirectory: outDir,
success: false
}), "utf8");
// Copy static directory
if (!options.buildExport && (0, _fs.existsSync)((0, _path.join)(dir, "static"))) {
if (!options.silent) {
_log.info('Copying "static" directory');
}
await nextExportSpan.traceChild("copy-static-directory").traceAsyncFn(()=>(0, _recursivecopy.recursiveCopy)((0, _path.join)(dir, "static"), (0, _path.join)(outDir, "static")));
}
// Copy .next/static directory
if (!options.buildExport && (0, _fs.existsSync)((0, _path.join)(distDir, _constants1.CLIENT_STATIC_FILES_PATH))) {
if (!options.silent) {
_log.info('Copying "static build" directory');
}
await nextExportSpan.traceChild("copy-next-static-directory").traceAsyncFn(()=>(0, _recursivecopy.recursiveCopy)((0, _path.join)(distDir, _constants1.CLIENT_STATIC_FILES_PATH), (0, _path.join)(outDir, "_next", _constants1.CLIENT_STATIC_FILES_PATH)));
}
// Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== "function") {
nextConfig.exportPathMap = async (defaultMap)=>{
return defaultMap;
};
}
const { i18n, images: { loader = "default", unoptimized } } = nextConfig;
if (i18n && !options.buildExport) {
throw new ExportError(`i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/messages/export-no-custom-routes`);
}
if (!options.buildExport) {
const { isNextImageImported } = await nextExportSpan.traceChild("is-next-image-imported").traceAsyncFn(()=>_fs.promises.readFile((0, _path.join)(distDir, _constants1.EXPORT_MARKER), "utf8").then((text)=>JSON.parse(text)).catch(()=>({})));
if (isNextImageImported && loader === "default" && !unoptimized && !_ciinfo.hasNextSupport) {
throw new ExportError(`Image Optimization using the default loader is not compatible with export.
Possible solutions:
- Use \`next start\` to run a server, which includes the Image Optimization API.
- Configure \`images.unoptimized = true\` in \`next.config.js\` to disable the Image Optimization API.
Read more: https://nextjs.org/docs/messages/export-image-api`);
}
}
// Start the rendering process
const renderOpts = {
dir,
buildId,
nextExport: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ""),
distDir,
dev: false,
hotReloader: null,
basePath: nextConfig.basePath,
canonicalBase: ((_nextConfig_amp = nextConfig.amp) == null ? void 0 : _nextConfig_amp.canonicalBase) || "",
ampValidatorPath: ((_nextConfig_experimental_amp = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp.validator) || undefined,
ampSkipValidation: ((_nextConfig_experimental_amp1 = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp1.skipValidation) || false,
ampOptimizerConfig: ((_nextConfig_experimental_amp2 = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp2.optimizer) || undefined,
locales: i18n == null ? void 0 : i18n.locales,
locale: i18n == null ? void 0 : i18n.defaultLocale,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
trailingSlash: nextConfig.trailingSlash,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
// Exported pages do not currently support dynamic HTML.
supportsDynamicHTML: false,
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: options.hasAppDir,
hasServerComponents: options.hasAppDir,
serverActionsBodySizeLimit: nextConfig.experimental.serverActionsBodySizeLimit,
nextFontManifest: require((0, _path.join)(distDir, "server", `${_constants1.NEXT_FONT_MANIFEST}.json`)),
images: nextConfig.images,
...options.hasAppDir ? {
serverActionsManifest: require((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.SERVER_REFERENCE_MANIFEST + ".json"))
} : {},
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId
};
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig;
if (Object.keys(publicRuntimeConfig).length > 0) {
renderOpts.runtimeConfig = publicRuntimeConfig;
}
globalThis.__NEXT_DATA__ = {
nextExport: true
};
if (!options.silent && !options.buildExport) {
_log.info(`Launching ${threads} workers`);
}
const exportPathMap = await nextExportSpan.traceChild("run-export-path-map").traceAsyncFn(async ()=>{
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId
});
return exportMap;
});
// only add missing 404 page when `buildExport` is false
if (!options.buildExport) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap["/404"]) {
exportPathMap["/404"] = {
page: "/_error"
};
}
/**
* exports 404.html for backwards compat
* E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify
*/ if (!exportPathMap["/404.html"]) {
// alias /404.html to /404 to be compatible with custom 404 / _error page
exportPathMap["/404.html"] = exportPathMap["/404"];
}
}
// make sure to prevent duplicates
const exportPaths = [
...new Set(Object.keys(exportPathMap).map((path)=>(0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(path))))
];
const filteredPaths = exportPaths.filter(// Remove API routes
(route)=>exportPathMap[route]._isAppDir || !(0, _isapiroute.isAPIRoute)(exportPathMap[route].page));
if (filteredPaths.length !== exportPaths.length) {
hasApiRoutes = true;
}
if (filteredPaths.length === 0) {
return;
}
if (prerenderManifest && !options.buildExport) {
const fallbackEnabledPages = new Set();
for (const path of Object.keys(exportPathMap)){
const page = exportPathMap[path].page;
const prerenderInfo = prerenderManifest.dynamicRoutes[page];
if (prerenderInfo && prerenderInfo.fallback !== false) {
fallbackEnabledPages.add(page);
}
}
if (fallbackEnabledPages.size) {
throw new ExportError(`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages
].join("\n")}\n${_constants.SSG_FALLBACK_EXPORT_ERROR}\n`);
}
}
let hasMiddleware = false;
if (!options.buildExport) {
try {
const middlewareManifest = require((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.MIDDLEWARE_MANIFEST));
hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0;
} catch {}
// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
if (!options.silent) {
_log.warn(_chalk.default.yellow(`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`) + `\n` + _chalk.default.yellow(`This command is meant for static-only hosts, and is` + " " + _chalk.default.bold(`not necessary to make your application static.`)) + `\n` + _chalk.default.yellow(`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`) + `\n` + _chalk.default.yellow(`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`));
}
}
}
const progress = !options.silent && createProgress(filteredPaths.length, `${options.statusMessage || "Exporting"}`);
const pagesDataDir = options.buildExport ? outDir : (0, _path.join)(outDir, "_next/data", buildId);
const ampValidations = {};
let hadValidationError = false;
const publicDir = (0, _path.join)(dir, _constants1.CLIENT_PUBLIC_FILES_PATH);
// Copy public directory
if (!options.buildExport && (0, _fs.existsSync)(publicDir)) {
if (!options.silent) {
_log.info('Copying "public" directory');
}
await nextExportSpan.traceChild("copy-public-directory").traceAsyncFn(()=>(0, _recursivecopy.recursiveCopy)(publicDir, outDir, {
filter (path) {
// Exclude paths used by pages
return !exportPathMap[path];
}
}));
}
const timeout = (nextConfig == null ? void 0 : nextConfig.staticPageGenerationTimeout) || 0;
let infoPrinted = false;
let exportPage;
let exportAppPage;
let endWorker;
if (options.exportPageWorker) {
exportPage = options.exportPageWorker;
exportAppPage = options.exportAppPageWorker;
endWorker = options.endWorker || (()=>Promise.resolve());
} else {
const worker = new _worker.Worker(require.resolve("./worker"), {
timeout: timeout * 1000,
onRestart: (_method, [{ path }], attempts)=>{
if (attempts >= 3) {
throw new ExportError(`Static page generation for ${path} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`);
}
_log.warn(`Restarted static page generation for ${path} because it took more than ${timeout} seconds`);
if (!infoPrinted) {
_log.warn("See more info here https://nextjs.org/docs/messages/static-page-generation-timeout");
infoPrinted = true;
}
},
maxRetries: 0,
numWorkers: threads,
enableWorkerThreads: nextConfig.experimental.workerThreads,
exposedMethods: [
"default"
]
});
exportPage = worker.default.bind(worker);
endWorker = async ()=>{
await worker.end();
};
}
let renderError = false;
const errorPaths = [];
await Promise.all(filteredPaths.map(async (path)=>{
const pageExportSpan = nextExportSpan.traceChild("export-page");
pageExportSpan.setAttribute("path", path);
return pageExportSpan.traceAsyncFn(async ()=>{
const pathMap = exportPathMap[path];
const exportPageOrApp = pathMap._isAppDir ? exportAppPage : exportPage;
if (!exportPageOrApp) {
throw new Error("invariant: Undefined export worker for app dir, this is a bug in Next.js.");
}
const result = await exportPageOrApp({
path,
pathMap,
distDir,
outDir,
pagesDataDir,
renderOpts,
serverRuntimeConfig,
subFolders,
buildExport: options.buildExport,
optimizeFonts: nextConfig.optimizeFonts,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
parentSpanId: pageExportSpan.id,
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
isrMemoryCacheSize: nextConfig.experimental.isrMemoryCacheSize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
incrementalCacheHandlerPath: nextConfig.experimental.incrementalCacheHandlerPath,
enableExperimentalReact: (0, _needsexperimentalreact.needsExperimentalReact)(nextConfig)
});
for (const validation of result.ampValidations || []){
const { page, result: ampValidationResult } = validation;
ampValidations[page] = ampValidationResult;
hadValidationError = hadValidationError || Array.isArray(ampValidationResult == null ? void 0 : ampValidationResult.errors) && ampValidationResult.errors.length > 0;
}
renderError = renderError || !!result.error;
if (!!result.error) {
const { page } = pathMap;
errorPaths.push(page !== path ? `${page}: ${path}` : path);
}
if (options.buildExport) {
if (typeof result.fromBuildExportRevalidate !== "undefined") {
nextConfig.initialPageRevalidationMap[path] = result.fromBuildExportRevalidate;
}
if (typeof result.fromBuildExportMeta !== "undefined") {
nextConfig.initialPageMetaMap[path] = result.fromBuildExportMeta;
}
if (result.ssgNotFound === true) {
nextConfig.ssgNotFoundPaths.push(path);
}
const durations = nextConfig.pageDurationMap[pathMap.page] = nextConfig.pageDurationMap[pathMap.page] || {};
durations[path] = result.duration;
}
if (progress) progress();
});
}));
const endWorkerPromise = endWorker();
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(Object.keys(prerenderManifest.routes).map(async (route)=>{
const { srcRoute } = prerenderManifest.routes[route];
const appPageName = mapAppRouteToPage.get(srcRoute || "");
const pageName = appPageName || srcRoute || route;
const isAppPath = Boolean(appPageName);
const isAppRouteHandler = appPageName && (0, _isapprouteroute.isAppRouteRoute)(appPageName);
// returning notFound: true from getStaticProps will not
// output html/json files during the build
if (prerenderManifest.notFoundRoutes.includes(route)) {
return;
}
route = (0, _normalizepagepath.normalizePagePath)(route);
const pagePath = (0, _require.getPagePath)(pageName, distDir, undefined, isAppPath);
const distPagesDir = (0, _path.join)(pagePath, // strip leading / and then recurse number of nested dirs
// to place from base folder
pageName.slice(1).split("/").map(()=>"..").join("/"));
const orig = (0, _path.join)(distPagesDir, route);
const handlerSrc = `${orig}.body`;
const handlerDest = (0, _path.join)(outDir, route);
if (isAppRouteHandler && await exists(handlerSrc)) {
await _fs.promises.mkdir((0, _path.dirname)(handlerDest), {
recursive: true
});
await _fs.promises.copyFile(handlerSrc, handlerDest);
return;
}
const htmlDest = (0, _path.join)(outDir, `${route}${subFolders && route !== "/index" ? `${_path.sep}index` : ""}.html`);
const ampHtmlDest = (0, _path.join)(outDir, `${route}.amp${subFolders ? `${_path.sep}index` : ""}.html`);
const jsonDest = isAppPath ? (0, _path.join)(outDir, `${route}${subFolders && route !== "/index" ? `${_path.sep}index` : ""}.txt`) : (0, _path.join)(pagesDataDir, `${route}.json`);
await _fs.promises.mkdir((0, _path.dirname)(htmlDest), {
recursive: true
});
await _fs.promises.mkdir((0, _path.dirname)(jsonDest), {
recursive: true
});
const htmlSrc = `${orig}.html`;
const jsonSrc = `${orig}${isAppPath ? ".rsc" : ".json"}`;
await _fs.promises.copyFile(htmlSrc, htmlDest);
await _fs.promises.copyFile(jsonSrc, jsonDest);
if (await exists(`${orig}.amp.html`)) {
await _fs.promises.mkdir((0, _path.dirname)(ampHtmlDest), {
recursive: true
});
await _fs.promises.copyFile(`${orig}.amp.html`, ampHtmlDest);
}
}));
}
if (Object.keys(ampValidations).length) {
console.log((0, _index.formatAmpMessages)(ampValidations));
}
if (hadValidationError) {
throw new ExportError(`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`);
}
if (renderError) {
throw new ExportError(`Export encountered errors on following paths:\n\t${errorPaths.sort().join("\n ")}`);
}
(0, _fs.writeFileSync)((0, _path.join)(distDir, _constants1.EXPORT_DETAIL), JSON.stringify({
version: 1,
outDirectory: outDir,
success: true
}), "utf8");
if (telemetry) {
await telemetry.flush();
}
await endWorkerPromise;
});
}
//# sourceMappingURL=index.js.map

1
node_modules/next/dist/export/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

79
node_modules/next/dist/export/worker.d.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
/// <reference types="node" />
import type { FontManifest, FontConfig } from '../server/font-utils';
import type { DomainLocale, ExportPathMap, NextConfigComplete } from '../server/config-shared';
import type { OutgoingHttpHeaders } from 'http';
import '../server/node-polyfill-fetch';
import '../server/node-environment';
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator';
import { IncrementalCache } from '../server/lib/incremental-cache';
interface AmpValidation {
page: string;
result: {
errors: AmpHtmlValidator.ValidationError[];
warnings: AmpHtmlValidator.ValidationError[];
};
}
type PathMap = ExportPathMap[keyof ExportPathMap];
interface ExportPageInput {
path: string;
pathMap: PathMap;
distDir: string;
outDir: string;
pagesDataDir: string;
renderOpts: RenderOpts;
buildExport?: boolean;
serverRuntimeConfig: {
[key: string]: any;
};
subFolders?: boolean;
optimizeFonts: FontConfig;
optimizeCss: any;
disableOptimizedLoading: any;
parentSpanId: any;
httpAgentOptions: NextConfigComplete['httpAgentOptions'];
debugOutput?: boolean;
isrMemoryCacheSize?: NextConfigComplete['experimental']['isrMemoryCacheSize'];
fetchCache?: boolean;
incrementalCacheHandlerPath?: string;
fetchCacheKeyPrefix?: string;
nextConfigOutput?: NextConfigComplete['output'];
enableExperimentalReact?: boolean;
}
interface ExportPageResults {
ampValidations: AmpValidation[];
fromBuildExportRevalidate?: number | false;
fromBuildExportMeta?: {
status?: number;
headers?: OutgoingHttpHeaders;
};
error?: boolean;
ssgNotFound?: boolean;
duration: number;
}
interface RenderOpts {
runtimeConfig?: {
[key: string]: any;
};
params?: {
[key: string]: string | string[];
};
ampPath?: string;
ampValidatorPath?: string;
ampSkipValidation?: boolean;
optimizeFonts?: FontConfig;
disableOptimizedLoading?: boolean;
optimizeCss?: any;
fontManifest?: FontManifest;
locales?: string[];
locale?: string;
defaultLocale?: string;
domainLocales?: DomainLocale[];
trailingSlash?: boolean;
supportsDynamicHTML?: boolean;
incrementalCache?: IncrementalCache;
strictNextHead?: boolean;
originalPathname?: string;
deploymentId?: string;
}
export default function exportPage({ parentSpanId, path, pathMap, distDir, outDir, pagesDataDir, renderOpts, buildExport, serverRuntimeConfig, subFolders, optimizeFonts, optimizeCss, disableOptimizedLoading, httpAgentOptions, debugOutput, isrMemoryCacheSize, fetchCache, fetchCacheKeyPrefix, incrementalCacheHandlerPath, enableExperimentalReact, }: ExportPageInput): Promise<ExportPageResults>;
export {};

577
node_modules/next/dist/export/worker.js generated vendored Normal file
View File

@@ -0,0 +1,577 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return exportPage;
}
});
require("../server/node-polyfill-fetch");
require("../server/node-environment");
const _path = require("path");
const _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs"));
const _amphtmlvalidator = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/amphtml-validator"));
const _loadcomponents = require("../server/load-components");
const _isdynamic = require("../shared/lib/router/utils/is-dynamic");
const _routematcher = require("../shared/lib/router/utils/route-matcher");
const _routeregex = require("../shared/lib/router/utils/route-regex");
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
const _constants = require("../lib/constants");
const _require = require("../server/require");
const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path");
const _trace = require("../trace");
const _ampmode = require("../shared/lib/amp-mode");
const _setuphttpagentenv = require("../server/setup-http-agent-env");
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../server/render-result"));
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
const _requestmeta = require("../server/request-meta");
const _apppaths = require("../shared/lib/router/utils/app-paths");
const _hooksservercontext = require("../client/components/hooks-server-context");
const _incrementalcache = require("../server/lib/incremental-cache");
const _notfound = require("../client/components/not-found");
const _redirect = require("../client/components/redirect");
const _nossrerror = require("../shared/lib/lazy-dynamic/no-ssr-error");
const _mockrequest = require("../server/lib/mock-request");
const _node = require("../server/base-http/node");
const _isapprouteroute = require("../lib/is-app-route-route");
const _utils = require("../server/web/utils");
const _routemoduleloader = require("../server/future/helpers/module-loader/route-module-loader");
const _nextrequest = require("../server/web/spec-extension/adapters/next-request");
const _ciinfo = /*#__PURE__*/ _interop_require_wildcard(require("../telemetry/ci-info"));
const _approuterheaders = require("../client/components/app-router-headers");
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 = {};
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;
}
process.env.NEXT_IS_EXPORT_WORKER = "true";
const envConfig = require("../shared/lib/runtime-config.external");
globalThis.__NEXT_DATA__ = {
nextExport: true
};
async function exportPage({ parentSpanId, path, pathMap, distDir, outDir, pagesDataDir, renderOpts, buildExport, serverRuntimeConfig, subFolders, optimizeFonts, optimizeCss, disableOptimizedLoading, httpAgentOptions, debugOutput, isrMemoryCacheSize, fetchCache, fetchCacheKeyPrefix, incrementalCacheHandlerPath, enableExperimentalReact }) {
(0, _setuphttpagentenv.setHttpClientAndAgentOptions)({
httpAgentOptions
});
const exportPageSpan = (0, _trace.trace)("export-page-worker", parentSpanId);
return exportPageSpan.traceAsyncFn(async ()=>{
const start = Date.now();
let results = {
ampValidations: []
};
try {
var _req_url, _components_pageConfig, _components_pageConfig1;
if (renderOpts.deploymentId) {
process.env.NEXT_DEPLOYMENT_ID = renderOpts.deploymentId;
}
if (enableExperimentalReact) {
process.env.__NEXT_EXPERIMENTAL_REACT = "true";
}
const { query: originalQuery = {} } = pathMap;
const { page } = pathMap;
const pathname = (0, _apppaths.normalizeAppPath)(page);
const isAppDir = Boolean(pathMap._isAppDir);
const isAppPrefetch = Boolean(pathMap._isAppPrefetch);
const isDynamicError = pathMap._isDynamicError;
const filePath = (0, _normalizepagepath.normalizePagePath)(path);
const isDynamic = (0, _isdynamic.isDynamicRoute)(page);
const ampPath = `${filePath}.amp`;
let renderAmpPath = ampPath;
let query = {
...originalQuery
};
let params;
const isRouteHandler = isAppDir && (0, _isapprouteroute.isAppRouteRoute)(page);
if (isAppDir) {
outDir = (0, _path.join)(distDir, "server/app");
}
let updatedPath = query.__nextSsgPath || path;
let locale = query.__nextLocale || renderOpts.locale;
delete query.__nextLocale;
delete query.__nextSsgPath;
if (renderOpts.locale) {
const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(path, renderOpts.locales);
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname;
locale = localePathResult.detectedLocale;
if (locale === renderOpts.defaultLocale) {
renderAmpPath = `${(0, _normalizepagepath.normalizePagePath)(updatedPath)}.amp`;
}
}
}
// We need to show a warning if they try to provide query values
// for an auto-exported page since they won't be available
const hasOrigQueryValues = Object.keys(originalQuery).length > 0;
const queryWithAutoExportWarn = ()=>{
if (hasOrigQueryValues) {
throw new Error(`\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \`getInitialProps\`\n`);
}
};
// Check if the page is a specified dynamic route
const nonLocalizedPath = (0, _normalizelocalepath.normalizeLocalePath)(path, renderOpts.locales).pathname;
if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? (0, _apppaths.normalizeAppPath)(page) : page;
params = (0, _routematcher.getRouteMatcher)((0, _routeregex.getRouteRegex)(normalizedPage))(updatedPath) || undefined;
if (params) {
query = {
...query,
...params
};
} else {
throw new Error(`The provided export path '${updatedPath}' doesn't match the '${page}' page.\nRead more: https://nextjs.org/docs/messages/export-path-mismatch`);
}
}
const { req, res } = (0, _mockrequest.createRequestResponseMocks)({
url: updatedPath
});
for (const statusCode of [
404,
500
]){
if ([
`/${statusCode}`,
`/${statusCode}.html`,
`/${statusCode}/index.html`
].some((p)=>p === updatedPath || `/${locale}${p}` === updatedPath)) {
res.statusCode = statusCode;
}
}
if (renderOpts.trailingSlash && !((_req_url = req.url) == null ? void 0 : _req_url.endsWith("/"))) {
req.url += "/";
}
if (locale && buildExport && renderOpts.domainLocales && renderOpts.domainLocales.some((dl)=>{
var _dl_locales;
return dl.defaultLocale === locale || ((_dl_locales = dl.locales) == null ? void 0 : _dl_locales.includes(locale || ""));
})) {
(0, _requestmeta.addRequestMeta)(req, "__nextIsLocaleDomain", true);
}
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig: renderOpts.runtimeConfig
});
const getHtmlFilename = (_path1)=>subFolders ? `${_path1}${_path.sep}index.html` : `${_path1}.html`;
let htmlFilename = getHtmlFilename(filePath);
// dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an
// extension of `.slug]`
const pageExt = isDynamic || isAppDir ? "" : (0, _path.extname)(page);
const pathExt = isDynamic || isAppDir ? "" : (0, _path.extname)(path);
// force output 404.html for backwards compat
if (path === "/404.html") {
htmlFilename = path;
} else if (pageExt !== pathExt && pathExt !== "") {
const isBuiltinPaths = [
"/500",
"/404"
].some((p)=>p === path || p === path + ".html");
// If the ssg path has .html extension, and it's not builtin paths, use it directly
// Otherwise, use that as the filename instead
const isHtmlExtPath = !isBuiltinPaths && path.endsWith(".html");
htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path;
} else if (path === "/") {
// If the path is the root, just use index.html
htmlFilename = "index.html";
}
const baseDir = (0, _path.join)(outDir, (0, _path.dirname)(htmlFilename));
let htmlFilepath = (0, _path.join)(outDir, htmlFilename);
await _fs.promises.mkdir(baseDir, {
recursive: true
});
let renderResult;
let curRenderOpts = {};
const renderToHTML = require("../server/future/route-modules/pages/module.compiled").renderToHTML;
let renderMethod = renderToHTML;
let inAmpMode = false, hybridAmp = false;
const renderedDuringBuild = (getStaticProps)=>{
return !buildExport && getStaticProps && !(0, _isdynamic.isDynamicRoute)(path);
};
let components = null;
if (!isRouteHandler) {
components = await (0, _loadcomponents.loadComponents)({
distDir,
page: page,
isAppPath: isAppDir
});
curRenderOpts = {
...components,
...renderOpts,
strictNextHead: !!renderOpts.strictNextHead,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts ? (0, _require.requireFontManifest)(distDir) : null,
locale: locale,
supportsDynamicHTML: false,
originalPathname: page,
..._ciinfo.hasNextSupport ? {
isRevalidate: true
} : {}
};
}
// during build we attempt rendering app dir paths
// and bail when dynamic dependencies are detected
// only fully static paths are fully generated here
if (isAppDir) {
if (fetchCache) {
let CacheHandler;
if (incrementalCacheHandlerPath) {
CacheHandler = require(incrementalCacheHandlerPath);
CacheHandler = CacheHandler.default || CacheHandler;
}
const incrementalCache = new _incrementalcache.IncrementalCache({
dev: false,
requestHeaders: {},
flushToDisk: true,
fetchCache: true,
maxMemoryCacheSize: isrMemoryCacheSize,
fetchCacheKeyPrefix,
getPrerenderManifest: ()=>({
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: "",
previewModeId: "",
previewModeSigningKey: ""
},
notFoundRoutes: []
}),
fs: {
readFile: (f)=>_fs.default.promises.readFile(f),
readFileSync: (f)=>_fs.default.readFileSync(f),
writeFile: (f, d)=>_fs.default.promises.writeFile(f, d),
mkdir: (dir)=>_fs.default.promises.mkdir(dir, {
recursive: true
}),
stat: (f)=>_fs.default.promises.stat(f)
},
serverDistDir: (0, _path.join)(distDir, "server"),
CurCacheHandler: CacheHandler,
minimalMode: _ciinfo.hasNextSupport
});
globalThis.__incrementalCache = incrementalCache;
curRenderOpts.incrementalCache = incrementalCache;
}
const isDynamicUsageError = (err)=>err.digest === _hooksservercontext.DYNAMIC_ERROR_CODE || (0, _notfound.isNotFoundError)(err) || err.digest === _nossrerror.NEXT_DYNAMIC_NO_SSR_CODE || (0, _redirect.isRedirectError)(err);
const isNotFoundPage = page === "/_not-found";
const generatePrefetchRsc = async ()=>{
// If we bail for prerendering due to dynamic usage we need to
// generate a static prefetch payload to prevent invoking
// functions during runtime just for prefetching
const { renderToHTMLOrFlight } = require("../server/future/route-modules/app-page/module.compiled");
req.headers[_approuterheaders.RSC.toLowerCase()] = "1";
req.headers[_approuterheaders.NEXT_URL.toLowerCase()] = path;
req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH.toLowerCase()] = "1";
curRenderOpts.supportsDynamicHTML = true;
delete curRenderOpts.isRevalidate;
const prefetchRenderResult = await renderToHTMLOrFlight(req, res, isNotFoundPage ? "/404" : pathname, query, curRenderOpts);
prefetchRenderResult.pipe(res);
await res.hasStreamed;
const prefetchRscData = Buffer.concat(res.buffers).toString();
await _fs.promises.writeFile(htmlFilepath.replace(/\.html$/, ".prefetch.rsc"), prefetchRscData);
};
// for dynamic routes with no generate static params
// we generate strictly the prefetch RSC payload to
// avoid attempting to render with default params e.g. [slug]
if (isAppPrefetch) {
await generatePrefetchRsc();
} else if (isRouteHandler) {
// Ensure that the url for the page is absolute.
req.url = `http://localhost:3000${req.url}`;
const request = _nextrequest.NextRequestAdapter.fromNodeNextRequest(new _node.NodeNextRequest(req), (0, _nextrequest.signalFromNodeResponse)(res));
// Create the context for the handler. This contains the params from
// the route and the context for the request.
const context = {
params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: "",
previewModeId: "",
previewModeSigningKey: ""
},
notFoundRoutes: []
},
staticGenerationContext: {
originalPathname: page,
nextExport: true,
supportsDynamicHTML: false,
incrementalCache: curRenderOpts.incrementalCache,
..._ciinfo.hasNextSupport ? {
isRevalidate: true
} : {}
}
};
try {
// This is a route handler, which means it has it's handler in the
// bundled file already, we should just use that.
const filename = _path.posix.join(distDir, "server", "app", page);
// Load the module for the route.
const module = await _routemoduleloader.RouteModuleLoader.load(filename);
// Call the handler with the request and context from the module.
const response = await module.handle(request, context);
// TODO: (wyattjoh) if cookie headers are present, should we bail?
// we don't consider error status for static generation
// except for 404
// TODO: do we want to cache other status codes?
const isValidStatus = response.status < 400 || response.status === 404;
if (isValidStatus) {
var _context_staticGenerationContext_store;
const body = await response.blob();
const revalidate = ((_context_staticGenerationContext_store = context.staticGenerationContext.store) == null ? void 0 : _context_staticGenerationContext_store.revalidate) || false;
results.fromBuildExportRevalidate = revalidate;
const headers = (0, _utils.toNodeOutgoingHttpHeaders)(response.headers);
const cacheTags = context.staticGenerationContext.fetchTags;
if (cacheTags) {
headers[_constants.NEXT_CACHE_TAGS_HEADER] = cacheTags;
}
if (!headers["content-type"] && body.type) {
headers["content-type"] = body.type;
}
results.fromBuildExportMeta = {
status: response.status,
headers
};
await _fs.promises.writeFile(htmlFilepath.replace(/\.html$/, ".body"), Buffer.from(await body.arrayBuffer()), "utf8");
await _fs.promises.writeFile(htmlFilepath.replace(/\.html$/, ".meta"), JSON.stringify({
status: response.status,
headers
}));
} else {
results.fromBuildExportRevalidate = 0;
}
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
results.fromBuildExportRevalidate = 0;
}
} else {
const renderToHTMLOrFlight = require("../server/future/route-modules/app-page/module.compiled").renderToHTMLOrFlight;
try {
curRenderOpts.params ||= {};
const result = await renderToHTMLOrFlight(req, res, isNotFoundPage ? "/404" : pathname, query, curRenderOpts);
const html = result.toUnchunkedString();
const { metadata } = result;
const flightData = metadata.pageData;
const revalidate = metadata.revalidate;
results.fromBuildExportRevalidate = revalidate;
if (revalidate !== 0) {
const cacheTags = metadata.fetchTags;
const headers = cacheTags ? {
[_constants.NEXT_CACHE_TAGS_HEADER]: cacheTags
} : undefined;
if (_ciinfo.hasNextSupport) {
if (cacheTags) {
results.fromBuildExportMeta = {
headers
};
}
}
await _fs.promises.writeFile(htmlFilepath, html ?? "", "utf8");
await _fs.promises.writeFile(htmlFilepath.replace(/\.html$/, ".meta"), JSON.stringify({
headers
}));
await _fs.promises.writeFile(htmlFilepath.replace(/\.html$/, ".rsc"), flightData);
} else if (isDynamicError) {
throw new Error(`Page with dynamic = "error" encountered dynamic data method on ${path}.`);
} else {
await generatePrefetchRsc();
}
const staticBailoutInfo = metadata.staticBailoutInfo || {};
if (revalidate === 0 && debugOutput && (staticBailoutInfo == null ? void 0 : staticBailoutInfo.description)) {
const bailErr = new Error(`Static generation failed due to dynamic usage on ${path}, reason: ${staticBailoutInfo.description}`);
const stack = staticBailoutInfo.stack;
if (stack) {
bailErr.stack = bailErr.message + stack.substring(stack.indexOf("\n"));
}
console.warn(bailErr);
}
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
}
}
return {
...results,
duration: Date.now() - start
};
}
if (!components) {
throw new Error(`invariant: components were not loaded correctly during export for path: ${path}`);
}
const ampState = {
ampFirst: ((_components_pageConfig = components.pageConfig) == null ? void 0 : _components_pageConfig.amp) === true,
hasQuery: Boolean(query.amp),
hybrid: ((_components_pageConfig1 = components.pageConfig) == null ? void 0 : _components_pageConfig1.amp) === "hybrid"
};
inAmpMode = (0, _ampmode.isInAmpMode)(ampState);
hybridAmp = ampState.hybrid;
if (components.getServerSideProps) {
throw new Error(`Error for page ${page}: ${_constants.SERVER_PROPS_EXPORT_ERROR}`);
}
// for non-dynamic SSG pages we should have already
// prerendered the file
if (renderedDuringBuild(components.getStaticProps)) {
return {
...results,
duration: Date.now() - start
};
}
if (components.getStaticProps && !htmlFilepath.endsWith(".html")) {
// make sure it ends with .html if the name contains a dot
htmlFilepath += ".html";
htmlFilename += ".html";
}
if (typeof components.Component === "string") {
renderResult = _renderresult.default.fromStatic(components.Component);
queryWithAutoExportWarn();
} else {
/**
* This sets environment variable to be used at the time of static export by head.tsx.
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/ if (optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(optimizeFonts);
}
if (optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true);
}
try {
renderResult = await renderMethod(req, res, page, query, // @ts-ignore
curRenderOpts);
} catch (err) {
if (err.digest !== _nossrerror.NEXT_DYNAMIC_NO_SSR_CODE) {
throw err;
}
}
}
results.ssgNotFound = renderResult == null ? void 0 : renderResult.metadata.isNotFound;
const validateAmp = async (rawAmpHtml, ampPageName, validatorPath)=>{
const validator = await _amphtmlvalidator.default.getInstance(validatorPath);
const result = validator.validateString(rawAmpHtml);
const errors = result.errors.filter((e)=>e.severity === "ERROR");
const warnings = result.errors.filter((e)=>e.severity !== "ERROR");
if (warnings.length || errors.length) {
results.ampValidations.push({
page: ampPageName,
result: {
errors,
warnings
}
});
}
};
const html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : "";
let ampRenderResult;
if (inAmpMode && !curRenderOpts.ampSkipValidation) {
if (!results.ssgNotFound) {
await validateAmp(html, path, curRenderOpts.ampValidatorPath);
}
} else if (hybridAmp) {
// we need to render the AMP version
let ampHtmlFilename = `${ampPath}${_path.sep}index.html`;
if (!subFolders) {
ampHtmlFilename = `${ampPath}.html`;
}
const ampBaseDir = (0, _path.join)(outDir, (0, _path.dirname)(ampHtmlFilename));
const ampHtmlFilepath = (0, _path.join)(outDir, ampHtmlFilename);
try {
await _fs.promises.access(ampHtmlFilepath);
} catch (_) {
// make sure it doesn't exist from manual mapping
try {
ampRenderResult = await renderMethod(req, res, page, // @ts-ignore
{
...query,
amp: "1"
}, curRenderOpts);
} catch (err) {
if (err.digest !== _nossrerror.NEXT_DYNAMIC_NO_SSR_CODE) {
throw err;
}
}
const ampHtml = ampRenderResult && !ampRenderResult.isNull ? ampRenderResult.toUnchunkedString() : "";
if (!curRenderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + "?amp=1");
}
await _fs.promises.mkdir(ampBaseDir, {
recursive: true
});
await _fs.promises.writeFile(ampHtmlFilepath, ampHtml, "utf8");
}
}
const metadata = (renderResult == null ? void 0 : renderResult.metadata) || (ampRenderResult == null ? void 0 : ampRenderResult.metadata) || {};
if (metadata.pageData) {
const dataFile = (0, _path.join)(pagesDataDir, htmlFilename.replace(/\.html$/, ".json"));
await _fs.promises.mkdir((0, _path.dirname)(dataFile), {
recursive: true
});
await _fs.promises.writeFile(dataFile, JSON.stringify(metadata.pageData), "utf8");
if (hybridAmp) {
await _fs.promises.writeFile(dataFile.replace(/\.json$/, ".amp.json"), JSON.stringify(metadata.pageData), "utf8");
}
}
results.fromBuildExportRevalidate = metadata.revalidate;
if (!results.ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
await _fs.promises.writeFile(htmlFilepath, html, "utf8");
}
} catch (error) {
console.error(`\nError occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error\n` + ((0, _iserror.default)(error) && error.stack ? error.stack : error));
results.error = true;
}
return {
...results,
duration: Date.now() - start
};
});
}
//# sourceMappingURL=worker.js.map

1
node_modules/next/dist/export/worker.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long