import type { QwikVitePlugin } from '@qwik.dev/core/optimizer'; import fs from 'node:fs'; import { readFile } from 'node:fs/promises'; import { basename, extname, join, resolve } from 'node:path'; import { findExports, findStaticImports, parseStaticImport } from 'mlly'; import type { ConfigEnv, EnvironmentOptions, HotUpdateOptions, Plugin, PluginOption, Rolldown, UserConfig, ViteDevServer, } from 'vite'; import { loadEnv } from 'vite'; import { isEntryName, isErrorName, isIndexModule, isLayoutModule, isMenuFileName, isPluginModule, isServiceWorkerName, normalizePath, normalizePathKey, removeExtension, } from '../../utils/fs'; import { parseRoutesDir } from '../build'; import { createBuildContext, resetBuildContext, resolveBasePathname } from '../context'; import { createMdxTransformer, type MdxTransform } from '../markdown/mdx'; import { transformMenu } from '../markdown/menu'; import { generateQwikRouterEntries } from '../runtime-generation/generate-entries'; import { generateQwikRouterConfig } from '../runtime-generation/generate-qwik-router-config'; import type { RouteLoaderSourceFiles } from '../runtime-generation/generate-routes'; import { generateServiceWorkerRegister } from '../runtime-generation/generate-service-worker'; import { getServerExcludedRoutes } from '../runtime-generation/server-exclude'; import type { RoutingContext } from '../types'; import { bundleServiceWorkerChunks } from './bundle-service-worker'; import { getRouteImports } from './get-route-imports'; import { imagePlugin } from './image-jsx'; import { collectServerFnModuleIds } from './server-fns'; import type { QwikCityVitePluginOptions, QwikRouterPluginApi, QwikRouterVitePluginOptions, } from './types'; import { validatePlugin } from './validate-plugin'; import { getRouterIndexTags, makeRouterDevMiddleware, sendRouterCssHotUpdate, } from './dev-middleware'; export const QWIK_ROUTER_CONFIG_ID = '@qwik-router-config'; /** * This virtual module is used to generate dynamic entries for user route files, which are added as * dynamic imports to the qwik-router-config as a way to create new entry points for the build. */ const QWIK_ROUTER_ENTRIES_ID = '@qwik-router-entries'; const QWIK_ROUTER = '@qwik.dev/router'; const QWIK_ROUTER_SW_REGISTER = '@qwik-router-sw-register'; const VIRTUAL_SERVER_FNS = 'virtual:qwik-router-server-fns'; type BuildContextRef = { current: RoutingContext | null }; /** * @deprecated Use `qwikRouter` instead. Will be removed in V3 * @public */ export function qwikCity(userOpts?: QwikCityVitePluginOptions): PluginOption[] { return qwikRouter(userOpts); } /** @public */ export function qwikRouter(userOpts?: QwikRouterVitePluginOptions): PluginOption[] { const buildContextRef: BuildContextRef = { current: null }; return [ qwikRouterPlugin(userOpts, buildContextRef), serverFnsPlugin(buildContextRef), ...imagePlugin(userOpts), ]; } /** Replace or strip loader placeholders in a bundle chunk. */ export function replaceLoaderPlaceholders( code: string, loadersByFile: Map ): string { // Missing loaders must not leave placeholder strings in the trie. return code.replace( /(_R|_D)\s*:\s*(["'`])__LOADERS:([^"'`]+)__\2\s*,?/g, (_match, field: string, _q, paths: string) => { const filePaths = (JSON.parse(`"${paths}"`) as string).split('|'); const hashes: string[] = []; for (const filePath of filePaths) { const fileHashes = loadersByFile.get(normalizePathKey(filePath)); if (fileHashes) { hashes.push(...fileHashes); } } if (hashes.length > 0) { return `${field}: ${JSON.stringify(hashes)},`; } // Trailing commas inside object literals are legal, so removing a mid-object entry // (and the trailing comma it emitted with) leaves the surrounding trie literal valid. return ''; } ); } export function addRouteLoaderHash( loadersByFile: Map, filePath: string, hash: string ) { const normalizedPath = normalizePathKey(filePath).split(/[?#]/, 1)[0]; const existing = loadersByFile.get(normalizedPath); if (!existing) { loadersByFile.set(normalizedPath, [hash]); return true; } if (!existing.includes(hash)) { existing.push(hash); return true; } return false; } export function clearRouteLoaderHashes(loadersByFile: Map, filePath: string) { return loadersByFile.delete(normalizePathKey(filePath).split(/[?#]/, 1)[0]); } export function isRouterSourceFilePath(filePath: string) { const fileName = basename(filePath); const extlessName = removeExtension(fileName); return ( isMenuFileName(fileName) || isIndexModule(extlessName) || isErrorName(extlessName) || isLayoutModule(extlessName) || isEntryName(extlessName) || isServiceWorkerName(extlessName) || isPluginModule(extlessName) ); } function isPathInDir(filePath: string, dirPath: string) { return filePath === dirPath || filePath.startsWith(`${dirPath}/`); } function isRouterSourceFileForContext(filePath: string, ctx: RoutingContext) { const normalizedPath = normalizePath(filePath); return ( isRouterSourceFilePath(normalizedPath) && (isPathInDir(normalizedPath, ctx.opts.routesDir) || isPathInDir(normalizedPath, ctx.opts.serverPluginsDir)) ); } function isDiscoveredRouteLoaderSource( filePath: string, sourceFiles: RouteLoaderSourceFiles | undefined ) { if (!sourceFiles) { return false; } const normalizedPath = normalizePath(filePath); for (const files of sourceFiles.values()) { if (files.includes(normalizedPath)) { return true; } } return false; } type SourceResolver = (specifier: string, importer: string) => Promise; export async function findRouteLoaderSourceFiles( ctx: RoutingContext, resolveSource: SourceResolver ): Promise { const sources = new Map(); const owners = new Set(); collectRouteLoaderOwners(ctx.routeTrie, owners); for (const plugin of ctx.serverPlugins) { owners.add(plugin.filePath); } await Promise.all( [...owners].map((owner) => collectRouteLoaderSources(owner, owner, resolveSource, sources)) ); return sources; } function collectRouteLoaderOwners(node: RoutingContext['routeTrie'], owners: Set) { for (const file of node._files) { if (file.type === 'layout' || file.type === 'route') { owners.add(file.filePath); } } for (const child of node.children.values()) { collectRouteLoaderOwners(child, owners); } } async function collectRouteLoaderSources( owner: string, filePath: string, resolveSource: SourceResolver, sources: Map, seen = new Set([owner]) ) { let code: string, exportEntries: ReturnType | null; try { code = await readFile(filePath, 'utf-8'); exportEntries = findExports(code); if (!exportEntries) { return; } } catch { return; } const importedFactories = new Map(); for (const entry of findStaticImports(code)) { const parsed = parseStaticImport(entry); if (parsed.defaultImport) { importedFactories.set(parsed.defaultImport, entry.specifier); } if (parsed.namedImports) { for (const localName of Object.values(parsed.namedImports)) { importedFactories.set(localName, entry.specifier); } } } const specifiers = new Set(); for (const exp of exportEntries) { if (exp.specifier) { specifiers.add(exp.specifier); } else if (/^export\s+(?:const|let|var)\s*{/.test(exp.code)) { const factoryName = code.slice(exp.end).match(/^\s*([\w$]+)(?:\s*<[^;()]*>)?\s*\(/)?.[1]; const specifier = factoryName && importedFactories.get(factoryName); if (specifier) { specifiers.add(specifier); } } } for (const specifier of specifiers) { const resolved = await resolveSource(specifier, filePath); if (!resolved || resolved.charCodeAt(0) === 0) { continue; } const resolvedPath = normalizePath(resolved.split(/[?#]/, 1)[0]); let ownerSources = sources.get(owner); if (!ownerSources) { sources.set(owner, (ownerSources = [])); } if (!ownerSources.includes(resolvedPath)) { ownerSources.push(resolvedPath); } if (!seen.has(resolvedPath)) { seen.add(resolvedPath); await collectRouteLoaderSources(owner, resolvedPath, resolveSource, sources, seen); } } } export function invalidateRouterConfigModules(server: ViteDevServer) { const modules: NonNullable>[] = []; const moduleGraphs = new Set(); moduleGraphs.add(server.moduleGraph); const environments = (server as any).environments; if (environments) { for (const environment of Object.values(environments)) { const graph = (environment as any)?.moduleGraph; if (graph) { moduleGraphs.add(graph); } } } for (const graph of moduleGraphs) { const mod = graph.getModuleById(QWIK_ROUTER_CONFIG_ID); if (mod) { graph.invalidateModule(mod); modules.push(mod); } } return modules; } function qwikRouterPlugin( userOpts: QwikRouterVitePluginOptions | undefined, buildContextRef: BuildContextRef ) { let ctx: RoutingContext | null = null; let mdxTransform: MdxTransform | null = null; let rootDir: string | null = null; let qwikPlugin: QwikVitePlugin | null; let outDir: string | null = null; let viteCommand: string; let devServer: ViteDevServer | null = null; let devSsrServer = userOpts?.devSsrServer; const routesDir = userOpts?.routesDir ?? 'src/routes'; const serverPluginsDir = userOpts?.serverPluginsDir ?? routesDir; /** Map from source file path to array of routeLoader$ hashes found in that file */ const loadersByFile = new Map(); let reExportedRouteLoaderSources: RouteLoaderSourceFiles | undefined; /** SSG include/exclude from the adapter (see `_setSsgRoutes`); drives the server-route prune. */ let ssgRoutePatterns: { include?: string[]; exclude?: string[] } | undefined; /** Extensionless ids of the server entries that must import the generated config. */ let serverEntryIds: string[] = []; const api: QwikRouterPluginApi = { getBasePathname: () => ctx?.opts.basePathname ?? '/', getRoutes: () => { return ctx?.routes.slice() ?? []; }, getServiceWorkers: () => { return ctx?.serviceWorkers.slice() ?? []; }, _setSsgRoutes: (include, exclude) => { ssgRoutePatterns = include?.length ? { include, exclude } : undefined; }, }; type P = Plugin & { api: T }; const plugin: P = { name: 'vite-plugin-qwik-router', enforce: 'pre', api, async config(_viteConfig, viteEnv) { viteCommand = viteEnv.command; const updatedViteConfig: UserConfig = { define: { 'globalThis.__DEFAULT_LOADERS_SERIALIZATION_STRATEGY__': JSON.stringify( userOpts?.defaultLoadersSerializationStrategy || 'auto' ), 'globalThis.__NO_TRAILING_SLASH__': JSON.stringify(userOpts?.trailingSlash === false), 'globalThis.__QWIK_ROUTER_BASE_PATHNAME__': JSON.stringify( resolveBasePathname(userOpts, _viteConfig.base || '/') ), 'globalThis.__SSR_CACHE_SIZE__': JSON.stringify( viteEnv.command === 'serve' ? 0 : (userOpts?.ssrCacheSize ?? 50) ), 'globalThis.__STRICT_LOADERS__': JSON.stringify(userOpts?.strictLoaders !== false), }, appType: 'custom', resolve: { dedupe: [QWIK_ROUTER, '@builder.io/qwik-city'], alias: [ { find: '@builder.io/qwik-city', replacement: '@qwik.dev/router' }, { find: /^@builder\.io\/qwik-city\/(.*)/, replacement: '@qwik.dev/router/$1' }, { find: '@qwik-city-plan', replacement: QWIK_ROUTER_CONFIG_ID }, { find: '@qwik-city-entries', replacement: QWIK_ROUTER_ENTRIES_ID }, { find: '@qwik-city-sw-register', replacement: QWIK_ROUTER_SW_REGISTER }, ], }, optimizeDeps: { // Let Vite find all app deps, these are not part of the static imports from `src/root` entries: [ `${routesDir}/**/index*`, `${routesDir}/**/layout*`, `${serverPluginsDir}/plugin@*`, ], // These need processing by the optimizer during dev exclude: [ QWIK_ROUTER, QWIK_ROUTER_CONFIG_ID, QWIK_ROUTER_ENTRIES_ID, QWIK_ROUTER_SW_REGISTER, ], }, // Duplicated from configEnvironment to support legacy vite build --ssr compatibility ssr: { external: ['node:async_hooks'], noExternal: [ QWIK_ROUTER, QWIK_ROUTER_CONFIG_ID, QWIK_ROUTER_ENTRIES_ID, QWIK_ROUTER_SW_REGISTER, // We've had reports of bundling issues with zod 'zod', ], }, }; return updatedViteConfig; }, configEnvironment(name: string, _config: EnvironmentOptions, _env: ConfigEnv) { // Use environment name to distinguish server vs client — config.consumer is not yet set // at the time this hook is called. Adapters may add their own server environment (e.g. `ssg`), // which needs the same externalization as `ssr`. if (name === 'ssr' || name === 'ssg') { return { resolve: { external: ['node:async_hooks'], noExternal: [ QWIK_ROUTER, QWIK_ROUTER_CONFIG_ID, QWIK_ROUTER_ENTRIES_ID, QWIK_ROUTER_SW_REGISTER, 'zod', ], }, } satisfies EnvironmentOptions; } return {}; }, async configResolved(config) { Object.assign(process.env, loadEnv(config.mode, process.cwd(), '')); rootDir = resolve(config.root); const target = config.build?.ssr || config.mode === 'ssr' ? 'ssr' : 'client'; ctx = createBuildContext( rootDir!, config.base, userOpts, target, !userOpts?.staticImportRoutes ); buildContextRef.current = ctx; await validatePlugin(ctx.opts); mdxTransform = await createMdxTransformer(ctx); // Use double type assertion to avoid TS "Excessive stack depth comparing types" error // when comparing QwikVitePlugin with Plugin types qwikPlugin = config.plugins.find( (p) => p.name === 'vite-plugin-qwik' ) as any as QwikVitePlugin; if (!qwikPlugin) { throw new Error('Missing vite-plugin-qwik'); } // Register callback to discover routeLoader$ hashes from optimizer segments qwikPlugin.api.onSegment((parentId, segment) => { if (segment.ctxName === 'routeLoader$') { const changed = addRouteLoaderHash(loadersByFile, parentId, segment.hash); // Refresh the dev route plan with newly discovered loaders. if (changed && devServer) { invalidateRouterConfigModules(devServer); } } }); if (typeof devSsrServer !== 'boolean') { // read the old option from qwik plugin devSsrServer = qwikPlugin.api._oldDevSsrServer(); } qwikPlugin.api.registerBundleGraphAdder?.((manifest) => { return getRouteImports(ctx!.routes, manifest); }); outDir = config.build?.outDir; serverEntryIds = getServerEntryIds( rootDir!, qwikPlugin.api.getOptions().srcDir ?? undefined, config.build?.ssr, config.build?.rolldownOptions?.input ); }, async configureServer(server) { devServer = server; // recursively watch all route files in the src/routes directory // chokidar 4 dropped globs, so watch directories and filter. const toWatch = [ctx!.opts.routesDir, ctx!.opts.serverPluginsDir]; server.watcher.add(toWatch); await new Promise((resolve) => setTimeout(resolve, 1000)); server.watcher.on('change', (path) => { if (!isRouterSourceFileForContext(path, ctx!)) { return; } clearRouteLoaderHashes(loadersByFile, path); ctx!.isDirty = true; invalidateRouterConfigModules(server); }); if (userOpts?.devSsrServer !== false) { // this callback runs after all other middlewares have been added, so we can SSR as the last middleware return () => { server.middlewares.use(makeRouterDevMiddleware(server, ctx!)); }; } }, hotUpdate({ file, modules, timestamp }: HotUpdateOptions) { const server = devServer; if (!server) { return; } // Route CSS is injected as a ; swap it in place rather than forcing a restart. if (sendRouterCssHotUpdate(server, file, timestamp)) { return []; } const clearedLoaderHashes = clearRouteLoaderHashes(loadersByFile, file); if (!ctx) { return; } // hotUpdate runs per environment, so return this environment's config module. const configModule = this.environment.moduleGraph.getModuleById(QWIK_ROUTER_CONFIG_ID); if (!isRouterSourceFileForContext(file, ctx)) { if ( clearedLoaderHashes || isDiscoveredRouteLoaderSource(file, reExportedRouteLoaderSources) ) { invalidateRouterConfigModules(server); return configModule ? [...modules, configModule] : modules; } return; } ctx.isDirty = true; invalidateRouterConfigModules(server); return configModule ? [...modules, configModule] : modules; }, transformIndexHtml() { if (viteCommand !== 'serve') { return; } return getRouterIndexTags(devServer!); }, buildStart() { resetBuildContext(ctx); // The client build still needs the config in its module graph for route discovery and // symbol extraction, so emit it as an explicit entry chunk here. if (this.environment.mode === 'build' && this.environment.config.consumer === 'client') { this.emitFile({ type: 'chunk', id: QWIK_ROUTER_CONFIG_ID }); } }, resolveId(id) { if (id === QWIK_ROUTER_CONFIG_ID || id === QWIK_ROUTER_ENTRIES_ID) { return { id, // user entries added in the routes, like src/routes/service-worker.ts // are added as dynamic imports to the qwik-router-config as a way to create // a new entry point for the build. Ensure these are not treeshaken. moduleSideEffects: 'no-treeshake', }; } if (id === QWIK_ROUTER_SW_REGISTER) { return id; } return null; }, async load(id) { if (ctx) { if (id.endsWith(QWIK_ROUTER_ENTRIES_ID)) { // @qwik-router-entries return generateQwikRouterEntries(ctx); } const isRouterConfig = id.endsWith(QWIK_ROUTER_CONFIG_ID); const isSwRegister = id.endsWith(QWIK_ROUTER_SW_REGISTER); if (isRouterConfig || isSwRegister) { if (ctx.isDirty) { await parseRoutesDir(ctx); ctx.isDirty = false; ctx.diagnostics.forEach((d) => { this.warn(d.message); }); } if (isRouterConfig) { // @qwik-router-config // In dev server mode, loadersByFile is kept current via onSegment + module // invalidation, so pass it directly. In build mode the config is loaded before // route files are optimized, so loadersByFile is empty here; pass undefined to // emit __LOADERS:...__ placeholders that generateBundle replaces after optimization. const isServerConsumer = this.environment.config.consumer === 'server'; // Prune the deployed SSR plan (drop prerendered server-free routes so their chunks // tree-shake out). The adapter's dedicated `ssg` environment renders every page, so it // (like the client and dev) keeps the full trie — keyed on the environment name. const serverExcludePaths = isServerConsumer && !devServer && this.environment.name !== 'ssg' ? await getServerExcludedRoutes(ctx, ssgRoutePatterns) : undefined; reExportedRouteLoaderSources = await findRouteLoaderSourceFiles( ctx, async (specifier, importer) => { const resolved = await this.resolve(specifier, importer, { skipSelf: true }); return resolved?.id; } ); return generateQwikRouterConfig( ctx, qwikPlugin!, isServerConsumer, devServer ? loadersByFile : undefined, serverExcludePaths, reExportedRouteLoaderSources ); } if (isSwRegister) { // @qwik-router-sw-register return generateServiceWorkerRegister(ctx); } } } return null; }, async transform(code, id) { // The server entry registers the generated config up front, so the runtime's getters find // it; the client loads it lazily as its own chunk. Appended to keep the source map lines. if (this.environment.config.consumer === 'server' && isServerEntryId(id, serverEntryIds)) { return { code: `${code}\nimport '${QWIK_ROUTER_CONFIG_ID}';`, map: null }; } const isVirtualId = id.startsWith('\0'); if (isVirtualId) { return; } const ext = extname(id).toLowerCase(); const isMD = ext === '.md' || ext === '.mdx'; if (ctx && isMD) { const fileName = basename(id); if (isMenuFileName(fileName)) { const menuCode = await transformMenu(ctx.opts, id, code); return { code: menuCode, map: null }; } if (mdxTransform) { try { const mdxResult = await mdxTransform(code, id); return mdxResult; } catch (e: any) { if (e && typeof e == 'object' && 'position' in e && 'reason' in e) { const column = (e as any).position?.start.column; const line = (e as any).position?.start.line; const err: Rolldown.RolldownError = Object.assign(new Error(e.reason), { id, plugin: 'qwik-router-mdx', loc: { column: column, line: line, }, stack: '', }); this.error(err); } else if (e instanceof Error) { this.error(e); } else { this.error(String(e)); } } } } return null; }, async generateBundle(_, bundles) { // A separate server build skips onSegment, so recover routeLoader$ hashes from the manifest. const manifest = qwikPlugin!.api.getManifest(); if (manifest) { const srcDir = qwikPlugin!.api.getOptions().srcDir!; for (const symbol of Object.values(manifest.symbols)) { if (symbol.ctxName === 'routeLoader$' && symbol.origin) { addRouteLoaderHash(loadersByFile, resolve(srcDir, symbol.origin), symbol.hash); } } } // Replace __LOADERS:...__ placeholder strings with actual loader hash arrays. // Runs even when no routeLoader$ was found so placeholders collapse to `void 0` // (otherwise they remain as raw strings and the client iterates them per-character). for (const chunk of Object.values(bundles)) { if (chunk.type === 'chunk' && chunk.code.includes('__LOADERS:')) { chunk.code = replaceLoaderPlaceholders(chunk.code, loadersByFile); } } // Turn entry and service worker chunks into entry points if (this.environment.config.consumer === 'client') { const serviceWorkerChunks = ctx!.serviceWorkers .map((sw) => findEntryChunk(bundles, sw.filePath)) .filter((c): c is Rolldown.OutputChunk => !!c); await bundleServiceWorkerChunks( bundles, serviceWorkerChunks, this.environment.config.build.minify ); for (const entry of [...ctx!.entries, ...ctx!.serviceWorkers]) { const c = findEntryChunk(bundles, entry.filePath); if (c) { c.fileName = entry.chunkFileName; } } } }, closeBundle: { sequential: true, async handler() { if (this.environment.config.consumer === 'server' && outDir) { await generateServerPackageJson(outDir); } }, }, }; return plugin; } function findEntryChunk(bundles: Rolldown.OutputBundle, filePath: string) { const extensionlessFilePath = removeExtension(filePath); for (const output of Object.values(bundles)) { if ( output.type === 'chunk' && output.isDynamicEntry && output.facadeModuleId && removeExtension(normalizePath(output.facadeModuleId)) === extensionlessFilePath ) { return output; } } return undefined; } async function generateServerPackageJson(outDir: string) { await fs.promises.mkdir(outDir, { recursive: true }); const serverPackageJsonPath = join(outDir, 'package.json'); let packageJson = {}; // we want to keep the content of an existing file: if (fs.existsSync(serverPackageJsonPath)) { const content = await fs.promises.readFile(serverPackageJsonPath, 'utf-8'); const contentAsJson = JSON.parse(content); packageJson = { ...contentAsJson, }; } packageJson = { ...packageJson, type: 'module', }; const serverPackageJsonCode = JSON.stringify(packageJson, null, 2); await fs.promises.writeFile(serverPackageJsonPath, serverPackageJsonCode); } /** * Separate plugin that tracks modules containing server$ functions during SSR builds and generates * `virtual:qwik-router-server-fns` — a virtual module that statically imports all such modules so * their `_regSymbol` side effects run before any RPC request arrives. */ function serverFnsPlugin(buildContextRef: BuildContextRef): Plugin { const RESOLVED_ID = '\0' + VIRTUAL_SERVER_FNS; const serverFnModules = new Set(); let serverFnsReady: Promise | null = null; function reset() { serverFnModules.clear(); serverFnsReady = null; } reset(); async function collectServerFnModules(this: Rolldown.PluginContext) { if (serverFnsReady) { await serverFnsReady; return; } serverFnsReady = (async () => { const ctx = buildContextRef.current; if (!ctx) { return; } const moduleIds = await collectServerFnModuleIds(ctx, RESOLVED_ID, this); for (let i = 0; i < moduleIds.length; i++) { serverFnModules.add(moduleIds[i]); } })(); await serverFnsReady; } return { name: 'vite-plugin-qwik-router-server-fns', buildStart() { reset(); }, resolveId(id) { if (id === VIRTUAL_SERVER_FNS) { return { id: RESOLVED_ID, moduleSideEffects: 'no-treeshake' }; } }, load: { order: 'pre', async handler(id) { const isServerBuild = this.environment.config.consumer === 'server' && this.environment.mode === 'build'; if (id === RESOLVED_ID) { if (isServerBuild) { await collectServerFnModules.call(this); } if (!isServerBuild || serverFnModules.size === 0) { return 'export const importEagerModules = () => Promise.resolve();\n'; } // Deliberately dynamic imports behind a function: a static import here // would evaluate the server$ modules during the config's own import // phase, before runtime module bodies initialize (TDZ in bundled SSR). return ( 'export const importEagerModules = () =>\n Promise.all([\n' + [...serverFnModules].map((mod) => ` import(${JSON.stringify(mod)}),`).join('\n') + '\n ]);\n' ); } return null; }, }, }; } /** * The server entries: `src/entry.ssr` (what the dev server renders through) plus the configured SSR * build inputs, which may be virtual ids. */ export function getServerEntryIds( rootDir: string, srcDir: string | undefined, buildSsr: string | boolean | undefined, input: string | string[] | Record | undefined ): string[] { const candidates: string[] = []; if (srcDir) { candidates.push(resolve(srcDir, 'entry.ssr')); } if (typeof buildSsr === 'string') { candidates.push(buildSsr); } if (typeof input === 'string') { candidates.push(input); } else if (Array.isArray(input)) { candidates.push(...input); } else if (input) { candidates.push(...Object.values(input)); } return candidates.map((candidate) => normalizeEntryId(candidate, rootDir)); } export function isServerEntryId(id: string, serverEntryIds: string[]): boolean { const entryId = normalizeEntryId(id.split('?', 1)[0], ''); return serverEntryIds.includes(entryId); } const isVirtualEntryId = (id: string) => id.startsWith('@') || id.startsWith('\0'); /** Absolute path without its script extension, or the id itself for a virtual entry. */ function normalizeEntryId(id: string, rootDir: string) { if (isVirtualEntryId(id)) { return id; } const absolute = rootDir ? resolve(rootDir, id) : id; return normalizePath(absolute).replace(/\.[cm]?[jt]sx?$/, ''); }