UNPKG

next

Version:

The React Framework

1,156 lines • 64.8 kB
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
0 && (module.exports = {
    propagateServerField: null,
    setupDevBundler: null
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    propagateServerField: function() {
        return propagateServerField;
    },
    setupDevBundler: function() {
        return setupDevBundler;
    }
});
const _swc = require("../../../build/swc");
const _installbindings = require("../../../build/swc/install-bindings");
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _querystring = /*#__PURE__*/ _interop_require_default(require("querystring"));
const _watchpack = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/watchpack"));
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _picocolors = require("../../../lib/picocolors");
const _filesystem = require("./filesystem");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../build/output/log"));
const _shared = require("../../../trace/shared");
const _findpagefile = require("../find-page-file");
const _events = require("../../../telemetry/events");
const _utils = require("../../../shared/lib/router/utils");
const _sortbypageexts = require("../../../build/sort-by-page-exts");
const _getconventionfilebasename = require("../../../build/get-convention-file-base-name");
const _normalizecatchallroutes = require("./normalize-catchall-routes");
const _verifytypescriptsetup = require("../../../lib/verify-typescript-setup");
const _verifypartytownsetup = require("../../../lib/verify-partytown-setup");
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _builddataroute = require("./build-data-route");
const _routematcher = require("../../../shared/lib/router/utils/route-matcher");
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _normalizepathsep = require("../../../shared/lib/page-path/normalize-path-sep");
const _createclientrouterfilter = require("../../../lib/create-client-router-filter");
const _absolutepathtopage = require("../../../shared/lib/page-path/absolute-path-to-page");
const _generateinterceptionroutesrewrites = require("../../../lib/generate-interception-routes-rewrites");
const _constants = require("../../../shared/lib/constants");
const _middlewareroutematcher = require("../../../shared/lib/router/utils/middleware-route-matcher");
const _utils1 = require("../../../build/utils");
const _shared1 = require("../../../build/webpack/plugins/next-types-plugin/shared");
const _hotreloadertypes = require("../../dev/hot-reloader-types");
const _pagetypes = require("../../../lib/page-types");
const _encryptionutilsserver = require("../../app-render/encryption-utils-server");
const _ismetadataroute = require("../../../lib/metadata/is-metadata-route");
const _getmetadataroute = require("../../../lib/metadata/get-metadata-route");
const _jsconfigpathsplugin = require("../../../build/webpack/plugins/jsconfig-paths-plugin");
const _store = require("../../../build/output/store");
const _utils2 = require("../../../shared/lib/turbopack/utils");
const _defineenv = require("../../../build/define-env");
const _internalerror = require("../../../shared/lib/turbopack/internal-error");
const _recursivereaddir = require("../../../lib/recursive-readdir");
const _constants1 = require("../../../lib/constants");
const _url = require("../../../lib/url");
const _isapiroute = require("../../../lib/is-api-route");
const _isapppageroute = require("../../../lib/is-app-page-route");
const _isapprouteroute = require("../../../lib/is-app-route-route");
const _unmatchedapppageserror = require("../../../shared/lib/errors/unmatched-app-pages-error");
const _missingcanonicalinterceptionrouteserror = require("../../../shared/lib/errors/missing-canonical-interception-routes-error");
const _incompatibleparallelrouteslotserror = require("../../../shared/lib/errors/incompatible-parallel-route-slots-error");
const _interceptionroutes = require("../../../shared/lib/router/utils/interception-routes");
const _strictroutematchingconfig = require("./strict-route-matching-config");
const _routetypesutils = require("./route-types-utils");
const _cachelifetypeutils = require("./cache-life-type-utils");
const _rootparamstypeutils = require("./root-params-type-utils");
const _fileclassifier = require("../../../build/file-classifier");
const _apppaths = require("../../../shared/lib/router/utils/app-paths");
const _ensureleadingslash = require("../../../shared/lib/page-path/ensure-leading-slash");
const _lockfile = require("../../../build/lockfile");
const _magicidentifier = require("../../../shared/lib/magic-identifier");
const _routekind = require("../../route-kind");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
async function verifyTypeScript(opts) {
    const verifyResult = await (0, _verifytypescriptsetup.verifyAndRunTypeScript)({
        dir: opts.dir,
        distDir: opts.nextConfig.distDir,
        strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes),
        shouldRunTypeCheck: false,
        tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
        typedRoutes: Boolean(opts.nextConfig.typedRoutes),
        disableStaticImages: opts.nextConfig.images.disableStaticImages,
        hasAppDir: !!opts.appDir,
        hasPagesDir: !!opts.pagesDir,
        appDir: opts.appDir,
        pagesDir: opts.pagesDir,
        useTypeScriptCli: Boolean(opts.nextConfig.experimental.useTypeScriptCli)
    });
    if (verifyResult.version) {
        return true;
    }
    return false;
}
async function propagateServerField(opts, field, args) {
    var _opts_renderServer_instance, _opts_renderServer;
    await ((_opts_renderServer = opts.renderServer) == null ? void 0 : (_opts_renderServer_instance = _opts_renderServer.instance) == null ? void 0 : _opts_renderServer_instance.propagateServerField(opts.dir, field, args));
}
async function startWatcher(opts) {
    const { nextConfig, appDir, pagesDir, dir, resetFetch } = opts;
    const { useFileSystemPublicRoutes } = nextConfig;
    const distDir = _path.default.join(opts.dir, opts.nextConfig.distDir);
    (0, _shared.setGlobal)('distDir', distDir);
    (0, _shared.setGlobal)('phase', _constants.PHASE_DEVELOPMENT_SERVER);
    let lockfile;
    if (opts.nextConfig.experimental.lockDistDir) {
        _fs.default.mkdirSync(distDir, {
            recursive: true
        });
        // Create server info to store in the lockfile itself
        // This allows other processes to discover the running server
        const appUrl = process.env.__NEXT_PRIVATE_ORIGIN ?? `http://localhost:${opts.port}`;
        const serverInfo = {
            pid: process.pid,
            port: opts.port,
            hostname: new URL(appUrl).hostname,
            appUrl,
            startedAt: Date.now()
        };
        lockfile = await _lockfile.Lockfile.acquireWithRetriesOrExit(_path.default.join(distDir, 'lock'), 'next dev', true, JSON.stringify(serverInfo), opts.dir, opts.nextConfig.distDir);
    }
    const validFileMatcher = (0, _findpagefile.createValidFileMatcher)(nextConfig.pageExtensions, appDir);
    const serverFields = {};
    // Update logging state once based on next.config.js when initializing
    _store.store.setState({
        logging: nextConfig.logging !== false
    });
    const hotReloader = opts.turbo ? await (async ()=>{
        const createHotReloaderTurbopack = require('../../dev/hot-reloader-turbopack').createHotReloaderTurbopack;
        return await createHotReloaderTurbopack(opts, serverFields, distDir, resetFetch, lockfile, opts.serverFastRefresh);
    })() : await (async ()=>{
        const HotReloader = process.env.NEXT_RSPACK ? require('../../dev/hot-reloader-rspack').default : require('../../dev/hot-reloader-webpack').default;
        return new HotReloader(opts.dir, {
            isSrcDir: opts.isSrcDir,
            appDir,
            pagesDir,
            distDir,
            config: opts.nextConfig,
            buildId: 'development',
            encryptionKey: await (0, _encryptionutilsserver.generateEncryptionKeyBase64)({
                isBuild: false,
                distDir
            }),
            telemetry: opts.telemetry,
            rewrites: opts.fsChecker.rewrites,
            previewProps: opts.fsChecker.previewProps,
            resetFetch,
            lockfile,
            onDevServerCleanup: opts.onDevServerCleanup,
            hasVulnerabilityInsight: opts.hasVulnerabilityInsight
        });
    })();
    await hotReloader.start();
    const distTypesDir = _path.default.join(distDir, 'types');
    await (0, _routetypesutils.writeRouteTypesManifest)({
        appRoutes: {},
        pageRoutes: {},
        layoutRoutes: {},
        appRouteHandlerRoutes: {},
        redirectRoutes: {},
        rewriteRoutes: {},
        appPagePaths: new Set(),
        pagesRouterPagePaths: new Set(),
        layoutPaths: new Set(),
        appRouteHandlers: new Set(),
        pageApiRoutes: new Set(),
        filePathToRoute: new Map(),
        rootParams: new Map()
    }, _path.default.join(distTypesDir, 'routes.d.ts'), opts.nextConfig);
    const routesManifestPath = _path.default.join(distDir, _constants.ROUTES_MANIFEST);
    const routesManifest = {
        version: 3,
        caseSensitive: !!nextConfig.experimental.caseSensitiveRoutes,
        basePath: nextConfig.basePath,
        rewrites: opts.fsChecker.rewrites,
        redirects: opts.fsChecker.redirects,
        headers: opts.fsChecker.headers,
        onMatchHeaders: opts.fsChecker.onMatchHeaders,
        i18n: nextConfig.i18n || undefined,
        skipProxyUrlNormalize: nextConfig.skipProxyUrlNormalize
    };
    await _fs.default.promises.writeFile(routesManifestPath, JSON.stringify(routesManifest));
    const previewPropsManifestPath = _path.default.join(distDir, _constants.SERVER_DIRECTORY, _constants.PREVIEW_PROPS_MANIFEST);
    _fs.default.mkdirSync(_path.default.join(distDir, _constants.SERVER_DIRECTORY), {
        recursive: true
    });
    await _fs.default.promises.writeFile(previewPropsManifestPath, JSON.stringify(opts.fsChecker.previewProps, null, 2));
    const prerenderManifestPath = _path.default.join(distDir, _constants.PRERENDER_MANIFEST);
    await _fs.default.promises.writeFile(prerenderManifestPath, JSON.stringify({
        version: 4,
        routes: {},
        dynamicRoutes: {},
        notFoundRoutes: []
    }, null, 2));
    if (opts.nextConfig.experimental.nextScriptWorkers) {
        await (0, _verifypartytownsetup.verifyPartytownSetup)(opts.dir, _path.default.join(distDir, _constants.CLIENT_STATIC_FILES_PATH));
    }
    opts.fsChecker.ensureCallback(async function ensure(item) {
        const definition = item.route;
        // FsOutput also includes static assets, which do not need compilation.
        if (!definition) return;
        // Static-info lookup needs the concrete grouped or parallel app path to
        // discover segment configuration such as `runtime = 'edge'`.
        await hotReloader.ensurePage({
            clientOnly: false,
            page: definition.page,
            isApp: item.type === 'appFile',
            definition,
            url: item.requestPath
        });
    });
    let resolved = false;
    let prevSortedRoutes = [];
    let hasComputedSortedRoutes = false;
    const pages = pagesDir ? [
        pagesDir
    ] : [];
    const app = appDir ? [
        appDir
    ] : [];
    const directories = [
        ...pages,
        ...app
    ];
    // Snapshot the route directories before watching starts. Watchpack can report
    // its first aggregation while a directory scan is still in flight, so route
    // discovery needs this snapshot to avoid observing a partial filesystem.
    const initialFiles = (await Promise.all(directories.map(async (directory)=>{
        try {
            return await (0, _recursivereaddir.recursiveReadDir)(directory, {
                relativePathnames: false
            });
        } catch (err) {
            // The directory can be removed while the dev server boots. Watchpack
            // reports that as a removal later on.
            if (err.code !== 'ENOENT') throw err;
            return [];
        }
    }))).flat();
    const initialPageFiles = initialFiles.filter(validFileMatcher.isPageFile);
    await new Promise(async (resolve, reject)=>{
        if (initialFiles.length === 0) {
            // Watchpack doesn't emit an event when all route directories are empty.
            resolve();
            resolved = true;
        }
        const rootDir = pagesDir || appDir;
        const files = [
            ...(0, _utils1.getPossibleMiddlewareFilenames)(_path.default.join(rootDir, '..'), nextConfig.pageExtensions),
            ...(0, _utils1.getPossibleInstrumentationHookFilenames)(_path.default.join(rootDir, '..'), nextConfig.pageExtensions)
        ];
        let nestedMiddleware = [];
        const envFiles = [
            '.env.development.local',
            '.env.local',
            '.env.development',
            '.env'
        ].map((file)=>_path.default.join(dir, file));
        files.push(...envFiles);
        // tsconfig/jsconfig paths hot-reloading
        const tsconfigPaths = [
            _path.default.join(dir, 'tsconfig.json'),
            _path.default.join(dir, 'jsconfig.json')
        ];
        files.push(...tsconfigPaths);
        const wp = new _watchpack.default({
            // Watchpack default is 200ms which adds 200ms of dead time on bootup.
            aggregateTimeout: 5,
            ignored: (pathname)=>{
                return !files.some((file)=>file.startsWith(pathname)) && !directories.some((d)=>pathname.startsWith(d) || d.startsWith(pathname));
            }
        });
        const fileWatchTimes = new Map();
        let enabledTypeScript = await verifyTypeScript(opts);
        let previousClientRouterFilters;
        let previousConflictingPagePaths = new Set();
        let previousRouteMatchingErrors = null;
        let hadInitialScan = false;
        let previousDuplicatePagePaths = new Set();
        const routeTypesFilePath = _path.default.join(distDir, 'types', 'routes.d.ts');
        const validatorFilePath = _path.default.join(distDir, 'types', 'validator.ts');
        let initialWatchTime = performance.now() + performance.timeOrigin;
        // Startup only waits this long for Watchpack to observe the files found by
        // the snapshot above, so a file it never reports cannot stall the server.
        const initialScanDeadline = initialWatchTime + 30000;
        wp.on('aggregated', async ()=>{
            var _serverFields_middleware, _serverFields_middleware1;
            const isInitialScan = !hadInitialScan;
            let writeEnvDefinitions = false;
            let typescriptStatusFromLastAggregation = enabledTypeScript;
            let middlewareMatchers;
            const routedPages = [];
            const knownFiles = wp.getTimeInfoEntries();
            // Watchpack can emit an aggregation while its initial directory scan is
            // still in flight. Ignore partial startup passes so route definitions and
            // errors are not published until every initial page file is observable.
            // Bounded by a deadline so an unwatchable file can never block startup.
            if (!resolved && performance.now() + performance.timeOrigin < initialScanDeadline && initialPageFiles.some((file)=>_fs.default.existsSync(file) && !knownFiles.has(file))) {
                return;
            }
            hadInitialScan = true;
            const appPaths = {};
            const defaultAppPaths = new Set();
            const pageNameSet = new Set();
            const conflictingAppPagePaths = new Set();
            const duplicatePagePaths = new Set();
            const appPageFilePaths = new Map();
            const appRouteFilePaths = new Map();
            const parallelRouteLayoutFiles = new Map();
            const pagesPageFilePaths = new Map();
            const appRouteHandlers = [];
            const pageApiRoutes = [];
            const pageRoutes = [];
            const appRoutes = [];
            const layoutRoutes = [];
            const slots = [];
            let envFileChange = false;
            let clientRouterFiltersChange = false;
            let tsconfigChange = false;
            let conflictingPageChange = 0;
            let hasRootAppNotFound = false;
            const { appFiles, pageFiles, staticMetadataFiles } = opts.fsChecker;
            appFiles.clear();
            pageFiles.clear();
            staticMetadataFiles.clear();
            _shared1.devPageFiles.clear();
            const sortedKnownFiles = [
                ...knownFiles.keys()
            ].sort((0, _sortbypageexts.sortByPageExts)(nextConfig.pageExtensions));
            let proxyFilePath;
            let middlewareFilePath;
            for (const fileName of sortedKnownFiles){
                if (!files.includes(fileName) && !directories.some((d)=>fileName.startsWith(d))) {
                    continue;
                }
                const { base: fileBase, dir: fileDir } = _path.default.parse(fileName);
                const fileBaseName = (0, _getconventionfilebasename.getConventionFileBaseName)(fileBase);
                const isAtConventionLevel = fileDir === dir || fileDir === _path.default.join(dir, 'src');
                if (isAtConventionLevel && fileBaseName === _constants1.MIDDLEWARE_FILENAME) {
                    middlewareFilePath = fileName;
                }
                if (isAtConventionLevel && fileBaseName === _constants1.PROXY_FILENAME) {
                    proxyFilePath = fileName;
                }
                if (middlewareFilePath) {
                    if (proxyFilePath) {
                        const cwd = process.cwd();
                        throw new Error(`Both ${_constants1.MIDDLEWARE_FILENAME} file "./${_path.default.relative(cwd, middlewareFilePath)}" and ${_constants1.PROXY_FILENAME} file "./${_path.default.relative(cwd, proxyFilePath)}" are detected. Please use "./${_path.default.relative(cwd, proxyFilePath)}" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`);
                    }
                    _log.warnOnce(`The "${_constants1.MIDDLEWARE_FILENAME}" file convention is deprecated. Please use "${_constants1.PROXY_FILENAME}" instead.\n\n` + `  To migrate automatically, run:\n` + `  npx @next/codemod@canary middleware-to-proxy .\n\n` + `  Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`);
                }
                const meta = knownFiles.get(fileName);
                const watchTime = fileWatchTimes.get(fileName);
                const nextWatchTime = meta == null ? void 0 : meta.timestamp;
                // If the file is showing up for the first time or the meta.timestamp is changed since last time
                // Files that were created before we started watching are not considered changed.
                // If any file was created by Next.js while booting, we assume those changes
                // are handled in the bootstrap phase.
                // Files that existed before we booted should be handled during bootstrapping.
                const fileChanged = watchTime === undefined && (nextWatchTime === undefined || nextWatchTime >= initialWatchTime) || watchTime && watchTime !== nextWatchTime;
                fileWatchTimes.set(fileName, nextWatchTime);
                if (envFiles.includes(fileName)) {
                    if (fileChanged) {
                        envFileChange = true;
                    }
                    continue;
                }
                if (tsconfigPaths.includes(fileName)) {
                    if (fileName.endsWith('tsconfig.json')) {
                        enabledTypeScript = true;
                    }
                    if (fileChanged) {
                        tsconfigChange = true;
                    }
                    continue;
                }
                const fileExists = _fs.default.existsSync(fileName);
                if (!validFileMatcher.isPageFile(fileName) || (meta == null ? void 0 : meta.accuracy) === undefined && !fileExists) {
                    continue;
                }
                if (fileExists) {
                    try {
                        if (!_fs.default.statSync(fileName).isFile()) {
                            continue;
                        }
                    } catch  {
                        continue;
                    }
                }
                const isAppPath = Boolean(appDir && (0, _normalizepathsep.normalizePathSep)(fileName).startsWith((0, _normalizepathsep.normalizePathSep)(appDir) + '/'));
                const isPagePath = Boolean(pagesDir && (0, _normalizepathsep.normalizePathSep)(fileName).startsWith((0, _normalizepathsep.normalizePathSep)(pagesDir) + '/'));
                const rootFile = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
                    dir: dir,
                    extensions: nextConfig.pageExtensions,
                    keepIndex: false,
                    pagesType: _pagetypes.PAGE_TYPES.ROOT
                });
                if ((0, _utils1.isMiddlewareFile)(rootFile)) {
                    var _staticInfo_middleware;
                    const getStaticInfoIncludingLayouts = require('../../../build/get-static-info-including-layouts').getStaticInfoIncludingLayouts;
                    const staticInfo = await getStaticInfoIncludingLayouts({
                        pageFilePath: fileName,
                        config: nextConfig,
                        appDir: appDir,
                        page: rootFile,
                        isDev: true,
                        isInsideAppDir: isAppPath,
                        pageExtensions: nextConfig.pageExtensions
                    });
                    if (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;
                    }
                    serverFields.actualMiddlewareFile = rootFile;
                    await propagateServerField(opts, 'actualMiddlewareFile', serverFields.actualMiddlewareFile);
                    middlewareMatchers = ((_staticInfo_middleware = staticInfo.middleware) == null ? void 0 : _staticInfo_middleware.matchers) || [
                        {
                            regexp: '^/.*$',
                            originalSource: '/:path*'
                        }
                    ];
                    continue;
                }
                if ((0, _utils1.isInstrumentationHookFile)(rootFile)) {
                    serverFields.actualInstrumentationHookFile = rootFile;
                    await propagateServerField(opts, 'actualInstrumentationHookFile', serverFields.actualInstrumentationHookFile);
                    continue;
                }
                if (fileName.endsWith('.ts') || fileName.endsWith('.tsx')) {
                    enabledTypeScript = true;
                }
                if (!(isAppPath || isPagePath)) {
                    continue;
                }
                // Collect all current filenames for the TS plugin to use
                _shared1.devPageFiles.add(fileName);
                let pageName = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
                    dir: isAppPath ? appDir : pagesDir,
                    extensions: nextConfig.pageExtensions,
                    keepIndex: isAppPath,
                    pagesType: isAppPath ? _pagetypes.PAGE_TYPES.APP : _pagetypes.PAGE_TYPES.PAGES
                });
                if (isAppPath && appDir && (0, _ismetadataroute.isMetadataRouteFile)(fileName.replace(appDir, ''), nextConfig.pageExtensions, true)) {
                    const getPageStaticInfo = require('../../../build/analysis/get-page-static-info').getPageStaticInfo;
                    const staticInfo = await getPageStaticInfo({
                        pageFilePath: fileName,
                        nextConfig: {},
                        page: pageName,
                        isDev: true,
                        pageType: _pagetypes.PAGE_TYPES.APP
                    });
                    pageName = (0, _getmetadataroute.normalizeMetadataPageToRoute)(pageName, !!(staticInfo.generateSitemaps || staticInfo.generateImageMetadata));
                }
                if (!isAppPath && pageName.startsWith('/api/') && 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) {
                    // Track root not-found
                    if (validFileMatcher.isRootNotFound(fileName)) {
                        hasRootAppNotFound = true;
                        continue;
                    }
                    const normalizedPageName = (0, _normalizepathsep.normalizePathSep)(pageName);
                    // Skip files/directories starting with `_` in the app directory
                    if (normalizedPageName.includes('/_')) continue;
                    // Record parallel route slots
                    (0, _fileclassifier.addSlotIfNew)(slots, normalizedPageName);
                    // Handle layouts separately - they don't get added to appPaths
                    if (validFileMatcher.isAppLayoutPage(fileName)) {
                        const layoutPath = normalizedPageName.replace(/%5F/g, '_').replace(/\/layout$/, '') || '/';
                        parallelRouteLayoutFiles.set(layoutPath, fileName);
                        const layoutRoute = (0, _ensureleadingslash.ensureLeadingSlash)((0, _apppaths.normalizeAppPath)(normalizedPageName).replace(/\/layout$/, ''));
                        layoutRoutes.push({
                            route: layoutRoute,
                            filePath: fileName
                        });
                        continue;
                    }
                    if (validFileMatcher.isAppDefaultPage(fileName)) {
                        defaultAppPaths.add(normalizedPageName.replace(/%5F/g, '_'));
                        continue;
                    }
                    // Skip non-router pages (loading.tsx, error.tsx, etc.)
                    if (!validFileMatcher.isAppRouterPage(fileName)) continue;
                    const originalPageName = pageName;
                    pageName = (0, _apppaths.normalizeAppPath)(pageName).replace(/%5F/g, '_');
                    const appRoute = (0, _normalizepathsep.normalizePathSep)(pageName);
                    const appPath = opts.turbo ? originalPageName.replace(/%5F/g, '_') : originalPageName;
                    if (!appPaths[pageName]) {
                        appPaths[pageName] = [];
                    }
                    appPaths[pageName].push(appPath);
                    appRouteFilePaths.set(appPath, fileName);
                    if (useFileSystemPublicRoutes) {
                        if (appDir && (0, _ismetadataroute.isStaticMetadataFile)(fileName.replace(appDir, ''))) {
                            const segment = _path.default.posix.dirname(pageName);
                            const lastSegment = _path.default.posix.basename(pageName);
                            const normalizedPath = (0, _getmetadataroute.fillStaticMetadataSegment)(segment, lastSegment);
                            staticMetadataFiles.set(normalizedPath, fileName);
                        } else {
                            appFiles.add(pageName);
                        }
                    }
                    const routeEntry = {
                        route: appRoute,
                        filePath: fileName
                    };
                    if ((0, _isapprouteroute.isAppRouteRoute)(appPath)) {
                        appRouteHandlers.push({
                            ...routeEntry,
                            page: appPath
                        });
                    } else {
                        appRoutes.push(routeEntry);
                    }
                    if (routedPages.includes(pageName)) continue;
                } else {
                    // Pages router
                    const existingPageFilePath = pagesPageFilePaths.get(pageName);
                    if (pagesDir && existingPageFilePath) {
                        duplicatePagePaths.add(pageName);
                        if (!previousDuplicatePagePaths.has(pageName)) {
                            const existingPagePath = (0, _normalizepathsep.normalizePathSep)(_path.default.join('pages', _path.default.relative(pagesDir, existingPageFilePath)));
                            const duplicatePagePath = (0, _normalizepathsep.normalizePathSep)(_path.default.join('pages', _path.default.relative(pagesDir, fileName)));
                            _log.warn(`Duplicate page detected. ${(0, _picocolors.cyan)(existingPagePath)} and ${(0, _picocolors.cyan)(duplicatePagePath)} both resolve to ${(0, _picocolors.cyan)(pageName)}.`);
                        }
                    }
                    if (useFileSystemPublicRoutes) {
                        pageFiles.add(pageName);
                        opts.fsChecker.nextDataRoutes.add(pageName);
                    }
                    const route = (0, _normalizepathsep.normalizePathSep)(pageName);
                    const routeEntry = {
                        route,
                        filePath: fileName
                    };
                    if ((0, _isapiroute.isAPIRoute)(pageName)) {
                        pageApiRoutes.push(routeEntry);
                    } else {
                        pageRoutes.push(routeEntry);
                    }
                }
                // Record pages
                if (isAppPath) {
                    appPageFilePaths.set(pageName, fileName);
                } else {
                    pagesPageFilePaths.set(pageName, fileName);
                }
                if (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) {
                    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 = _path.default.relative(dir, appPageFilePaths.get(p));
                        const pagesPath = _path.default.relative(dir, pagesPageFilePaths.get(p));
                        errorMessage += `  "${pagesPath}" - "${appPath}"\n`;
                    }
                    hotReloader.setHmrServerError(new Error(errorMessage));
                } else if (numConflicting === 0) {
                    hotReloader.clearHmrServerError();
                }
            }
            previousConflictingPagePaths = conflictingAppPagePaths;
            previousDuplicatePagePaths = duplicatePagePaths;
            let clientRouterFilters;
            if (nextConfig.experimental.clientRouterFilter) {
                clientRouterFilters = (0, _createclientrouterfilter.createClientRouterFilter)(Object.keys(appPaths), nextConfig.experimental.clientRouterFilterRedirects ? (nextConfig._originalRedirects || []).filter((r)=>!r.internal) : [], nextConfig.experimental.clientRouterFilterAllowedRate);
                if (!previousClientRouterFilters || JSON.stringify(previousClientRouterFilters) !== JSON.stringify(clientRouterFilters)) {
                    clientRouterFiltersChange = true;
                    previousClientRouterFilters = clientRouterFilters;
                }
            }
            // Also set on the initial scan, so that typed env definitions exist
            // from startup.
            if (envFileChange || isInitialScan) {
                writeEnvDefinitions = true;
            }
            if (envFileChange || clientRouterFiltersChange || tsconfigChange) {
                if (envFileChange) {
                    await propagateServerField(opts, 'loadEnvConfig', [
                        {
                            dev: true,
                            forceReload: true
                        }
                    ]);
                }
                if (hotReloader.turbopackProject) {
                    const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
                    await hotReloader.turbopackProject.update({
                        defineEnv: (0, _swc.createDefineEnv)({
                            isTurbopack: true,
                            clientRouterFilters,
                            config: nextConfig,
                            dev: true,
                            distDir,
                            fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
                            hasRewrites,
                            // TODO: Implement
                            middlewareMatchers: undefined,
                            projectPath: opts.dir,
                            rewrites: opts.fsChecker.rewrites
                        })
                    });
                } else {
                    var _hotReloader_activeWebpackConfigs;
                    let tsconfigResult;
                    // This is not relevant for Turbopack because tsconfig/jsconfig is handled internally.
                    if (tsconfigChange) {
                        try {
                            const loadJsConfig = require('../../../build/load-jsconfig').default;
                            tsconfigResult = await loadJsConfig(dir, nextConfig);
                        } catch (_) {
                        /* do we want to log if there are syntax errors in tsconfig while editing? */ }
                    }
                    (_hotReloader_activeWebpackConfigs = hotReloader.activeWebpackConfigs) == null ? void 0 : _hotReloader_activeWebpackConfigs.forEach((config, idx)=>{
                        const isClient = idx === 0;
                        const isNodeServer = idx === 1;
                        const isEdgeServer = idx === 2;
                        const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
                        if (tsconfigChange) {
                            var _config_resolve_plugins, _config_resolve;
                            (_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 instanceof _jsconfigpathsplugin.JsConfigPathsPlugin && tsconfigResult) {
                                    var _config_resolve_modules, _config_resolve, _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 == null ? void 0 : currentResolvedBaseUrl.baseUrl));
                                    if (resolvedBaseUrl) {
                                        if (resolvedBaseUrl.baseUrl !== (currentResolvedBaseUrl == null ? void 0 : currentResolvedBaseUrl.baseUrl)) {
                                            // remove old baseUrl and add new one
                                            if (resolvedUrlIndex && resolvedUrlIndex > -1) {
                                                var _config_resolve_modules1, _config_resolve1;
                                                (_config_resolve1 = config.resolve) == null ? void 0 : (_config_resolve_modules1 = _config_resolve1.modules) == null ? void 0 : _config_resolve_modules1.splice(resolvedUrlIndex, 1);
                                            }
                                            // If the resolvedBaseUrl is implicit we only remove the previous value.
                                            // Only add the baseUrl if it's explicitly set in tsconfig/jsconfig
                                            if (!resolvedBaseUrl.isImplicit) {
                                                var _config_resolve_modules2, _config_resolve2;
                                                (_config_resolve2 = config.resolve) == null ? void 0 : (_config_resolve_modules2 = _config_resolve2.modules) == null ? void 0 : _config_resolve_modules2.push(resolvedBaseUrl.baseUrl);
                                            }
                                        }
                                    }
                                    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 (envFileChange || clientRouterFiltersChange) {
                            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 newDefine = (0, _defineenv.getDefineEnv)({
                                        isTurbopack: false,
                                        clientRouterFilters,
                                        config: nextConfig,
                                        dev: true,
                                        distDir,
                                        fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
                                        hasRewrites,
                                        isClient,
                                        isEdgeServer,
                                        isNodeServer,
                                        middlewareMatchers: undefined,
                                        projectPath: opts.dir,
                                        rewrites: opts.fsChecker.rewrites
                                    });
                                    Object.keys(plugin.definitions).forEach((key)=>{
                                        if (!(key in newDefine)) {
                                            delete plugin.definitions[key];
                                        }
                                    });
                                    Object.assign(plugin.definitions, newDefine);
                                }
                            });
                        }
                    });
                }
                await hotReloader.invalidate({
                    // A router-filter change only requires the updated define to be
                    // compiled into the bundles; unlike env, it can't affect rendered
                    // output or cached data.
                    reloadAfterInvalidation: envFileChange
                });
            }
            if (nestedMiddleware.length > 0) {
                _log.error(new _utils1.NestedMiddlewareError(nestedMiddleware, dir, pagesDir || appDir).message);
                nestedMiddleware = [];
            }
            // appPaths intentionally contains both pages and route handlers. The
            // removed matcher providers classified those entries independently, so
            // isolate pages before catch-all normalization and definition creation.
            const appPagePaths = {};
            for (const [route, routeAppPaths] of Object.entries(appPaths)){
                const pageAppPaths = routeAppPaths.filter(_isapppageroute.isAppPageRoute);
                if (pageAppPaths.length > 0) {
                    appPagePaths[route] = pageAppPaths;
                }
            }
            const { unmatchedAppPages, incompatibleParallelRouteSlots } = (0, _normalizecatchallroutes.normalizeCatchAllRoutes)(appPagePaths, undefined, {
                strictRouteMatching: nextConfig.experimental.strictRouteMatching,
                defaultAppPaths
            });
            const missingCanonicalInterceptionRoutes = nextConfig.experimental.strictRouteMatching ? (0, _interceptionroutes.findMissingCanonicalInterceptionRoutes)(appPagePaths) : [];
            const routeMatchingErrors = [];
            if (missingCanonicalInterceptionRoutes.length > 0) {
                routeMatchingErrors.push(new _missingcanonicalinterceptionrouteserror.MissingCanonicalInterceptionRoutesError(missingCanonicalInterceptionRoutes));
            }
            if (incompatibleParallelRouteSlots.length > 0) {
                routeMatchingErrors.push(new _incompatibleparallelrouteslotserror.IncompatibleParallelRouteSlotsError(incompatibleParallelRouteSlots.map((incompatibleRoute)=>({
                        ...incompatibleRoute,
                        layoutFile: _path.default.relative(dir, parallelRouteLayoutFiles.get(incompatibleRoute.layoutPath) ?? _path.default.join(appDir, incompatibleRoute.layoutPath, 'layout'))
                    }))));
            }
            if (unmatchedAppPages.length > 0) {
                routeMatchingErrors.push(new _unmatchedapppageserror.UnmatchedAppPagesError(unmatchedAppPages.map((appPath)=>{
                    const filePath = appRouteFilePaths.get(appPath);
                    return filePath ? (0, _normalizepathsep.normalizePathSep)(_path.default.relative(dir, filePath)) : appPath;
                })));
            }
            const routeMatchingError = routeMatchingErrors[0] ?? null;
            const routeMatchingErrorsKey = routeMatchingErrors.map((error)=>error.message).join('\n\n') || null;
            if (numConflicting === 0 && routeMatchingErrorsKey !== null && routeMatchingErrorsKey !== previousRouteMatchingErrors) {
                for (const error of routeMatchingErrors){
                    _log.error(error.message);
                }
                const warning = (0, _strictroutematchingconfig.getStrictRouteMatchingDefaultWarning)(nextConfig);
                if (warning) {
                    _log.warnOnce(warning);
                }
            }
            // Turbopack reports route-matching failures as app-structure issues.
            // Webpack needs an HMR server error so dev can finish booting and surface
            // the problem to connected clients instead of throwing from this watcher.
            if (!opts.turbo) {
                if (numConflicting === 0 && routeMatchingError) {
                    hotReloader.setHmrServerError(routeMatchingError);
                } else if (numConflicting === 0 && previousRouteMatchingErrors) {
                    hotReloader.clearHmrServerError();
                }
            }
            previousRouteMatchingErrors = routeMatchingErrorsKey;
            for (const pageAppPaths of Object.values(appPagePaths)){
                pageAppPaths.sort(_apppaths.compareAppPaths);
            }
            (0, _normalizecatchallroutes.normalizeCatchAllRoutes)(appPaths);
            // Make sure to sort parallel routes to make the result deterministic.
            serverFields.appPathRoutes = Object.fromEntries(Object.entries(appPaths).map(([k, v])=>[
                    k,
                    v.sort(_apppaths.compareAppPaths)
                ]));
            await propagateServerField(opts, 'appPathRoutes', serverFields.appPathRoutes);
            // fsChecker replaces the removed dev matcher providers. Refresh its
            // definitions on every watcher pass so newly added routes can be ensured
            // and rendered without waiting for a separate matcher reload.
            const pageRouteDefinitions = [
                ...pageRoutes.map(({ route, filePath })=>({
                        kind: _routekind.RouteKind.PAGES,
                        pathname: route,
                        page: route,
                        bundlePath: _path.default.posix.join('pages', (0, _normalizepagepath.normalizePagePath)(route)),
                        filename: filePath,
                        ...opts.nextConfig.i18n ? {
                            i18n: {}
                        } : undefined
                    })),
                ...pageApiRoutes.map(({ route, filePath })=>({
                        kind: _routekind.RouteKind.PAGES_API,
                        pathname: route,
                        page: route,
                        bundlePath: _path.default.posix.join('pages', (0, _normalizepagepath.normalizePagePath)(route)),
                        filename: filePath,
                        ...opts.nextConfig.i18n ? {
                            i18n: {}
                        } : undefined
                    }))
            ];
            const appRouteDefinitions = [
                ...Object.entries(appPagePaths).map(([route, routeAppPaths])=>{
                    const page = (0, _apppaths.selectAppPageEntry)(route, routeAppPaths);
                    const filePath = appRouteFilePaths.get(page);
                    return {
                        kind: _routekind.RouteKind.APP_PAGE,
                        pathname: route,
                        page,
                        bundlePath: _path.default.posix.join('app', (0, _normalizepagepath.normalizePagePath)(page)),
                        filename: filePath,
                        appPaths: routeAppPaths
                    };
                }),
                ...appRouteHandlers.map(({ route, page, filePath })=>{
                    return {
                        kind: _routekind.RouteKind.APP_ROUTE,
                        pathname: route,
                        page,
                        bundlePath: _path.default.posix.join('app', (0, _normalizepagepath.normalizePagePath)(page)),
                        filename: filePath
                    };
                })
            ];
            opts.fsChecker.setRouteDefinitions('pageFile', pageRouteDefinitions);
            opts.fsChecker.setRouteDefinitions('appFile', appRouteDefinitions);
            // TODO: pass this to fsChecker/next-dev-server?
            serverFields.middleware = middlewareMatchers ? {
                match: null,
                page: '/',
                matchers: middlewareMatchers
            } : undefined;
            await propagateServerField(opts, 'middleware', serverFields.middleware);
            serverFields.hasAppNotFound = hasRootAppNotFound;
            opts.fsChecker.middlewareMatcher = ((_serverFields_middleware = serverFields.middleware) == null ? void 0 : _serverFields_middleware.matchers) ? (0, _middlewareroutematcher.getMiddlewareRouteMatcher)((_serverFields_middleware1 = serverFields.middleware) == null ? void 0 : _serverFields_middleware1.matchers) : undefined;
            const interceptionRoutes = (0, _generateinterceptionroutesrewrites.generateInterceptionRoutesRewrites)(Object.keys(appPaths), opts.nextConfig.basePath).map((item)=>(0, _filesystem.buildCustomRoute)('before_files_rewrite', item, opts.nextConfig.basePath, opts.nextConfig.experimental.caseSensitiveRoutes));
            opts.fsChecker.rewrites.beforeFiles.push(...interceptionRoutes);
            const exportPathMap = typeof nextConfig.exportPathMap === 'function' && await (nextConfig.exportPathMap == null ? void 0 : nextConfig.exportPathMap.call(nextConfig, {}, {
                dev: true,
                dir: opts.dir,
                outDir: null,
                distDir: distDir,
                buildId: 'development'
            })) || {};
            const exportPathMapEntries = Object.entries(exportPathMap || {});
            if (exportPathMapEntries.length > 0) {
                opts.fsChecker.exportPathMapRoutes = exportPathMapEntries.map(([key, value])=>(0, _filesystem.buildCustomRoute)('before_files_rewrite', {
                        source: key,
                        destination: `${value.page}${value.query ? '?' : ''}${_querystring.default.stringify(value.query)}`
                    }, opts.nextConfig.basePath, opts.nextConfig.experimental.caseSensitiveRoutes));
            }
            try {
                // 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, _utils.getSortedRoutes)(routedPages);
                opts.fsChecker.dynamicRoutes = sortedRoutes.map((page)=>{
                    const regex = (0, _routeregex.getNamedRouteRegex)(page, {
                        prefixRouteKeys: true,
                        includePrefix: true,
                        includeSuffix: true
                    });
                    return {
                        regex: regex.re.toString(),
                        namedRegex: regex.namedRegex,
                        routeKeys: regex.routeKeys,
                        match: (0, _routematcher.getRouteMatcher)(regex),
                        page
                    };
                });
                const dataRoutes = [];
                for (const page of sortedRoutes){
                    const route = (0, _builddataroute.buildDataRoute)(page, 'development');
                    const routeRegex = (0, _routeregex.getNamedRouteRegex)(route.page, {
                        prefixRouteKeys: true
                    });
                    dataRoutes.push({
                        ...route,
                        regex: routeRegex.re.toString(),
                        namedRegex: routeRegex.namedRegex,
                        routeKeys: routeRegex.routeKeys,
                        match: (0, _routematcher.getRouteMatcher)({
                            // TODO: fix this in the manifest itself, must also be fixed in
                            // upstream builder that relies on this
                            re: opts.nextConfig.i18n ? new RegExp((0, _builddataroute.addLocalePrefixToDataRouteRegex)(route.dataRouteRegex, 'development')) : new RegExp(route.dataRouteRegex),
                            groups: routeRegex.groups
                        })
                    });
                }
                opts.fsChecker.dynamicRoutes.unshift(...dataRoutes);
                // For Turbopack ADDED_PAGE and REMOVED_PAGE are implemented in hot-reloader-turbopack.ts
                // in order to avoid a race condition where ADDED_PAGE and REMOVED_PAGE are sent before Turbopack picked up the file change.
                if (!opts.turbo) {
                    const sortedRoutesChanged = prevSortedRoutes.length !== sortedRoutes.length || prevSortedRoutes.some((route, idx)=>route !== sortedRoutes[idx]);
                    // The first aggregation has nothing to compare against, so every
                    // route would look added to a client that is already connected.
                    if (hasComputedSortedRoutes && sortedRoutesChanged) {
                        const addedRoutes = sortedRoutes.filter((route)=>!prevSortedRoutes.includes(route));
                        const removedRoutes = prevSortedRoutes.filter((route)=>!sortedRoutes.includes(route));
                        // emit the change so clients fetch the update
                        hotReloader.send({
                            type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE,
                            data: [
                                {
                                    devPagesManifest: true
                                }
                            ]
                        });
                        addedRoutes.forEach((route)=>{
                            hotReloader.send({
                                type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.ADDED_PAGE,
                                data: [
                                    route
                                ]
                            });
                        });
                        removedRoutes.forEach((route)=>{
                            hotReloader.send({
                                type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.REMOVED_PAGE,
                                data: [
                                    route
                                ]
                            });
                        });
                    }
                }
                prevSortedRoutes = sortedRoutes;
                hasComputedSortedRoutes = true;
                if (enabledTypeScript) {
                    var _nextConfig_experimental;
                    // Using === false to make the check clearer.
                    if (typescriptStatusFromLastAggregation === false) {
                        // we tolerate the error here as this is best effort
                        // and the manual install command will be shown
                        await verifyTypeScript(opts).then(()=>{
                            tsconfigChange = true;
                        }).catch(()=>{});
                    }
                    if (writeEnvDefinitions && ((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.typedEnv)) {
                        // TODO: The call to propagateServerField 'loadEnvConfig' causes the env to be loaded twice on env file changes.
                        const loadEnvConfig = require('@next/env').loadEnvConfig;
                        const { loadedEnvFiles } = loadEnvConfig(dir, process.env.NODE_ENV === 'development', // Silent as it's the second time `loadEnvConfig` is called in this pass.
                        undefined, true);
                        const createEnvDefinitions = require('../experimental/create-env-definitions').createEnvDefinitions;
                        await createEnvDefinitions({
                            distDir,
                            loadedEnvFiles: [
                                ...loadedEnvFiles,
                                {
                                    path: nextConfig.configFileName,
                                    env: nextConfig.env,
                                    contents: ''
                                }
                            ]
                        });
                    }
                    const routeTypesManifest = await (0, _routetypesutils.createRouteTypesManifest)({
                        dir,
                        pageRoutes,
                        appRoutes,
                        layoutRoutes,
                        slots,
                        redirects: opts.nextConfig.redirects,
                        rewrites: opts.nextConfig.rewrites,
                        // Ensure relative paths in validator.ts are computed from validatorFilePath,
                        // matching behavior of build and CLI typegen.
                        validatorFilePath,
                        appRouteHandlers,
                        pageApiRoutes
                    });
                    await (0, _routetypesutils.writeRouteTypesManifest)(routeTypesManifest, routeTypesFilePath, opts.nextConfig);
                    await (0, _routetypesutils.writeValidatorFile)(routeTypesManifest, validatorFilePath, Boolean(nextConfig.experimental.strictRouteTypes));
                    // Generate cache-life types if cacheLife config exists
                    const cacheLifeFilePath = _path.default.join(distTypesDir, 'cache-life.d.ts');
                    (0, _cachelifetypeutils.writeCacheLifeTypes)(opts.nextConfig.cacheLife, cacheLifeFilePath);
                    await (0, _rootparamstypeutils.writeRootParamsTypes)(routeTypesManifest, _path.default.join(distTypesDir, 'root-params.d.ts'));
                }
                if (!resolved) {
                    resolve();
                    resolved = true;
                }
            } catch (e) {
                if (!resolved) {
                    reject(e);
                    resolved = true;
                } else {
                    _log.warn('Failed to reload dynamic routes:', e);
                }
            }
        });
        wp.watch({
            directories: [
                dir
            ],
            startTime: 0
        });
    });
    const clientPagesManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.DEV_CLIENT_PAGES_MANIFEST}`;
    opts.fsChecker.devVirtualFsItems.add(clientPagesManifestPath);
    const devMiddlewareManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.DEV_CLIENT_MIDDLEWARE_MANIFEST}`;
    opts.fsChecker.devVirtualFsItems.add(devMiddlewareManifestPath);
    const devTurbopackMiddlewareManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST}`;
    opts.fsChecker.devVirtualFsItems.add(devTurbopackMiddlewareManifestPath);
    async function requestHandler(req, res) {
        const parsedUrl = (0, _url.parseUrl)(req.url || '/');
        const pathname = parsedUrl !== undefined ? parsedUrl.pathname : null;
        if (pathname !== null && pathname.includes(clientPagesManifestPath)) {
            res.statusCode = 200;
            res.setHeader('Content-Type', _constants1.JSON_CONTENT_TYPE_HEADER);
            res.end(JSON.stringify({
                pages: prevSortedRoutes.filter((route)=>!opts.fsChecker.appFiles.has(route))
            }));
            return {
                finished: true
            };
        }
        if (pathname !== null && (pathname.includes(devMiddlewareManifestPath) || pathname.includes(devTurbopackMiddlewareManifestPath))) {
            var _serverFields_middleware;
            res.statusCode = 200;
            res.setHeader('Content-Type', _constants1.JSON_CONTENT_TYPE_HEADER);
            res.end(JSON.stringify(((_serverFields_middleware = serverFields.middleware) == null ? void 0 : _serverFields_middleware.matchers) || []));
            return {
                finished: true
            };
        }
        return {
            finished: false
        };
    }
    function logErrorWithOriginalStack(err, type) {
        if (err instanceof Error) {
            err.message = (0, _magicidentifier.deobfuscateText)(err.message);
        }
        if (err instanceof _utils2.ModuleBuildError) {
            // Errors that may come from issues from the user's code
            _log.error(err.message);
        } else if (err instanceof _internalerror.TurbopackInternalError) {
        // An internal Turbopack error that has been handled by next-swc, written
        // to disk and a simplified message shown to user on the Rust side.
        } else if (type === 'warning') {
            _log.warn(err);
        } else if (type === 'app-dir') {
            _log.error(err);
        } else if (type) {
            _log.error(`${type}:`, err);
        } else {
            _log.error(err);
        }
    }
    return {
        serverFields,
        hotReloader,
        requestHandler,
        logErrorWithOriginalStack,
        async ensureMiddleware (requestUrl) {
            if (!serverFields.actualMiddlewareFile) return;
            return hotReloader.ensurePage({
                page: serverFields.actualMiddlewareFile,
                clientOnly: false,
                definition: undefined,
                url: requestUrl
            });
        }
    };
}
async function setupDevBundler(opts) {
    var _opts_nextConfig_experimental;
    const isSrcDir = _path.default.relative(opts.dir, opts.pagesDir || opts.appDir || '').startsWith('src');
    await (0, _installbindings.installBindings)((_opts_nextConfig_experimental = opts.nextConfig.experimental) == null ? void 0 : _opts_nextConfig_experimental.useWasmBinary);
    // Set up code frame renderer for error formatting
    const { installCodeFrameSupport } = require('../install-code-frame');
    installCodeFrameSupport();
    const result = await startWatcher({
        ...opts,
        isSrcDir
    });
    opts.telemetry.record((0, _events.eventCliSession)(opts.nextConfig, {
        webpackVersion: 5,
        isSrcDir,
        turboFlag: !!opts.turbo,
        cliCommand: 'dev',
        appDir: !!opts.appDir,
        pagesDir: !!opts.pagesDir,
        isCustomServer: !!opts.isCustomServer,
        hasNowJson: !!await (0, _findup.default)('now.json', {
            cwd: opts.dir
        })
    }));
    // Track build features for dev server here:
    opts.telemetry.record({
        eventName: _events.EVENT_BUILD_FEATURE_USAGE,
        payload: {
            featureName: 'turbopackFileSystemCache',
            invocationCount: (0, _utils2.isFileSystemCacheEnabledForDev)(opts.nextConfig) ? 1 : 0
        }
    });
    return result;
}
 // Returns a trace rewritten through Turbopack's sourcemaps

//# sourceMappingURL=setup-dev-bundler.js.map