"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "default", {
    enumerable: true,
    get: function() {
        return DevServer;
    }
});
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _jestworker = require("next/dist/compiled/jest-worker");
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _path = require("path");
const _watchpack = /*#__PURE__*/ _interop_require_default(require("watchpack"));
const _output = require("../../build/output");
const _constants = require("../../lib/constants");
const _fileexists = require("../../lib/file-exists");
const _findpagesdir = require("../../lib/find-pages-dir");
const _loadcustomroutes = /*#__PURE__*/ _interop_require_default(require("../../lib/load-custom-routes"));
const _verifyTypeScriptSetup = require("../../lib/verifyTypeScriptSetup");
const _verifypartytownsetup = require("../../lib/verify-partytown-setup");
const _constants1 = require("../../shared/lib/constants");
const _nextserver = /*#__PURE__*/ _interop_require_wildcard(require("../next-server"));
const _routematcher = require("../../shared/lib/router/utils/route-matcher");
const _middlewareroutematcher = require("../../shared/lib/router/utils/middleware-route-matcher");
const _normalizepagepath = require("../../shared/lib/page-path/normalize-page-path");
const _absolutepathtopage = require("../../shared/lib/page-path/absolute-path-to-page");
const _router = /*#__PURE__*/ _interop_require_default(require("../router"));
const _pathmatch = require("../../shared/lib/router/utils/path-match");
const _pathhasprefix = require("../../shared/lib/router/utils/path-has-prefix");
const _removepathprefix = require("../../shared/lib/router/utils/remove-path-prefix");
const _events = require("../../telemetry/events");
const _storage = require("../../telemetry/storage");
const _trace = require("../../trace");
const _findpagefile = require("../lib/find-page-file");
const _utils = require("../lib/utils");
const _coalescedfunction = require("../../lib/coalesced-function");
const _loadcomponents = require("../load-components");
const _utils1 = require("../../shared/lib/utils");
const _middleware = require("next/dist/compiled/@next/react-dev-overlay/dist/middleware");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
const _iserror = /*#__PURE__*/ _interop_require_wildcard(require("../../lib/is-error"));
const _routeregex = require("../../shared/lib/router/utils/route-regex");
const _utils2 = require("../../shared/lib/router/utils");
const _entries = require("../../build/entries");
const _normalizepathsep = require("../../shared/lib/page-path/normalize-path-sep");
const _apppaths = require("../../shared/lib/router/utils/app-paths");
const _utils3 = require("../../build/utils");
const _loadjsconfig = /*#__PURE__*/ _interop_require_default(require("../../build/load-jsconfig"));
const _formatservererror = require("../../lib/format-server-error");
const _shared = require("../../build/webpack/plugins/next-types-plugin/shared");
const _devroutematchermanager = require("../future/route-matcher-managers/dev-route-matcher-manager");
const _devpagesroutematcherprovider = require("../future/route-matcher-providers/dev/dev-pages-route-matcher-provider");
const _devpagesapiroutematcherprovider = require("../future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider");
const _devapppageroutematcherprovider = require("../future/route-matcher-providers/dev/dev-app-page-route-matcher-provider");
const _devapprouteroutematcherprovider = require("../future/route-matcher-providers/dev/dev-app-route-route-matcher-provider");
const _nodemanifestloader = require("../future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader");
const _cachedfilereader = require("../future/route-matcher-providers/dev/helpers/file-reader/cached-file-reader");
const _defaultfilereader = require("../future/route-matcher-providers/dev/helpers/file-reader/default-file-reader");
const _buildcontext = require("../../build/build-context");
const _logappdirerror = require("./log-app-dir-error");
const _createclientrouterfilter = require("../../lib/create-client-router-filter");
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _render = require("../render");
const _invokerequest = require("../lib/server-ipc/invoke-request");
const _generateinterceptionroutesrewrites = require("../../lib/generate-interception-routes-rewrites");
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;
}
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl;
const ReactDevOverlay = (props)=>{
    if (ReactDevOverlayImpl === undefined) {
        ReactDevOverlayImpl = require("next/dist/compiled/@next/react-dev-overlay/dist/client").ReactDevOverlay;
    }
    return ReactDevOverlayImpl(props);
};
class DevServer extends _nextserver.default {
    getStaticPathsWorker() {
        const worker = new _jestworker.Worker(require.resolve("./static-paths-worker"), {
            maxRetries: 1,
            // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.
            // This helps reusing the memory a lot.
            numWorkers: 1,
            enableWorkerThreads: this.nextConfig.experimental.workerThreads,
            forkOptions: {
                env: {
                    ...process.env,
                    // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers
                    // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
                    // the number of workers Next.js tries to launch. The only worker users are interested in debugging
                    // is the main Next.js one
                    NODE_OPTIONS: (0, _utils.getNodeOptionsWithoutInspect)()
                }
            }
        });
        worker.getStdout().pipe(process.stdout);
        worker.getStderr().pipe(process.stderr);
        return worker;
    }
    constructor(options){
        var _this_nextConfig_experimental, _this_nextConfig_experimental_amp;
        try {
            // Increase the number of stack frames on the server
            Error.stackTraceLimit = 50;
        } catch  {}
        super({
            ...options,
            dev: true
        });
        this.addedUpgradeListener = false;
        this.originalFetch = global.fetch;
        this.renderOpts.dev = true;
        this.renderOpts.appDirDevErrorLogger = (err)=>this.logErrorWithOriginalStack(err, "app-dir");
        this.renderOpts.ErrorDebug = ReactDevOverlay;
        this.devReady = new Promise((resolve)=>{
            this.setDevReady = resolve;
        });
        this.staticPathsCache = new _lrucache.default({
            // 5MB
            max: 5 * 1024 * 1024,
            length (value) {
                return JSON.stringify(value.staticPaths).length;
            }
        });
        this.renderOpts.ampSkipValidation = ((_this_nextConfig_experimental = this.nextConfig.experimental) == null ? void 0 : (_this_nextConfig_experimental_amp = _this_nextConfig_experimental.amp) == null ? void 0 : _this_nextConfig_experimental_amp.skipValidation) ?? false;
        this.renderOpts.ampValidator = (html, pathname)=>{
            const validatorPath = this.nextConfig.experimental && this.nextConfig.experimental.amp && this.nextConfig.experimental.amp.validator;
            const AmpHtmlValidator = require("next/dist/compiled/amphtml-validator");
            return AmpHtmlValidator.getInstance(validatorPath).then((validator)=>{
                const result = validator.validateString(html);
                (0, _output.ampValidation)(pathname, result.errors.filter((e)=>e.severity === "ERROR").filter((e)=>this._filterAmpDevelopmentScript(html, e)), result.errors.filter((e)=>e.severity !== "ERROR"));
            });
        };
        if (_fs.default.existsSync((0, _path.join)(this.dir, "static"))) {
            _log.warn(`The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`);
        }
        // setup upgrade listener eagerly when we can otherwise
        // it will be done on the first request via req.socket.server
        if (options.httpServer) {
            this.setupWebSocketHandler(options.httpServer);
        }
        this.isCustomServer = !options.isNextDevCommand;
        const { pagesDir , appDir  } = (0, _findpagesdir.findPagesDir)(this.dir, !!this.nextConfig.experimental.appDir);
        this.pagesDir = pagesDir;
        this.appDir = appDir;
    }
    getRoutes() {
        const { pagesDir , appDir  } = (0, _findpagesdir.findPagesDir)(this.dir, !!this.nextConfig.experimental.appDir);
        const ensurer = {
            ensure: async (match)=>{
                await this.ensurePage({
                    match,
                    page: match.definition.page,
                    clientOnly: false
                });
            }
        };
        const routes = super.getRoutes();
        const matchers = new _devroutematchermanager.DevRouteMatcherManager(routes.matchers, ensurer, this.dir);
        const handlers = routes.handlers;
        const extensions = this.nextConfig.pageExtensions;
        const fileReader = new _cachedfilereader.CachedFileReader(new _defaultfilereader.DefaultFileReader());
        // If the pages directory is available, then configure those matchers.
        if (pagesDir) {
            matchers.push(new _devpagesroutematcherprovider.DevPagesRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
            matchers.push(new _devpagesapiroutematcherprovider.DevPagesAPIRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
        }
        if (appDir) {
            matchers.push(new _devapppageroutematcherprovider.DevAppPageRouteMatcherProvider(appDir, extensions, fileReader));
            matchers.push(new _devapprouteroutematcherprovider.DevAppRouteRouteMatcherProvider(appDir, extensions, fileReader));
        }
        return {
            matchers,
            handlers
        };
    }
    getBuildId() {
        return "development";
    }
    async addExportPathMapRoutes() {
        // Makes `next export` exportPathMap work in development mode.
        // So that the user doesn't have to define a custom server reading the exportPathMap
        if (this.nextConfig.exportPathMap) {
            _log.info("Defining routes from exportPathMap");
            const exportPathMap = await this.nextConfig.exportPathMap({}, {
                dev: true,
                dir: this.dir,
                outDir: null,
                distDir: this.distDir,
                buildId: this.buildId
            });
            // In development we can't give a default path mapping
            for(const path in exportPathMap){
                const { page , query ={}  } = exportPathMap[path];
                this.router.addFsRoute({
                    match: (0, _pathmatch.getPathMatch)(path),
                    type: "route",
                    name: `${path} exportpathmap route`,
                    fn: async (req, res, _params, parsedUrl)=>{
                        const { query: urlQuery  } = parsedUrl;
                        Object.keys(urlQuery).filter((key)=>query[key] === undefined).forEach((key)=>_log.warn(`Url '${path}' defines a query parameter '${key}' that is missing in exportPathMap`));
                        const mergedQuery = {
                            ...urlQuery,
                            ...query
                        };
                        await this.render(req, res, page, mergedQuery, parsedUrl, true);
                        return {
                            finished: true
                        };
                    }
                });
            }
        }
    }
    async startWatcher() {
        if (this.webpackWatcher) {
            return;
        }
        const validFileMatcher = (0, _findpagefile.createValidFileMatcher)(this.nextConfig.pageExtensions, this.appDir);
        let resolved = false;
        return new Promise(async (resolve, reject)=>{
            if (this.pagesDir) {
                // Watchpack doesn't emit an event for an empty directory
                _fs.default.readdir(this.pagesDir, (_, files)=>{
                    if (files == null ? void 0 : files.length) {
                        return;
                    }
                    if (!resolved) {
                        resolve();
                        resolved = true;
                    }
                });
            }
            const pages = this.pagesDir ? [
                this.pagesDir
            ] : [];
            const app = this.appDir ? [
                this.appDir
            ] : [];
            const directories = [
                ...pages,
                ...app
            ];
            const rootDir = this.pagesDir || this.appDir;
            const files = [
                ...(0, _utils3.getPossibleMiddlewareFilenames)((0, _path.join)(rootDir, ".."), this.nextConfig.pageExtensions),
                ...(0, _utils3.getPossibleInstrumentationHookFilenames)((0, _path.join)(rootDir, ".."), this.nextConfig.pageExtensions)
            ];
            let nestedMiddleware = [];
            const envFiles = [
                ".env.development.local",
                ".env.local",
                ".env.development",
                ".env"
            ].map((file)=>(0, _path.join)(this.dir, file));
            files.push(...envFiles);
            // tsconfig/jsconfig paths hot-reloading
            const tsconfigPaths = [
                (0, _path.join)(this.dir, "tsconfig.json"),
                (0, _path.join)(this.dir, "jsconfig.json")
            ];
            files.push(...tsconfigPaths);
            const wp = this.webpackWatcher = new _watchpack.default({
                ignored: (pathname)=>{
                    return !files.some((file)=>file.startsWith(pathname)) && !directories.some((dir)=>pathname.startsWith(dir) || dir.startsWith(pathname));
                }
            });
            wp.watch({
                directories: [
                    this.dir
                ],
                startTime: 0
            });
            const fileWatchTimes = new Map();
            let enabledTypeScript = this.usingTypeScript;
            let previousClientRouterFilters;
            let previousConflictingPagePaths = new Set();
            wp.on("aggregated", async ()=>{
                let middlewareMatchers;
                const routedPages = [];
                const knownFiles = wp.getTimeInfoEntries();
                const appPaths = {};
                const pageNameSet = new Set();
                const conflictingAppPagePaths = new Set();
                const appPageFilePaths = new Map();
                const pagesPageFilePaths = new Map();
                let envChange = false;
                let clientRouterFilterChange = false;
                let tsconfigChange = false;
                let conflictingPageChange = 0;
                _shared.devPageFiles.clear();
                for (const [fileName, meta] of knownFiles){
                    if (!files.includes(fileName) && !directories.some((dir)=>fileName.startsWith(dir))) {
                        continue;
                    }
                    const watchTime = fileWatchTimes.get(fileName);
                    const watchTimeChange = watchTime && watchTime !== (meta == null ? void 0 : meta.timestamp);
                    fileWatchTimes.set(fileName, meta.timestamp);
                    if (envFiles.includes(fileName)) {
                        if (watchTimeChange) {
                            envChange = true;
                        }
                        continue;
                    }
                    if (tsconfigPaths.includes(fileName)) {
                        if (fileName.endsWith("tsconfig.json")) {
                            enabledTypeScript = true;
                        }
                        if (watchTimeChange) {
                            tsconfigChange = true;
                        }
                        continue;
                    }
                    if ((meta == null ? void 0 : meta.accuracy) === undefined || !validFileMatcher.isPageFile(fileName)) {
                        continue;
                    }
                    const isAppPath = Boolean(this.appDir && (0, _normalizepathsep.normalizePathSep)(fileName).startsWith((0, _normalizepathsep.normalizePathSep)(this.appDir)));
                    _shared.devPageFiles.add(fileName);
                    const rootFile = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
                        dir: this.dir,
                        extensions: this.nextConfig.pageExtensions,
                        keepIndex: false,
                        pagesType: "root"
                    });
                    if ((0, _utils3.isMiddlewareFile)(rootFile)) {
                        var _staticInfo_middleware;
                        const staticInfo = await this.getStaticInfo({
                            fileName,
                            rootFile,
                            isAppPath
                        });
                        if (this.nextConfig.output === "export") {
                            _log.error('Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
                            continue;
                        }
                        this.actualMiddlewareFile = rootFile;
                        middlewareMatchers = ((_staticInfo_middleware = staticInfo.middleware) == null ? void 0 : _staticInfo_middleware.matchers) || [
                            {
                                regexp: ".*",
                                originalSource: "/:path*"
                            }
                        ];
                        continue;
                    }
                    if ((0, _utils3.isInstrumentationHookFile)(rootFile) && this.nextConfig.experimental.instrumentationHook) {
                        this.actualInstrumentationHookFile = rootFile;
                        continue;
                    }
                    if (fileName.endsWith(".ts") || fileName.endsWith(".tsx")) {
                        enabledTypeScript = true;
                    }
                    let pageName = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
                        dir: isAppPath ? this.appDir : this.pagesDir,
                        extensions: this.nextConfig.pageExtensions,
                        keepIndex: isAppPath,
                        pagesType: isAppPath ? "app" : "pages"
                    });
                    if (!isAppPath && pageName.startsWith("/api/") && this.nextConfig.output === "export") {
                        _log.error('API Routes cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
                        continue;
                    }
                    if (isAppPath) {
                        if (!validFileMatcher.isAppRouterPage(fileName) && !validFileMatcher.isRootNotFound(fileName)) {
                            continue;
                        }
                        // Ignore files/directories starting with `_` in the app directory
                        if ((0, _normalizepathsep.normalizePathSep)(pageName).includes("/_")) {
                            continue;
                        }
                        const originalPageName = pageName;
                        pageName = (0, _apppaths.normalizeAppPath)(pageName).replace(/%5F/g, "_");
                        if (!appPaths[pageName]) {
                            appPaths[pageName] = [];
                        }
                        appPaths[pageName].push(originalPageName);
                        if (routedPages.includes(pageName)) {
                            continue;
                        }
                    } else {
                        // /index is preserved for root folder
                        pageName = pageName.replace(/\/index$/, "") || "/";
                    }
                    (isAppPath ? appPageFilePaths : pagesPageFilePaths).set(pageName, fileName);
                    if (this.appDir && pageNameSet.has(pageName)) {
                        conflictingAppPagePaths.add(pageName);
                    } else {
                        pageNameSet.add(pageName);
                    }
                    /**
           * If there is a middleware that is not declared in the root we will
           * warn without adding it so it doesn't make its way into the system.
           */ if (/[\\\\/]_middleware$/.test(pageName)) {
                        nestedMiddleware.push(pageName);
                        continue;
                    }
                    routedPages.push(pageName);
                }
                const numConflicting = conflictingAppPagePaths.size;
                conflictingPageChange = numConflicting - previousConflictingPagePaths.size;
                if (conflictingPageChange !== 0) {
                    if (numConflicting > 0) {
                        var _this_hotReloader;
                        let errorMessage = `Conflicting app and page file${numConflicting === 1 ? " was" : "s were"} found, please remove the conflicting files to continue:\n`;
                        for (const p of conflictingAppPagePaths){
                            const appPath = (0, _path.relative)(this.dir, appPageFilePaths.get(p));
                            const pagesPath = (0, _path.relative)(this.dir, pagesPageFilePaths.get(p));
                            errorMessage += `  "${pagesPath}" - "${appPath}"\n`;
                        }
                        (_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.setHmrServerError(new Error(errorMessage));
                    } else if (numConflicting === 0) {
                        var _this_hotReloader1;
                        await this.matchers.reload();
                        (_this_hotReloader1 = this.hotReloader) == null ? void 0 : _this_hotReloader1.clearHmrServerError();
                    }
                }
                previousConflictingPagePaths = conflictingAppPagePaths;
                let clientRouterFilters;
                if (this.nextConfig.experimental.clientRouterFilter) {
                    clientRouterFilters = (0, _createclientrouterfilter.createClientRouterFilter)(Object.keys(appPaths), this.nextConfig.experimental.clientRouterFilterRedirects ? (this.nextConfig._originalRedirects || []).filter((r)=>!r.internal) : [], this.nextConfig.experimental.clientRouterFilterAllowedRate);
                    if (!previousClientRouterFilters || JSON.stringify(previousClientRouterFilters) !== JSON.stringify(clientRouterFilters)) {
                        clientRouterFilterChange = true;
                        previousClientRouterFilters = clientRouterFilters;
                    }
                }
                if (!this.usingTypeScript && enabledTypeScript && !this.isRenderWorker) {
                    // we tolerate the error here as this is best effort
                    // and the manual install command will be shown
                    await this.verifyTypeScript().then(()=>{
                        tsconfigChange = true;
                    }).catch(()=>{});
                }
                if (clientRouterFilterChange || envChange || tsconfigChange) {
                    var _this_hotReloader2, _this_hotReloader_activeConfigs, _this_hotReloader3;
                    if (envChange) {
                        this.loadEnvConfig({
                            dev: true,
                            forceReload: true,
                            silent: !!process.env.__NEXT_PRIVATE_RENDER_WORKER
                        });
                    }
                    let tsconfigResult;
                    if (tsconfigChange) {
                        try {
                            tsconfigResult = await (0, _loadjsconfig.default)(this.dir, this.nextConfig);
                        } catch (_) {
                        /* do we want to log if there are syntax errors in tsconfig  while editing? */ }
                    }
                    (_this_hotReloader2 = this.hotReloader) == null ? void 0 : (_this_hotReloader_activeConfigs = _this_hotReloader2.activeConfigs) == null ? void 0 : _this_hotReloader_activeConfigs.forEach((config, idx)=>{
                        const isClient = idx === 0;
                        const isNodeServer = idx === 1;
                        const isEdgeServer = idx === 2;
                        const hasRewrites = this.customRoutes.rewrites.afterFiles.length > 0 || this.customRoutes.rewrites.beforeFiles.length > 0 || this.customRoutes.rewrites.fallback.length > 0;
                        if (tsconfigChange) {
                            var _config_resolve, _config_resolve_plugins;
                            (_config_resolve = config.resolve) == null ? void 0 : (_config_resolve_plugins = _config_resolve.plugins) == null ? void 0 : _config_resolve_plugins.forEach((plugin)=>{
                                // look for the JsConfigPathsPlugin and update with
                                // the latest paths/baseUrl config
                                if (plugin && plugin.jsConfigPlugin && tsconfigResult) {
                                    var _config_resolve, _config_resolve_modules, _jsConfig_compilerOptions;
                                    const { resolvedBaseUrl , jsConfig  } = tsconfigResult;
                                    const currentResolvedBaseUrl = plugin.resolvedBaseUrl;
                                    const resolvedUrlIndex = (_config_resolve = config.resolve) == null ? void 0 : (_config_resolve_modules = _config_resolve.modules) == null ? void 0 : _config_resolve_modules.findIndex((item)=>item === currentResolvedBaseUrl);
                                    if (resolvedBaseUrl && resolvedBaseUrl !== currentResolvedBaseUrl) {
                                        var _config_resolve1, _config_resolve_modules1;
                                        // remove old baseUrl and add new one
                                        if (resolvedUrlIndex && resolvedUrlIndex > -1) {
                                            var _config_resolve2, _config_resolve_modules2;
                                            (_config_resolve2 = config.resolve) == null ? void 0 : (_config_resolve_modules2 = _config_resolve2.modules) == null ? void 0 : _config_resolve_modules2.splice(resolvedUrlIndex, 1);
                                        }
                                        (_config_resolve1 = config.resolve) == null ? void 0 : (_config_resolve_modules1 = _config_resolve1.modules) == null ? void 0 : _config_resolve_modules1.push(resolvedBaseUrl);
                                    }
                                    if ((jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.paths) && resolvedBaseUrl) {
                                        Object.keys(plugin.paths).forEach((key)=>{
                                            delete plugin.paths[key];
                                        });
                                        Object.assign(plugin.paths, jsConfig.compilerOptions.paths);
                                        plugin.resolvedBaseUrl = resolvedBaseUrl;
                                    }
                                }
                            });
                        }
                        if (envChange || clientRouterFilterChange) {
                            var _config_plugins;
                            (_config_plugins = config.plugins) == null ? void 0 : _config_plugins.forEach((plugin)=>{
                                // we look for the DefinePlugin definitions so we can
                                // update them on the active compilers
                                if (plugin && typeof plugin.definitions === "object" && plugin.definitions.__NEXT_DEFINE_ENV) {
                                    const { getDefineEnv  } = require("../../build/webpack-config");
                                    const newDefine = getDefineEnv({
                                        dev: true,
                                        config: this.nextConfig,
                                        distDir: this.distDir,
                                        isClient,
                                        hasRewrites,
                                        isNodeServer,
                                        isEdgeServer,
                                        clientRouterFilters
                                    });
                                    Object.keys(plugin.definitions).forEach((key)=>{
                                        if (!(key in newDefine)) {
                                            delete plugin.definitions[key];
                                        }
                                    });
                                    Object.assign(plugin.definitions, newDefine);
                                }
                            });
                        }
                    });
                    (_this_hotReloader3 = this.hotReloader) == null ? void 0 : _this_hotReloader3.invalidate({
                        reloadAfterInvalidation: envChange
                    });
                }
                if (nestedMiddleware.length > 0) {
                    _log.error(new _utils3.NestedMiddlewareError(nestedMiddleware, this.dir, this.pagesDir || this.appDir).message);
                    nestedMiddleware = [];
                }
                // Make sure to sort parallel routes to make the result deterministic.
                this.appPathRoutes = Object.fromEntries(Object.entries(appPaths).map(([k, v])=>[
                        k,
                        v.sort()
                    ]));
                this.middleware = middlewareMatchers ? {
                    match: (0, _middlewareroutematcher.getMiddlewareRouteMatcher)(middlewareMatchers),
                    page: "/",
                    matchers: middlewareMatchers
                } : undefined;
                this.customRoutes = await (0, _loadcustomroutes.default)(this.nextConfig);
                const { rewrites  } = this.customRoutes;
                this.customRoutes.rewrites.beforeFiles.push(...(0, _generateinterceptionroutesrewrites.generateInterceptionRoutesRewrites)(Object.keys(appPaths)));
                if (rewrites.beforeFiles.length || rewrites.afterFiles.length || rewrites.fallback.length) {
                    this.router.setRewrites(this.generateRewrites({
                        restrictedRedirectPaths: []
                    }));
                }
                try {
                    var _this_sortedRoutes;
                    // we serve a separate manifest with all pages for the client in
                    // dev mode so that we can match a page after a rewrite on the client
                    // before it has been built and is populated in the _buildManifest
                    const sortedRoutes = (0, _utils2.getSortedRoutes)(routedPages);
                    this.dynamicRoutes = sortedRoutes.map((page)=>{
                        const regex = (0, _routeregex.getRouteRegex)(page);
                        return {
                            match: (0, _routematcher.getRouteMatcher)(regex),
                            page,
                            re: regex.re
                        };
                    }).filter(Boolean);
                    if (!((_this_sortedRoutes = this.sortedRoutes) == null ? void 0 : _this_sortedRoutes.every((val, idx)=>val === sortedRoutes[idx]))) {
                        var // emit the change so clients fetch the update
                        _this_hotReloader4;
                        (_this_hotReloader4 = this.hotReloader) == null ? void 0 : _this_hotReloader4.send("devPagesManifestUpdate", {
                            devPagesManifest: true
                        });
                    }
                    this.sortedRoutes = sortedRoutes;
                    this.router.setCatchallMiddleware(this.generateCatchAllMiddlewareRoute(true));
                    if (!resolved) {
                        resolve();
                        resolved = true;
                    }
                } catch (e) {
                    if (!resolved) {
                        reject(e);
                        resolved = true;
                    } else {
                        _log.warn("Failed to reload dynamic routes:", e);
                    }
                } finally{
                    // Reload the matchers. The filesystem would have been written to,
                    // and the matchers need to re-scan it to update the router.
                    await this.matchers.reload();
                }
            });
        });
    }
    async stopWatcher() {
        if (!this.webpackWatcher) {
            return;
        }
        this.webpackWatcher.close();
        this.webpackWatcher = null;
    }
    async verifyTypeScript() {
        if (this.verifyingTypeScript) {
            return;
        }
        try {
            this.verifyingTypeScript = true;
            const verifyResult = await (0, _verifyTypeScriptSetup.verifyTypeScriptSetup)({
                dir: this.dir,
                distDir: this.nextConfig.distDir,
                intentDirs: [
                    this.pagesDir,
                    this.appDir
                ].filter(Boolean),
                typeCheckPreflight: false,
                tsconfigPath: this.nextConfig.typescript.tsconfigPath,
                disableStaticImages: this.nextConfig.images.disableStaticImages,
                hasAppDir: !!this.appDir,
                hasPagesDir: !!this.pagesDir
            });
            if (verifyResult.version) {
                this.usingTypeScript = true;
            }
        } finally{
            this.verifyingTypeScript = false;
        }
    }
    async prepareImpl() {
        var _this_hotReloader;
        (0, _trace.setGlobal)("distDir", this.distDir);
        (0, _trace.setGlobal)("phase", _constants1.PHASE_DEVELOPMENT_SERVER);
        if (!this.isRenderWorker) {
            await this.verifyTypeScript();
        }
        this.customRoutes = await (0, _loadcustomroutes.default)(this.nextConfig);
        // reload router
        const { redirects , rewrites , headers  } = this.customRoutes;
        if (rewrites.beforeFiles.length || rewrites.afterFiles.length || rewrites.fallback.length || redirects.length || headers.length) {
            this.router = new _router.default(this.generateRoutes(true));
        }
        const telemetry = new _storage.Telemetry({
            distDir: this.distDir
        });
        // router worker does not start webpack compilers
        if (!this.isRenderWorker) {
            const { default: HotReloader  } = require("./hot-reloader");
            this.hotReloader = new HotReloader(this.dir, {
                pagesDir: this.pagesDir,
                distDir: this.distDir,
                config: this.nextConfig,
                previewProps: this.getPrerenderManifest().preview,
                buildId: this.buildId,
                rewrites,
                appDir: this.appDir,
                telemetry
            });
        }
        await super.prepareImpl();
        await this.addExportPathMapRoutes();
        await ((_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.start());
        await this.startWatcher();
        await this.runInstrumentationHookIfAvailable();
        await this.matchers.reload();
        this.setDevReady();
        if (this.nextConfig.experimental.nextScriptWorkers) {
            await (0, _verifypartytownsetup.verifyPartytownSetup)(this.dir, (0, _path.join)(this.distDir, _constants1.CLIENT_STATIC_FILES_PATH));
        }
        // This is required by the tracing subsystem.
        (0, _trace.setGlobal)("appDir", this.appDir);
        (0, _trace.setGlobal)("pagesDir", this.pagesDir);
        (0, _trace.setGlobal)("telemetry", telemetry);
        const isSrcDir = (0, _path.relative)(this.dir, this.pagesDir || this.appDir || "").startsWith("src");
        if (!this.isRenderWorker) {
            telemetry.record((0, _events.eventCliSession)(this.distDir, this.nextConfig, {
                webpackVersion: 5,
                cliCommand: "dev",
                isSrcDir,
                hasNowJson: !!await (0, _findup.default)("now.json", {
                    cwd: this.dir
                }),
                isCustomServer: this.isCustomServer,
                turboFlag: false,
                pagesDir: !!this.pagesDir,
                appDir: !!this.appDir
            }));
        }
        process.on("unhandledRejection", (reason)=>{
            this.logErrorWithOriginalStack(reason, "unhandledRejection").catch(()=>{});
        });
        process.on("uncaughtException", (err)=>{
            this.logErrorWithOriginalStack(err, "uncaughtException").catch(()=>{});
        });
    }
    async close() {
        await this.stopWatcher();
        if (this.hotReloader) {
            await this.hotReloader.stop();
        }
    }
    async hasPage(pathname) {
        let normalizedPath;
        try {
            normalizedPath = (0, _normalizepagepath.normalizePagePath)(pathname);
        } catch (err) {
            console.error(err);
            // if normalizing the page fails it means it isn't valid
            // so it doesn't exist so don't throw and return false
            // to ensure we return 404 instead of 500
            return false;
        }
        if ((0, _utils3.isMiddlewareFile)(normalizedPath)) {
            return (0, _findpagefile.findPageFile)(this.dir, normalizedPath, this.nextConfig.pageExtensions, false).then(Boolean);
        }
        let appFile = null;
        let pagesFile = null;
        if (this.appDir) {
            appFile = await (0, _findpagefile.findPageFile)(this.appDir, normalizedPath + "/page", this.nextConfig.pageExtensions, true);
        }
        if (this.pagesDir) {
            pagesFile = await (0, _findpagefile.findPageFile)(this.pagesDir, normalizedPath, this.nextConfig.pageExtensions, false);
        }
        if (appFile && pagesFile) {
            return false;
        }
        return Boolean(appFile || pagesFile);
    }
    async _beforeCatchAllRender(req, res, params, parsedUrl) {
        const { pathname  } = parsedUrl;
        const pathParts = params.path || [];
        const path = `/${pathParts.join("/")}`;
        // check for a public file, throwing error if there's a
        // conflicting page
        let decodedPath;
        try {
            decodedPath = decodeURIComponent(path);
        } catch (_) {
            throw new _utils1.DecodeError("failed to decode param");
        }
        if (await this.hasPublicFile(decodedPath)) {
            const match = await this.matchers.match(pathname, {
                skipDynamic: true
            });
            if (match) {
                const err = new Error(`A conflicting public file and page file was found for path ${pathname} https://nextjs.org/docs/messages/conflicting-public-file-page`);
                res.statusCode = 500;
                await this.renderError(err, req, res, pathname, {});
                return true;
            }
            await this.servePublic(req, res, pathParts);
            return true;
        }
        return false;
    }
    setupWebSocketHandler(server, _req) {
        if (!this.addedUpgradeListener) {
            var _ref;
            this.addedUpgradeListener = true;
            server = server || ((_ref = _req == null ? void 0 : _req.originalRequest.socket) == null ? void 0 : _ref.server);
            if (!server) {
                // this is very unlikely to happen but show an error in case
                // it does somehow
                _log.error(`Invalid IncomingMessage received, make sure http.createServer is being used to handle requests.`);
            } else {
                const { basePath  } = this.nextConfig;
                server.on("upgrade", async (req, socket, head)=>{
                    var _req_url;
                    let assetPrefix = (this.nextConfig.assetPrefix || "").replace(/^\/+/, "");
                    // assetPrefix can be a proxy server with a url locally
                    // if so, it's needed to send these HMR requests with a rewritten url directly to /_next/webpack-hmr
                    // otherwise account for a path-like prefix when listening to socket events
                    if (assetPrefix.startsWith("http")) {
                        assetPrefix = "";
                    } else if (assetPrefix) {
                        assetPrefix = `/${assetPrefix}`;
                    }
                    if ((_req_url = req.url) == null ? void 0 : _req_url.startsWith(`${basePath || assetPrefix || ""}/_next/webpack-hmr`)) {
                        if (!this.isRenderWorker) {
                            var _this_hotReloader;
                            (_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.onHMR(req, socket, head);
                        }
                    } else {
                        this.handleUpgrade(req, socket, head);
                    }
                });
            }
        }
    }
    async runMiddleware(params) {
        try {
            const result = await super.runMiddleware({
                ...params,
                onWarning: (warn)=>{
                    this.logErrorWithOriginalStack(warn, "warning");
                }
            });
            if ("finished" in result) {
                return result;
            }
            result.waitUntil.catch((error)=>{
                this.logErrorWithOriginalStack(error, "unhandledRejection");
            });
            return result;
        } catch (error) {
            if (error instanceof _utils1.DecodeError) {
                throw error;
            }
            /**
       * We only log the error when it is not a MiddlewareNotFound error as
       * in that case we should be already displaying a compilation error
       * which is what makes the module not found.
       */ if (!(error instanceof _utils1.MiddlewareNotFoundError)) {
                this.logErrorWithOriginalStack(error);
            }
            const err = (0, _iserror.getProperError)(error);
            err.middleware = true;
            const { request , response , parsedUrl  } = params;
            /**
       * When there is a failure for an internal Next.js request from
       * middleware we bypass the error without finishing the request
       * so we can serve the required chunks to render the error.
       */ if (request.url.includes("/_next/static") || request.url.includes("/__nextjs_original-stack-frame")) {
                return {
                    finished: false
                };
            }
            response.statusCode = 500;
            this.renderError(err, request, response, parsedUrl.pathname);
            return {
                finished: true
            };
        }
    }
    async runEdgeFunction(params) {
        try {
            return super.runEdgeFunction({
                ...params,
                onWarning: (warn)=>{
                    this.logErrorWithOriginalStack(warn, "warning");
                }
            });
        } catch (error) {
            if (error instanceof _utils1.DecodeError) {
                throw error;
            }
            this.logErrorWithOriginalStack(error, "warning");
            const err = (0, _iserror.getProperError)(error);
            const { req , res , page  } = params;
            res.statusCode = 500;
            this.renderError(err, req, res, page);
            return null;
        }
    }
    async handleRequest(req, res, parsedUrl) {
        await this.devReady;
        return await super.handleRequest(req, res, parsedUrl);
    }
    async run(req, res, parsedUrl) {
        await this.devReady;
        this.setupWebSocketHandler(undefined, req);
        const { basePath  } = this.nextConfig;
        let originalPathname = null;
        // TODO: see if we can remove this in the future
        if (basePath && (0, _pathhasprefix.pathHasPrefix)(parsedUrl.pathname || "/", basePath)) {
            // strip basePath before handling dev bundles
            // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
            originalPathname = parsedUrl.pathname;
            parsedUrl.pathname = (0, _removepathprefix.removePathPrefix)(parsedUrl.pathname || "/", basePath);
        }
        const { pathname  } = parsedUrl;
        if (pathname.startsWith("/_next")) {
            if (await (0, _fileexists.fileExists)((0, _path.join)(this.publicDir, "_next"))) {
                throw new Error(_constants.PUBLIC_DIR_MIDDLEWARE_CONFLICT);
            }
        }
        if (this.hotReloader) {
            const { finished =false  } = await this.hotReloader.run(req.originalRequest, res.originalResponse, parsedUrl);
            if (finished) return;
        }
        if (originalPathname) {
            // restore the path before continuing so that custom-routes can accurately determine
            // if they should match against the basePath or not
            parsedUrl.pathname = originalPathname;
        }
        try {
            return await super.run(req, res, parsedUrl);
        } catch (error) {
            const err = (0, _iserror.getProperError)(error);
            (0, _formatservererror.formatServerError)(err);
            this.logErrorWithOriginalStack(err).catch(()=>{});
            if (!res.sent) {
                res.statusCode = 500;
                try {
                    return await this.renderError(err, req, res, pathname, {
                        __NEXT_PAGE: (0, _iserror.default)(err) && err.page || pathname || ""
                    });
                } catch (internalErr) {
                    console.error(internalErr);
                    res.body("Internal Server Error").send();
                }
            }
        }
    }
    async invokeIpcMethod(method, args) {
        const ipcPort = process.env.__NEXT_PRIVATE_ROUTER_IPC_PORT;
        const ipcKey = process.env.__NEXT_PRIVATE_ROUTER_IPC_KEY;
        if (ipcPort) {
            const res = await (0, _invokerequest.invokeRequest)(`http://${this.hostname}:${ipcPort}?key=${ipcKey}&method=${method}&args=${encodeURIComponent(JSON.stringify(args))}`, {
                method: "GET",
                headers: {}
            });
            const chunks = [];
            for await (const chunk of res){
                if (chunk) {
                    chunks.push(chunk);
                }
            }
            const body = Buffer.concat(chunks).toString();
            if (body.startsWith("{") && body.endsWith("}")) {
                const parsedBody = JSON.parse(body);
                if (parsedBody && typeof parsedBody === "object" && "err" in parsedBody && "stack" in parsedBody.err) {
                    throw (0, _render.deserializeErr)(parsedBody.err);
                }
                return parsedBody;
            }
        }
    }
    async logErrorWithOriginalStack(err, type) {
        if (this.isRenderWorker) {
            await this.invokeIpcMethod("logErrorWithOriginalStack", [
                (0, _render.errorToJSON)(err),
                type
            ]);
            return;
        }
        let usedOriginalStack = false;
        if ((0, _iserror.default)(err) && err.stack) {
            try {
                const frames = (0, _middleware.parseStack)(err.stack);
                // Filter out internal edge related runtime stack
                const frame = frames.find(({ file  })=>{
                    return !(file == null ? void 0 : file.startsWith("eval")) && !(file == null ? void 0 : file.includes("web/adapter")) && !(file == null ? void 0 : file.includes("web/globals")) && !(file == null ? void 0 : file.includes("sandbox/context")) && !(file == null ? void 0 : file.includes("<anonymous>"));
                });
                if ((frame == null ? void 0 : frame.lineNumber) && (frame == null ? void 0 : frame.file)) {
                    var _this_hotReloader, _this_hotReloader_edgeServerStats, _this_hotReloader1, _this_hotReloader_serverStats, _frame_file, _frame_file1, _this_hotReloader2, _this_hotReloader_serverStats1, _this_hotReloader3, _this_hotReloader_edgeServerStats1;
                    const moduleId = frame.file.replace(/^(webpack-internal:\/\/\/|file:\/\/)/, "");
                    const modulePath = frame.file.replace(/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, "");
                    const src = (0, _middleware.getErrorSource)(err);
                    const isEdgeCompiler = src === _constants1.COMPILER_NAMES.edgeServer;
                    const compilation = isEdgeCompiler ? (_this_hotReloader = this.hotReloader) == null ? void 0 : (_this_hotReloader_edgeServerStats = _this_hotReloader.edgeServerStats) == null ? void 0 : _this_hotReloader_edgeServerStats.compilation : (_this_hotReloader1 = this.hotReloader) == null ? void 0 : (_this_hotReloader_serverStats = _this_hotReloader1.serverStats) == null ? void 0 : _this_hotReloader_serverStats.compilation;
                    const source = await (0, _middleware.getSourceById)(!!((_frame_file = frame.file) == null ? void 0 : _frame_file.startsWith(_path.sep)) || !!((_frame_file1 = frame.file) == null ? void 0 : _frame_file1.startsWith("file:")), moduleId, compilation);
                    const originalFrame = await (0, _middleware.createOriginalStackFrame)({
                        line: frame.lineNumber,
                        column: frame.column,
                        source,
                        frame,
                        moduleId,
                        modulePath,
                        rootDirectory: this.dir,
                        errorMessage: err.message,
                        serverCompilation: isEdgeCompiler ? undefined : (_this_hotReloader2 = this.hotReloader) == null ? void 0 : (_this_hotReloader_serverStats1 = _this_hotReloader2.serverStats) == null ? void 0 : _this_hotReloader_serverStats1.compilation,
                        edgeCompilation: isEdgeCompiler ? (_this_hotReloader3 = this.hotReloader) == null ? void 0 : (_this_hotReloader_edgeServerStats1 = _this_hotReloader3.edgeServerStats) == null ? void 0 : _this_hotReloader_edgeServerStats1.compilation : undefined
                    }).catch(()=>{});
                    if (originalFrame) {
                        const { originalCodeFrame , originalStackFrame  } = originalFrame;
                        const { file , lineNumber , column , methodName  } = originalStackFrame;
                        _log[type === "warning" ? "warn" : "error"](`${file} (${lineNumber}:${column}) @ ${methodName}`);
                        if (isEdgeCompiler) {
                            err = err.message;
                        }
                        if (type === "warning") {
                            _log.warn(err);
                        } else if (type === "app-dir") {
                            (0, _logappdirerror.logAppDirError)(err);
                        } else if (type) {
                            _log.error(`${type}:`, err);
                        } else {
                            _log.error(err);
                        }
                        console[type === "warning" ? "warn" : "error"](originalCodeFrame);
                        usedOriginalStack = true;
                    }
                }
            } catch (_) {
            // failed to load original stack using source maps
            // this un-actionable by users so we don't show the
            // internal error and only show the provided stack
            }
        }
        if (!usedOriginalStack) {
            if (type === "warning") {
                _log.warn(err);
            } else if (type === "app-dir") {
                (0, _logappdirerror.logAppDirError)(err);
            } else if (type) {
                _log.error(`${type}:`, err);
            } else {
                _log.error(err);
            }
        }
    }
    // override production loading of routes-manifest
    getCustomRoutes() {
        // actual routes will be loaded asynchronously during .prepare()
        return {
            redirects: [],
            rewrites: {
                beforeFiles: [],
                afterFiles: [],
                fallback: []
            },
            headers: []
        };
    }
    getPagesManifest() {
        return _nodemanifestloader.NodeManifestLoader.require((0, _path.join)(this.serverDistDir, _constants1.PAGES_MANIFEST)) ?? undefined;
    }
    getAppPathsManifest() {
        if (!this.hasAppDir) return undefined;
        return _nodemanifestloader.NodeManifestLoader.require((0, _path.join)(this.serverDistDir, _constants1.APP_PATHS_MANIFEST)) ?? undefined;
    }
    getMiddleware() {
        return this.middleware;
    }
    getNextFontManifest() {
        return undefined;
    }
    async hasMiddleware() {
        return this.hasPage(this.actualMiddlewareFile);
    }
    async ensureMiddleware() {
        return this.ensurePage({
            page: this.actualMiddlewareFile,
            clientOnly: false
        });
    }
    async runInstrumentationHookIfAvailable() {
        if (this.actualInstrumentationHookFile) {
            _buildcontext.NextBuildContext.hasInstrumentationHook = true;
            await this.ensurePage({
                page: this.actualInstrumentationHookFile,
                clientOnly: false
            });
            try {
                const instrumentationHook = await require((0, _path.join)(this.distDir, "server", _constants.INSTRUMENTATION_HOOK_FILENAME));
                await instrumentationHook.register();
            } catch (err) {
                err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
                throw err;
            }
        }
    }
    async ensureEdgeFunction({ page , appPaths  }) {
        return this.ensurePage({
            page,
            appPaths,
            clientOnly: false
        });
    }
    generateRoutes(dev) {
        const { fsRoutes , ...otherRoutes } = super.generateRoutes(dev);
        // Create a shallow copy so we can mutate it.
        const routes = [
            ...fsRoutes
        ];
        // In development we expose all compiled files for react-error-overlay's line show feature
        // We use unshift so that we're sure the routes is defined before Next's default routes
        routes.unshift({
            match: (0, _pathmatch.getPathMatch)("/_next/development/:path*"),
            type: "route",
            name: "_next/development catchall",
            fn: async (req, res, params)=>{
                const p = (0, _path.join)(this.distDir, ...params.path || []);
                await this.serveStatic(req, res, p);
                return {
                    finished: true
                };
            }
        });
        routes.unshift({
            match: (0, _pathmatch.getPathMatch)(`/_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_CLIENT_PAGES_MANIFEST}`),
            type: "route",
            name: `_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_CLIENT_PAGES_MANIFEST}`,
            fn: async (_req, res)=>{
                var _this_sortedRoutes;
                res.statusCode = 200;
                res.setHeader("Content-Type", "application/json; charset=utf-8");
                res.body(JSON.stringify({
                    pages: (_this_sortedRoutes = this.sortedRoutes) == null ? void 0 : _this_sortedRoutes.filter((route)=>!this.appPathRoutes[route])
                })).send();
                return {
                    finished: true
                };
            }
        });
        routes.unshift({
            match: (0, _pathmatch.getPathMatch)(`/_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_MIDDLEWARE_MANIFEST}`),
            type: "route",
            name: `_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_MIDDLEWARE_MANIFEST}`,
            fn: async (_req, res)=>{
                var _this_getMiddleware;
                res.statusCode = 200;
                res.setHeader("Content-Type", "application/json; charset=utf-8");
                res.body(JSON.stringify(((_this_getMiddleware = this.getMiddleware()) == null ? void 0 : _this_getMiddleware.matchers) ?? [])).send();
                return {
                    finished: true
                };
            }
        });
        routes.push({
            match: (0, _pathmatch.getPathMatch)("/:path*"),
            type: "route",
            name: "catchall public directory route",
            fn: async (req, res, params, parsedUrl)=>{
                const { pathname  } = parsedUrl;
                if (!pathname) {
                    throw new Error("pathname is undefined");
                }
                // Used in development to check public directory paths
                if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
                    return {
                        finished: true
                    };
                }
                return {
                    finished: false
                };
            }
        });
        return {
            fsRoutes: routes,
            ...otherRoutes
        };
    }
    // In development public files are not added to the router but handled as a fallback instead
    generatePublicRoutes() {
        return [];
    }
    _filterAmpDevelopmentScript(html, event) {
        if (event.code !== "DISALLOWED_SCRIPT_TAG") {
            return true;
        }
        const snippetChunks = html.split("\n");
        let snippet;
        if (!(snippet = html.split("\n")[event.line - 1]) || !(snippet = snippet.substring(event.col))) {
            return true;
        }
        snippet = snippet + snippetChunks.slice(event.line).join("\n");
        snippet = snippet.substring(0, snippet.indexOf("</script>"));
        return !snippet.includes("data-amp-development-mode-only");
    }
    async getStaticPaths({ pathname , originalAppPath , requestHeaders  }) {
        const isAppPath = Boolean(originalAppPath);
        // we lazy load the staticPaths to prevent the user
        // from waiting on them for the page to load in dev mode
        const __getStaticPaths = async ()=>{
            const { configFileName , publicRuntimeConfig , serverRuntimeConfig , httpAgentOptions  } = this.nextConfig;
            const { locales , defaultLocale  } = this.nextConfig.i18n || {};
            const staticPathsWorker = this.getStaticPathsWorker();
            try {
                const pathsResult = await staticPathsWorker.loadStaticPaths({
                    distDir: this.distDir,
                    pathname,
                    config: {
                        configFileName,
                        publicRuntimeConfig,
                        serverRuntimeConfig
                    },
                    httpAgentOptions,
                    locales,
                    defaultLocale,
                    originalAppPath,
                    isAppPath,
                    requestHeaders,
                    incrementalCacheHandlerPath: this.nextConfig.experimental.incrementalCacheHandlerPath,
                    fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
                    isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
                    maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize
                });
                return pathsResult;
            } finally{
                // we don't re-use workers so destroy the used one
                staticPathsWorker.end();
            }
        };
        const result = this.staticPathsCache.get(pathname);
        const nextInvoke = (0, _coalescedfunction.withCoalescedInvoke)(__getStaticPaths)(`staticPaths-${pathname}`, []).then((res)=>{
            const { paths: staticPaths = [] , fallback  } = res.value;
            if (!isAppPath && this.nextConfig.output === "export") {
                if (fallback === "blocking") {
                    throw new Error('getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
                } else if (fallback === true) {
                    throw new Error('getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
                }
            }
            const value = {
                staticPaths,
                fallbackMode: fallback === "blocking" ? "blocking" : fallback === true ? "static" : fallback
            };
            this.staticPathsCache.set(pathname, value);
            return value;
        }).catch((err)=>{
            this.staticPathsCache.del(pathname);
            if (!result) throw err;
            _log.error(`Failed to generate static paths for ${pathname}:`);
            console.error(err);
        });
        if (result) {
            return result;
        }
        return nextInvoke;
    }
    restorePatchedGlobals() {
        global.fetch = this.originalFetch;
    }
    async ensurePage(opts) {
        var _this_hotReloader;
        if (this.isRenderWorker) {
            await this.invokeIpcMethod("ensurePage", [
                opts
            ]);
            return;
        }
        return (_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.ensurePage(opts);
    }
    async findPageComponents({ pathname , query , params , isAppPath , appPaths =null , shouldEnsure  }) {
        await this.devReady;
        const compilationErr = await this.getCompilationError(pathname);
        if (compilationErr) {
            // Wrap build errors so that they don't get logged again
            throw new _nextserver.WrappedBuildError(compilationErr);
        }
        try {
            if (shouldEnsure || this.renderOpts.customServer) {
                await this.ensurePage({
                    page: pathname,
                    appPaths,
                    clientOnly: false
                });
            }
            this.nextFontManifest = super.getNextFontManifest();
            // before we re-evaluate a route module, we want to restore globals that might
            // have been patched previously to their original state so that we don't
            // patch on top of the previous patch, which would keep the context of the previous
            // patched global in memory, creating a memory leak.
            this.restorePatchedGlobals();
            return await super.findPageComponents({
                pathname,
                query,
                params,
                isAppPath
            });
        } catch (err) {
            if (err.code !== "ENOENT") {
                throw err;
            }
            return null;
        }
    }
    async getFallbackErrorComponents() {
        var _this_hotReloader;
        if (this.isRenderWorker) {
            await this.invokeIpcMethod("getFallbackErrorComponents", []);
            return await (0, _loadcomponents.loadDefaultErrorComponents)(this.distDir);
        }
        await ((_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.buildFallbackError());
        // Build the error page to ensure the fallback is built too.
        // TODO: See if this can be moved into hotReloader or removed.
        await this.ensurePage({
            page: "/_error",
            clientOnly: false
        });
        if (this.isRouterWorker) {
            return null;
        }
        return await (0, _loadcomponents.loadDefaultErrorComponents)(this.distDir);
    }
    setImmutableAssetCacheControl(res, pathSegments) {
        // `next/font` generates checksum in the filepath even in dev,
        // we can safely cache fonts to avoid FOUC of fonts during development.
        if (pathSegments[0] === "media" && pathSegments[1] && /\.(woff|woff2|eot|ttf|otf)$/.test(pathSegments[1])) {
            res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
            return;
        }
        res.setHeader("Cache-Control", "no-store, must-revalidate");
    }
    servePublic(req, res, pathParts) {
        const p = (0, _path.join)(this.publicDir, ...pathParts);
        return this.serveStatic(req, res, p);
    }
    async hasPublicFile(path) {
        try {
            const info = await _fs.default.promises.stat((0, _path.join)(this.publicDir, path));
            return info.isFile();
        } catch (_) {
            return false;
        }
    }
    async getCompilationError(page) {
        var _this_hotReloader;
        if (this.isRenderWorker) {
            const err = await this.invokeIpcMethod("getCompilationError", [
                page
            ]);
            return (0, _render.deserializeErr)(err);
        }
        const errors = await ((_this_hotReloader = this.hotReloader) == null ? void 0 : _this_hotReloader.getCompilationErrors(page));
        if (!errors) return;
        // Return the very first error we found.
        return errors[0];
    }
    async getStaticInfo({ fileName , rootFile , isAppPath  }) {
        if (this.isRenderWorker) {
            return this.invokeIpcMethod("getStaticInfo", [
                fileName
            ]);
        } else {
            return (0, _entries.getStaticInfoIncludingLayouts)({
                pageFilePath: fileName,
                config: this.nextConfig,
                appDir: this.appDir,
                page: rootFile,
                isDev: true,
                isInsideAppDir: isAppPath,
                pageExtensions: this.nextConfig.pageExtensions
            });
        }
    }
    isServableUrl(untrustedFileUrl) {
        // This method mimics what the version of `send` we use does:
        // 1. decodeURIComponent:
        //    https://github.com/pillarjs/send/blob/0.17.1/index.js#L989
        //    https://github.com/pillarjs/send/blob/0.17.1/index.js#L518-L522
        // 2. resolve:
        //    https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L561
        let decodedUntrustedFilePath;
        try {
            // (1) Decode the URL so we have the proper file name
            decodedUntrustedFilePath = decodeURIComponent(untrustedFileUrl);
        } catch  {
            return false;
        }
        // (2) Resolve "up paths" to determine real request
        const untrustedFilePath = (0, _path.resolve)(decodedUntrustedFilePath);
        // don't allow null bytes anywhere in the file path
        if (untrustedFilePath.indexOf("\x00") !== -1) {
            return false;
        }
        // During development mode, files can be added while the server is running.
        // Checks for .next/static, .next/server, static and public.
        // Note that in development .next/server is available for error reporting purposes.
        // see `packages/next/server/next-server.ts` for more details.
        if (untrustedFilePath.startsWith((0, _path.join)(this.distDir, "static") + _path.sep) || untrustedFilePath.startsWith((0, _path.join)(this.distDir, "server") + _path.sep) || untrustedFilePath.startsWith((0, _path.join)(this.dir, "static") + _path.sep) || untrustedFilePath.startsWith((0, _path.join)(this.dir, "public") + _path.sep)) {
            return true;
        }
        return false;
    }
}

//# sourceMappingURL=next-dev-server.js.map