"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
0 && (module.exports = {
    mergeBuildManifests: null,
    mergeAppBuildManifests: null,
    mergePagesManifests: null,
    mergeMiddlewareManifests: null,
    mergeActionManifests: null,
    mergeFontManifests: null,
    mergeLoadableManifests: null,
    getTurbopackJsConfig: null,
    readPartialManifest: null,
    loadMiddlewareManifest: null,
    writeManifests: null,
    formatIssue: null,
    processIssues: null,
    renderStyledStringToErrorAnsi: null,
    msToNs: null,
    handleRouteType: null,
    handleEntrypoints: null,
    handlePagesErrorRoute: null
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    mergeBuildManifests: function() {
        return mergeBuildManifests;
    },
    mergeAppBuildManifests: function() {
        return mergeAppBuildManifests;
    },
    mergePagesManifests: function() {
        return mergePagesManifests;
    },
    mergeMiddlewareManifests: function() {
        return mergeMiddlewareManifests;
    },
    mergeActionManifests: function() {
        return mergeActionManifests;
    },
    mergeFontManifests: function() {
        return mergeFontManifests;
    },
    mergeLoadableManifests: function() {
        return mergeLoadableManifests;
    },
    getTurbopackJsConfig: function() {
        return getTurbopackJsConfig;
    },
    readPartialManifest: function() {
        return readPartialManifest;
    },
    loadMiddlewareManifest: function() {
        return loadMiddlewareManifest;
    },
    writeManifests: function() {
        return writeManifests;
    },
    formatIssue: function() {
        return formatIssue;
    },
    processIssues: function() {
        return processIssues;
    },
    renderStyledStringToErrorAnsi: function() {
        return renderStyledStringToErrorAnsi;
    },
    msToNs: function() {
        return msToNs;
    },
    handleRouteType: function() {
        return handleRouteType;
    },
    handleEntrypoints: function() {
        return handleEntrypoints;
    },
    handlePagesErrorRoute: function() {
        return handlePagesErrorRoute;
    }
});
const _pathtoregexp = require("next/dist/compiled/path-to-regexp");
const _actionencryptionutils = require("../app-render/action-encryption-utils");
const _loadjsconfig = /*#__PURE__*/ _interop_require_default(require("../../build/load-jsconfig"));
const _path = require("path");
const _promises = require("fs/promises");
const _constants = require("../../shared/lib/constants");
const _writeatomic = require("../../lib/fs/write-atomic");
const _nextjsrequirecachehotreloader = require("../../build/webpack/plugins/nextjs-require-cache-hot-reloader");
const _buildmanifestplugin = require("../../build/webpack/plugins/build-manifest-plugin");
const _generateinterceptionroutesrewrites = require("../../lib/generate-interception-routes-rewrites");
const _magicidentifier = require("../../shared/lib/magic-identifier");
const _picocolors = require("../../lib/picocolors");
const _hotreloadertypes = require("./hot-reloader-types");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
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;
}
function mergeBuildManifests(manifests) {
    const manifest = {
        pages: {
            "/_app": []
        },
        // Something in next.js depends on these to exist even for app dir rendering
        devFiles: [],
        ampDevFiles: [],
        polyfillFiles: [],
        lowPriorityFiles: [
            "static/development/_ssgManifest.js",
            "static/development/_buildManifest.js"
        ],
        rootMainFiles: [],
        ampFirstPages: []
    };
    for (const m of manifests){
        Object.assign(manifest.pages, m.pages);
        if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles;
    }
    return manifest;
}
function mergeAppBuildManifests(manifests) {
    const manifest = {
        pages: {}
    };
    for (const m of manifests){
        Object.assign(manifest.pages, m.pages);
    }
    return manifest;
}
function mergePagesManifests(manifests) {
    const manifest = {};
    for (const m of manifests){
        Object.assign(manifest, m);
    }
    return manifest;
}
function mergeMiddlewareManifests(manifests) {
    const manifest = {
        version: 2,
        middleware: {},
        sortedMiddleware: [],
        functions: {}
    };
    let instrumentation = undefined;
    for (const m of manifests){
        Object.assign(manifest.functions, m.functions);
        Object.assign(manifest.middleware, m.middleware);
        if (m.instrumentation) {
            instrumentation = m.instrumentation;
        }
    }
    const updateFunctionDefinition = (fun)=>{
        return {
            ...fun,
            files: [
                ...(instrumentation == null ? void 0 : instrumentation.files) ?? [],
                ...fun.files
            ]
        };
    };
    for (const key of Object.keys(manifest.middleware)){
        const value = manifest.middleware[key];
        manifest.middleware[key] = updateFunctionDefinition(value);
    }
    for (const key of Object.keys(manifest.functions)){
        const value = manifest.functions[key];
        manifest.functions[key] = updateFunctionDefinition(value);
    }
    for (const fun of Object.values(manifest.functions).concat(Object.values(manifest.middleware))){
        for (const matcher of fun.matchers){
            if (!matcher.regexp) {
                matcher.regexp = (0, _pathtoregexp.pathToRegexp)(matcher.originalSource, [], {
                    delimiter: "/",
                    sensitive: false,
                    strict: true
                }).source.replaceAll("\\/", "/");
            }
        }
    }
    manifest.sortedMiddleware = Object.keys(manifest.middleware);
    return manifest;
}
async function mergeActionManifests(manifests) {
    const manifest = {
        node: {},
        edge: {},
        encryptionKey: await (0, _actionencryptionutils.generateRandomActionKeyRaw)(true)
    };
    function mergeActionIds(actionEntries, other) {
        for(const key in other){
            const action = actionEntries[key] ??= {
                workers: {},
                layer: {}
            };
            Object.assign(action.workers, other[key].workers);
            Object.assign(action.layer, other[key].layer);
        }
    }
    for (const m of manifests){
        mergeActionIds(manifest.node, m.node);
        mergeActionIds(manifest.edge, m.edge);
    }
    return manifest;
}
function mergeFontManifests(manifests) {
    const manifest = {
        app: {},
        appUsingSizeAdjust: false,
        pages: {},
        pagesUsingSizeAdjust: false
    };
    for (const m of manifests){
        Object.assign(manifest.app, m.app);
        Object.assign(manifest.pages, m.pages);
        manifest.appUsingSizeAdjust = manifest.appUsingSizeAdjust || m.appUsingSizeAdjust;
        manifest.pagesUsingSizeAdjust = manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust;
    }
    return manifest;
}
function mergeLoadableManifests(manifests) {
    const manifest = {};
    for (const m of manifests){
        Object.assign(manifest, m);
    }
    return manifest;
}
async function getTurbopackJsConfig(dir, nextConfig) {
    const { jsConfig } = await (0, _loadjsconfig.default)(dir, nextConfig);
    return jsConfig ?? {
        compilerOptions: {}
    };
}
async function readPartialManifest(distDir, name, pageName, type = "pages") {
    const manifestPath = _path.posix.join(distDir, `server`, type === "app-route" ? "app" : type, type === "middleware" || type === "instrumentation" ? "" : pageName === "/" ? "index" : pageName === "/index" || pageName.startsWith("/index/") ? `/index${pageName}` : pageName, type === "app" ? "page" : type === "app-route" ? "route" : "", name);
    return JSON.parse(await (0, _promises.readFile)(_path.posix.join(manifestPath), "utf-8"));
}
async function loadMiddlewareManifest(distDir, middlewareManifests, pageName, type) {
    middlewareManifests.set(pageName, await readPartialManifest(distDir, _constants.MIDDLEWARE_MANIFEST, pageName, type));
}
async function loadBuildManifest(distDir, buildManifests, pageName, type = "pages") {
    buildManifests.set(pageName, await readPartialManifest(distDir, _constants.BUILD_MANIFEST, pageName, type));
}
async function loadAppBuildManifest(distDir, appBuildManifests, pageName) {
    appBuildManifests.set(pageName, await readPartialManifest(distDir, _constants.APP_BUILD_MANIFEST, pageName, "app"));
}
async function loadPagesManifest(distDir, pagesManifests, pageName) {
    pagesManifests.set(pageName, await readPartialManifest(distDir, _constants.PAGES_MANIFEST, pageName));
}
async function loadAppPathManifest(distDir, appPathsManifests, pageName, type = "app") {
    appPathsManifests.set(pageName, await readPartialManifest(distDir, _constants.APP_PATHS_MANIFEST, pageName, type));
}
async function loadActionManifest(distDir, actionManifests, pageName) {
    actionManifests.set(pageName, await readPartialManifest(distDir, `${_constants.SERVER_REFERENCE_MANIFEST}.json`, pageName, "app"));
}
async function loadFontManifest(distDir, fontManifests, pageName, type = "pages") {
    fontManifests.set(pageName, await readPartialManifest(distDir, `${_constants.NEXT_FONT_MANIFEST}.json`, pageName, type));
}
async function loadLoadableManifest(distDir, loadableManifests, pageName, type = "pages") {
    loadableManifests.set(pageName, await readPartialManifest(distDir, _constants.REACT_LOADABLE_MANIFEST, pageName, type));
}
async function writeBuildManifest(distDir, buildId, buildManifests, currentEntrypoints, rewrites) {
    const buildManifest = mergeBuildManifests(buildManifests.values());
    const buildManifestPath = (0, _path.join)(distDir, _constants.BUILD_MANIFEST);
    const middlewareBuildManifestPath = (0, _path.join)(distDir, "server", `${_constants.MIDDLEWARE_BUILD_MANIFEST}.js`);
    const interceptionRewriteManifestPath = (0, _path.join)(distDir, "server", `${_constants.INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`);
    (0, _nextjsrequirecachehotreloader.deleteCache)(buildManifestPath);
    (0, _nextjsrequirecachehotreloader.deleteCache)(middlewareBuildManifestPath);
    (0, _nextjsrequirecachehotreloader.deleteCache)(interceptionRewriteManifestPath);
    await (0, _writeatomic.writeFileAtomic)(buildManifestPath, JSON.stringify(buildManifest, null, 2));
    await (0, _writeatomic.writeFileAtomic)(middlewareBuildManifestPath, `self.__BUILD_MANIFEST=${JSON.stringify(buildManifest)};`);
    const interceptionRewrites = JSON.stringify(rewrites.beforeFiles.filter(_generateinterceptionroutesrewrites.isInterceptionRouteRewrite));
    await (0, _writeatomic.writeFileAtomic)(interceptionRewriteManifestPath, `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(interceptionRewrites)};`);
    const content = {
        __rewrites: rewrites ? (0, _buildmanifestplugin.normalizeRewritesForBuildManifest)(rewrites) : {
            afterFiles: [],
            beforeFiles: [],
            fallback: []
        },
        ...Object.fromEntries([
            ...currentEntrypoints.keys()
        ].map((pathname)=>[
                pathname,
                `static/chunks/pages${pathname === "/" ? "/index" : pathname}.js`
            ])),
        sortedPages: [
            ...currentEntrypoints.keys()
        ]
    };
    const buildManifestJs = `self.__BUILD_MANIFEST = ${JSON.stringify(content)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`;
    await (0, _writeatomic.writeFileAtomic)((0, _path.join)(distDir, "static", buildId, "_buildManifest.js"), buildManifestJs);
    await (0, _writeatomic.writeFileAtomic)((0, _path.join)(distDir, "static", buildId, "_ssgManifest.js"), _buildmanifestplugin.srcEmptySsgManifest);
}
async function writeFallbackBuildManifest(distDir, buildManifests) {
    const fallbackBuildManifest = mergeBuildManifests([
        buildManifests.get("_app"),
        buildManifests.get("_error")
    ].filter(Boolean));
    const fallbackBuildManifestPath = (0, _path.join)(distDir, `fallback-${_constants.BUILD_MANIFEST}`);
    (0, _nextjsrequirecachehotreloader.deleteCache)(fallbackBuildManifestPath);
    await (0, _writeatomic.writeFileAtomic)(fallbackBuildManifestPath, JSON.stringify(fallbackBuildManifest, null, 2));
}
async function writeAppBuildManifest(distDir, appBuildManifests) {
    const appBuildManifest = mergeAppBuildManifests(appBuildManifests.values());
    const appBuildManifestPath = (0, _path.join)(distDir, _constants.APP_BUILD_MANIFEST);
    (0, _nextjsrequirecachehotreloader.deleteCache)(appBuildManifestPath);
    await (0, _writeatomic.writeFileAtomic)(appBuildManifestPath, JSON.stringify(appBuildManifest, null, 2));
}
async function writePagesManifest(distDir, pagesManifests) {
    const pagesManifest = mergePagesManifests(pagesManifests.values());
    const pagesManifestPath = (0, _path.join)(distDir, "server", _constants.PAGES_MANIFEST);
    (0, _nextjsrequirecachehotreloader.deleteCache)(pagesManifestPath);
    await (0, _writeatomic.writeFileAtomic)(pagesManifestPath, JSON.stringify(pagesManifest, null, 2));
}
async function writeAppPathsManifest(distDir, appPathsManifests) {
    const appPathsManifest = mergePagesManifests(appPathsManifests.values());
    const appPathsManifestPath = (0, _path.join)(distDir, "server", _constants.APP_PATHS_MANIFEST);
    (0, _nextjsrequirecachehotreloader.deleteCache)(appPathsManifestPath);
    await (0, _writeatomic.writeFileAtomic)(appPathsManifestPath, JSON.stringify(appPathsManifest, null, 2));
}
async function writeMiddlewareManifest(distDir, middlewareManifests) {
    const middlewareManifest = mergeMiddlewareManifests(middlewareManifests.values());
    const middlewareManifestPath = (0, _path.join)(distDir, "server", _constants.MIDDLEWARE_MANIFEST);
    (0, _nextjsrequirecachehotreloader.deleteCache)(middlewareManifestPath);
    await (0, _writeatomic.writeFileAtomic)(middlewareManifestPath, JSON.stringify(middlewareManifest, null, 2));
}
async function writeActionManifest(distDir, actionManifests) {
    const actionManifest = await mergeActionManifests(actionManifests.values());
    const actionManifestJsonPath = (0, _path.join)(distDir, "server", `${_constants.SERVER_REFERENCE_MANIFEST}.json`);
    const actionManifestJsPath = (0, _path.join)(distDir, "server", `${_constants.SERVER_REFERENCE_MANIFEST}.js`);
    const json = JSON.stringify(actionManifest, null, 2);
    (0, _nextjsrequirecachehotreloader.deleteCache)(actionManifestJsonPath);
    (0, _nextjsrequirecachehotreloader.deleteCache)(actionManifestJsPath);
    await (0, _promises.writeFile)(actionManifestJsonPath, json, "utf-8");
    await (0, _promises.writeFile)(actionManifestJsPath, `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`, "utf-8");
}
async function writeNextFontManifest(distDir, fontManifests) {
    const fontManifest = mergeFontManifests(fontManifests.values());
    const json = JSON.stringify(fontManifest, null, 2);
    const fontManifestJsonPath = (0, _path.join)(distDir, "server", `${_constants.NEXT_FONT_MANIFEST}.json`);
    const fontManifestJsPath = (0, _path.join)(distDir, "server", `${_constants.NEXT_FONT_MANIFEST}.js`);
    (0, _nextjsrequirecachehotreloader.deleteCache)(fontManifestJsonPath);
    (0, _nextjsrequirecachehotreloader.deleteCache)(fontManifestJsPath);
    await (0, _writeatomic.writeFileAtomic)(fontManifestJsonPath, json);
    await (0, _writeatomic.writeFileAtomic)(fontManifestJsPath, `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`);
}
/**
 * Turbopack doesn't support this functionality, so it writes an empty manifest.
 */ async function writeAutomaticFontOptimizationManifest(distDir) {
    const manifestPath = (0, _path.join)(distDir, "server", _constants.AUTOMATIC_FONT_OPTIMIZATION_MANIFEST);
    await (0, _writeatomic.writeFileAtomic)(manifestPath, JSON.stringify([]));
}
async function writeLoadableManifest(distDir, loadableManifests) {
    const loadableManifest = mergeLoadableManifests(loadableManifests.values());
    const loadableManifestPath = (0, _path.join)(distDir, _constants.REACT_LOADABLE_MANIFEST);
    const middlewareloadableManifestPath = (0, _path.join)(distDir, "server", `${_constants.MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`);
    const json = JSON.stringify(loadableManifest, null, 2);
    (0, _nextjsrequirecachehotreloader.deleteCache)(loadableManifestPath);
    (0, _nextjsrequirecachehotreloader.deleteCache)(middlewareloadableManifestPath);
    await (0, _writeatomic.writeFileAtomic)(loadableManifestPath, json);
    await (0, _writeatomic.writeFileAtomic)(middlewareloadableManifestPath, `self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(json)}`);
}
async function writeManifests({ rewrites, distDir, buildId, buildManifests, appBuildManifests, pagesManifests, appPathsManifests, middlewareManifests, actionManifests, fontManifests, loadableManifests, currentEntrypoints }) {
    await writeBuildManifest(distDir, buildId, buildManifests, currentEntrypoints, rewrites);
    await writeAppBuildManifest(distDir, appBuildManifests);
    await writePagesManifest(distDir, pagesManifests);
    await writeAppPathsManifest(distDir, appPathsManifests);
    await writeMiddlewareManifest(distDir, middlewareManifests);
    await writeActionManifest(distDir, actionManifests);
    await writeNextFontManifest(distDir, fontManifests);
    await writeLoadableManifest(distDir, loadableManifests);
    await writeFallbackBuildManifest(distDir, buildManifests);
    await writeAutomaticFontOptimizationManifest(distDir);
}
class ModuleBuildError extends Error {
}
function issueKey(issue) {
    return [
        issue.severity,
        issue.filePath,
        JSON.stringify(issue.title),
        JSON.stringify(issue.description)
    ].join("-");
}
function formatIssue(issue) {
    const { filePath, title, description, source } = issue;
    let { documentationLink } = issue;
    let formattedTitle = renderStyledStringToErrorAnsi(title).replace(/\n/g, "\n    ");
    // TODO: Use error codes to identify these
    // TODO: Generalize adapting Turbopack errors to Next.js errors
    if (formattedTitle.includes("Module not found")) {
        // For compatiblity with webpack
        // TODO: include columns in webpack errors.
        documentationLink = "https://nextjs.org/docs/messages/module-not-found";
    }
    let formattedFilePath = filePath.replace("[project]/", "./").replaceAll("/./", "/").replace("\\\\?\\", "");
    let message;
    if (source && source.range) {
        const { start } = source.range;
        message = `${formattedFilePath}:${start.line + 1}:${start.column + 1}\n${formattedTitle}`;
    } else if (formattedFilePath) {
        message = `${formattedFilePath}\n${formattedTitle}`;
    } else {
        message = formattedTitle;
    }
    message += "\n";
    if ((source == null ? void 0 : source.range) && source.source.content) {
        const { start, end } = source.range;
        const { codeFrameColumns } = require("next/dist/compiled/babel/code-frame");
        message += codeFrameColumns(source.source.content, {
            start: {
                line: start.line + 1,
                column: start.column + 1
            },
            end: {
                line: end.line + 1,
                column: end.column + 1
            }
        }, {
            forceColor: true
        }).trim() + "\n\n";
    }
    if (description) {
        message += renderStyledStringToErrorAnsi(description) + "\n\n";
    }
    // TODO: make it possible to enable this for debugging, but not in tests.
    // if (detail) {
    //   message += renderStyledStringToErrorAnsi(detail) + '\n\n'
    // }
    // TODO: Include a trace from the issue.
    if (documentationLink) {
        message += documentationLink + "\n\n";
    }
    return message;
}
function processIssues(currentIssues, name, result, throwIssue = false) {
    const newIssues = new Map();
    currentIssues.set(name, newIssues);
    const relevantIssues = new Set();
    for (const issue of result.issues){
        if (issue.severity !== "error" && issue.severity !== "fatal") continue;
        const key = issueKey(issue);
        const formatted = formatIssue(issue);
        newIssues.set(key, issue);
        // We show errors in node_modules to the console, but don't throw for them
        if (/(^|\/)node_modules(\/|$)/.test(issue.filePath)) continue;
        relevantIssues.add(formatted);
    }
    if (relevantIssues.size && throwIssue) {
        throw new ModuleBuildError([
            ...relevantIssues
        ].join("\n\n"));
    }
}
function renderStyledStringToErrorAnsi(string) {
    function decodeMagicIdentifiers(str) {
        return str.replaceAll(_magicidentifier.MAGIC_IDENTIFIER_REGEX, (ident)=>{
            try {
                return (0, _picocolors.magenta)(`{${(0, _magicidentifier.decodeMagicIdentifier)(ident)}}`);
            } catch (e) {
                return (0, _picocolors.magenta)(`{${ident} (decoding failed: ${e})}`);
            }
        });
    }
    switch(string.type){
        case "text":
            return decodeMagicIdentifiers(string.value);
        case "strong":
            return (0, _picocolors.bold)((0, _picocolors.red)(decodeMagicIdentifiers(string.value)));
        case "code":
            return (0, _picocolors.green)(decodeMagicIdentifiers(string.value));
        case "line":
            return string.value.map(renderStyledStringToErrorAnsi).join("");
        case "stack":
            return string.value.map(renderStyledStringToErrorAnsi).join("\n");
        default:
            throw new Error("Unknown StyledString type", string);
    }
}
const MILLISECONDS_IN_NANOSECOND = 1000000;
function msToNs(ms) {
    return BigInt(Math.floor(ms)) * BigInt(MILLISECONDS_IN_NANOSECOND);
}
async function handleRouteType({ rewrites, distDir, buildId, globalEntrypoints, currentIssues, buildManifests, appBuildManifests, pagesManifests, appPathsManifests, middlewareManifests, actionManifests, fontManifests, loadableManifests, currentEntrypoints, handleRequireCacheClearing, changeSubscription, readyIds, page, route }) {
    switch(route.type){
        case "page":
            {
                try {
                    if (globalEntrypoints.app) {
                        const writtenEndpoint = await globalEntrypoints.app.writeToDisk();
                        handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("_app", writtenEndpoint);
                        processIssues(currentIssues, "_app", writtenEndpoint);
                    }
                    await loadBuildManifest(distDir, buildManifests, "_app");
                    await loadPagesManifest(distDir, pagesManifests, "_app");
                    if (globalEntrypoints.document) {
                        const writtenEndpoint = await globalEntrypoints.document.writeToDisk();
                        handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("_document", writtenEndpoint);
                        processIssues(currentIssues, "_document", writtenEndpoint);
                    }
                    await loadPagesManifest(distDir, pagesManifests, "_document");
                    const writtenEndpoint = await route.htmlEndpoint.writeToDisk();
                    handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing(page, writtenEndpoint);
                    const type = writtenEndpoint == null ? void 0 : writtenEndpoint.type;
                    await loadBuildManifest(distDir, buildManifests, page);
                    await loadPagesManifest(distDir, pagesManifests, page);
                    if (type === "edge") {
                        await loadMiddlewareManifest(distDir, middlewareManifests, page, "pages");
                    } else {
                        middlewareManifests.delete(page);
                    }
                    await loadFontManifest(distDir, fontManifests, page, "pages");
                    await loadLoadableManifest(distDir, loadableManifests, page, "pages");
                    await writeManifests({
                        rewrites,
                        distDir,
                        buildId,
                        buildManifests,
                        appBuildManifests,
                        pagesManifests,
                        appPathsManifests,
                        middlewareManifests,
                        actionManifests,
                        fontManifests,
                        loadableManifests,
                        currentEntrypoints
                    });
                    processIssues(currentIssues, page, writtenEndpoint);
                } finally{
                    changeSubscription == null ? void 0 : changeSubscription(page, "server", false, route.dataEndpoint, (pageName)=>{
                        // Report the next compilation again
                        readyIds == null ? void 0 : readyIds.delete(page);
                        return {
                            event: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ONLY_CHANGES,
                            pages: [
                                pageName
                            ]
                        };
                    });
                    changeSubscription == null ? void 0 : changeSubscription(page, "client", false, route.htmlEndpoint, ()=>{
                        return {
                            event: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.CLIENT_CHANGES
                        };
                    });
                    if (globalEntrypoints.document) {
                        changeSubscription == null ? void 0 : changeSubscription("_document", "server", false, globalEntrypoints.document, ()=>{
                            return {
                                action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE
                            };
                        });
                    }
                }
                break;
            }
        case "page-api":
            {
                const writtenEndpoint = await route.endpoint.writeToDisk();
                handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing(page, writtenEndpoint);
                const type = writtenEndpoint == null ? void 0 : writtenEndpoint.type;
                await loadPagesManifest(distDir, pagesManifests, page);
                if (type === "edge") {
                    await loadMiddlewareManifest(distDir, middlewareManifests, page, "pages");
                } else {
                    middlewareManifests.delete(page);
                }
                await loadLoadableManifest(distDir, loadableManifests, page, "pages");
                await writeManifests({
                    rewrites,
                    distDir,
                    buildId,
                    buildManifests,
                    appBuildManifests,
                    pagesManifests,
                    appPathsManifests,
                    middlewareManifests,
                    actionManifests,
                    fontManifests,
                    loadableManifests,
                    currentEntrypoints
                });
                processIssues(currentIssues, page, writtenEndpoint);
                break;
            }
        case "app-page":
            {
                const writtenEndpoint = await route.htmlEndpoint.writeToDisk();
                handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing(page, writtenEndpoint);
                changeSubscription == null ? void 0 : changeSubscription(page, "server", true, route.rscEndpoint, (_page, change)=>{
                    if (change.issues.some((issue)=>issue.severity === "error")) {
                        // Ignore any updates that has errors
                        // There will be another update without errors eventually
                        return;
                    }
                    // Report the next compilation again
                    readyIds == null ? void 0 : readyIds.delete(page);
                    return {
                        action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES
                    };
                });
                const type = writtenEndpoint == null ? void 0 : writtenEndpoint.type;
                if (type === "edge") {
                    await loadMiddlewareManifest(distDir, middlewareManifests, page, "app");
                } else {
                    middlewareManifests.delete(page);
                }
                await loadAppBuildManifest(distDir, appBuildManifests, page);
                await loadBuildManifest(distDir, buildManifests, page, "app");
                await loadAppPathManifest(distDir, appPathsManifests, page, "app");
                await loadActionManifest(distDir, actionManifests, page);
                await loadFontManifest(distDir, fontManifests, page, "app");
                await writeManifests({
                    rewrites,
                    distDir,
                    buildId,
                    buildManifests,
                    appBuildManifests,
                    pagesManifests,
                    appPathsManifests,
                    middlewareManifests,
                    actionManifests,
                    fontManifests,
                    loadableManifests,
                    currentEntrypoints
                });
                processIssues(currentIssues, page, writtenEndpoint, true);
                break;
            }
        case "app-route":
            {
                const writtenEndpoint = await route.endpoint.writeToDisk();
                handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing(page, writtenEndpoint);
                const type = writtenEndpoint == null ? void 0 : writtenEndpoint.type;
                await loadAppPathManifest(distDir, appPathsManifests, page, "app-route");
                if (type === "edge") {
                    await loadMiddlewareManifest(distDir, middlewareManifests, page, "app-route");
                } else {
                    middlewareManifests.delete(page);
                }
                await writeManifests({
                    rewrites,
                    distDir,
                    buildId,
                    buildManifests,
                    appBuildManifests,
                    pagesManifests,
                    appPathsManifests,
                    middlewareManifests,
                    actionManifests,
                    fontManifests,
                    loadableManifests,
                    currentEntrypoints
                });
                processIssues(currentIssues, page, writtenEndpoint, true);
                break;
            }
        default:
            {
                throw new Error(`unknown route type ${route.type} for ${page}`);
            }
    }
}
async function handleEntrypoints({ rewrites, nextConfig, entrypoints, serverFields, propagateServerField, distDir, buildId, globalEntrypoints, currentEntrypoints, changeSubscriptions, changeSubscription, clearChangeSubscription, sendHmr, startBuilding, handleRequireCacheClearing, prevMiddleware, currentIssues, buildManifests, appBuildManifests, pagesManifests, appPathsManifests, middlewareManifests, actionManifests, fontManifests, loadableManifests }) {
    globalEntrypoints.app = entrypoints.pagesAppEndpoint;
    globalEntrypoints.document = entrypoints.pagesDocumentEndpoint;
    globalEntrypoints.error = entrypoints.pagesErrorEndpoint;
    currentEntrypoints.clear();
    for (const [pathname, route] of entrypoints.routes){
        switch(route.type){
            case "page":
            case "page-api":
            case "app-page":
            case "app-route":
                {
                    currentEntrypoints.set(pathname, route);
                    break;
                }
            default:
                _log.info(`skipping ${pathname} (${route.type})`);
                break;
        }
    }
    if (changeSubscriptions) {
        for (const [pathname, subscriptionPromise] of changeSubscriptions){
            if (pathname === "") {
                continue;
            }
            if (!currentEntrypoints.has(pathname)) {
                const subscription = await subscriptionPromise;
                subscription.return == null ? void 0 : subscription.return.call(subscription);
                changeSubscriptions.delete(pathname);
            }
        }
    }
    const { middleware, instrumentation } = entrypoints;
    // We check for explicit true/false, since it's initialized to
    // undefined during the first loop (middlewareChanges event is
    // unnecessary during the first serve)
    if (prevMiddleware === true && !middleware) {
        // Went from middleware to no middleware
        await (clearChangeSubscription == null ? void 0 : clearChangeSubscription("middleware", "server"));
        sendHmr == null ? void 0 : sendHmr("middleware", {
            event: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES
        });
    } else if (prevMiddleware === false && middleware) {
        // Went from no middleware to middleware
        sendHmr == null ? void 0 : sendHmr("middleware", {
            event: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES
        });
    }
    if (nextConfig.experimental.instrumentationHook && instrumentation) {
        const processInstrumentation = async (displayName, name, prop)=>{
            const writtenEndpoint = await instrumentation[prop].writeToDisk();
            handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing(displayName, writtenEndpoint);
            processIssues(currentIssues, name, writtenEndpoint);
        };
        await processInstrumentation("instrumentation (node.js)", "instrumentation.nodeJs", "nodeJs");
        await processInstrumentation("instrumentation (edge)", "instrumentation.edge", "edge");
        await loadMiddlewareManifest(distDir, middlewareManifests, "instrumentation", "instrumentation");
        await writeManifests({
            rewrites: rewrites,
            distDir,
            buildId,
            buildManifests,
            appBuildManifests,
            pagesManifests,
            appPathsManifests,
            middlewareManifests,
            actionManifests,
            fontManifests,
            loadableManifests,
            currentEntrypoints
        });
        if (serverFields && propagateServerField) {
            serverFields.actualInstrumentationHookFile = "/instrumentation";
            await propagateServerField("actualInstrumentationHookFile", serverFields.actualInstrumentationHookFile);
        }
    } else {
        if (serverFields && propagateServerField) {
            serverFields.actualInstrumentationHookFile = undefined;
            await propagateServerField("actualInstrumentationHookFile", serverFields.actualInstrumentationHookFile);
        }
    }
    if (middleware) {
        const processMiddleware = async ()=>{
            const writtenEndpoint = await middleware.endpoint.writeToDisk();
            handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("middleware", writtenEndpoint);
            processIssues(currentIssues, "middleware", writtenEndpoint);
            await loadMiddlewareManifest(distDir, middlewareManifests, "middleware", "middleware");
            if (serverFields) {
                var _middlewareManifests_get;
                serverFields.middleware = {
                    match: null,
                    page: "/",
                    matchers: (_middlewareManifests_get = middlewareManifests.get("middleware")) == null ? void 0 : _middlewareManifests_get.middleware["/"].matchers
                };
            }
        };
        await processMiddleware();
        changeSubscription == null ? void 0 : changeSubscription("middleware", "server", false, middleware.endpoint, async ()=>{
            const finishBuilding = startBuilding == null ? void 0 : startBuilding("middleware", undefined, true);
            await processMiddleware();
            if (serverFields && propagateServerField) {
                await propagateServerField("actualMiddlewareFile", serverFields.actualMiddlewareFile);
                await propagateServerField("middleware", serverFields.middleware);
            }
            await writeManifests({
                rewrites: rewrites,
                distDir,
                buildId,
                buildManifests,
                appBuildManifests,
                pagesManifests,
                appPathsManifests,
                middlewareManifests,
                actionManifests,
                fontManifests,
                loadableManifests,
                currentEntrypoints
            });
            finishBuilding == null ? void 0 : finishBuilding();
            return {
                event: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES
            };
        });
        prevMiddleware = true;
    } else {
        middlewareManifests.delete("middleware");
        if (serverFields) {
            serverFields.actualMiddlewareFile = undefined;
            serverFields.middleware = undefined;
            prevMiddleware = false;
        }
    }
    if (serverFields && propagateServerField) {
        await propagateServerField("actualMiddlewareFile", serverFields.actualMiddlewareFile);
        await propagateServerField("middleware", serverFields.middleware);
    }
}
async function handlePagesErrorRoute({ rewrites, globalEntrypoints, currentIssues, distDir, buildId, buildManifests, pagesManifests, fontManifests, appBuildManifests, appPathsManifests, middlewareManifests, actionManifests, loadableManifests, currentEntrypoints, handleRequireCacheClearing, changeSubscription }) {
    if (globalEntrypoints.app) {
        const writtenEndpoint = await globalEntrypoints.app.writeToDisk();
        handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("_app", writtenEndpoint);
        processIssues(currentIssues, "_app", writtenEndpoint);
    }
    await loadBuildManifest(distDir, buildManifests, "_app");
    await loadPagesManifest(distDir, pagesManifests, "_app");
    await loadFontManifest(distDir, fontManifests, "_app");
    if (globalEntrypoints.document) {
        const writtenEndpoint = await globalEntrypoints.document.writeToDisk();
        handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("_document", writtenEndpoint);
        changeSubscription == null ? void 0 : changeSubscription("_document", "server", false, globalEntrypoints.document, ()=>{
            return {
                action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE
            };
        });
        processIssues(currentIssues, "_document", writtenEndpoint);
    }
    await loadPagesManifest(distDir, pagesManifests, "_document");
    if (globalEntrypoints.error) {
        const writtenEndpoint = await globalEntrypoints.error.writeToDisk();
        handleRequireCacheClearing == null ? void 0 : handleRequireCacheClearing("_error", writtenEndpoint);
        processIssues(currentIssues, "/_error", writtenEndpoint);
    }
    await loadBuildManifest(distDir, buildManifests, "_error");
    await loadPagesManifest(distDir, pagesManifests, "_error");
    await loadFontManifest(distDir, fontManifests, "_error");
    await writeManifests({
        rewrites,
        distDir,
        buildId,
        buildManifests,
        appBuildManifests,
        pagesManifests,
        appPathsManifests,
        middlewareManifests,
        actionManifests,
        fontManifests,
        loadableManifests,
        currentEntrypoints
    });
}

//# sourceMappingURL=turbopack-utils.js.map