Superpositional
AboutReview principlesPricingBlogGalleryAsk a RepoFAQ…
← Back to galleryAsk this repo
Approved · 0 retained findingsvitejs/vite#21626

feat: support bundled dev mode in ssr

Input

PR author’s description

<!-- - What is this PR solving? Write a clear and concise description. - Reference the issues it solves (e.g. `fixes #123`). - What other alternatives have you explored? - Are there any parts you think require more…

PR diff

Current GitHub diff ↗
packages/vite/src/node/ssr/fetchModule.ts · patch excerpt
-import { pathToFileURL } from 'node:url'+import path from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'
Browse 30 changed files
packages/vite/src/node/ssr/fetchModule.ts+210 −8
@@ -1,15 +1,24 @@-import { pathToFileURL } from 'node:url'+import path from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url' import type { FetchResult } from 'vite/module-runner'-import type { EnvironmentModuleNode, TransformResult } from '..'+import type { TransformResult } from '..' import {   MODULE_RUNNER_SOURCEMAPPING_SOURCE,   SOURCEMAPPING_URL, } from '../../shared/constants'-import { encodeSourceURL, unwrapId } from '../../shared/utils'+import type { ViteFetchResult } from '../../shared/invokeMethods'+import { cleanUrl, encodeSourceURL, unwrapId } from '../../shared/utils' import { tryNodeResolve } from '../plugins/resolve'+import type { BundledDev } from '../server/bundledDev' import type { DevEnvironment } from '../server/environment' import { genSourceMapUrl } from '../server/sourcemap'-import { isBuiltin, isExternalUrl, isFilePathESM } from '../utils'+import {+  isBuiltin,+  isExternalUrl,+  isFilePathESM,+  normalizePath,+} from '../utils'+import { ssrTransform } from './ssrTransform'  export interface FetchModuleOptions {   cached?: boolean@@ -43,7 +52,13 @@ export async function fetchModule(    // if there is no importer, the file is an entry point   // entry points are always internalized-  if (!isFileUrl && importer && url[0] !== '.' && url[0] !== '/') {+  if (+    !isFileUrl &&+    importer &&+    url[0] !== '.' &&+    url[0] !== '/' &&+    !isBundledChunkUrl(environment, url)+  ) {     const { isProduction, root } = environment.config     const { externalConditions, dedupe, preserveSymlinks } =       environment.config.resolve@@ -80,6 +95,12 @@ export async function fetchModule(    url = unwrapId(url) +  const bundledDev = environment.bundledDev++  if (bundledDev) {+    return fetchBundledModule(environment, bundledDev, url, importer, options)+  }+   const mod = await environment.moduleGraph.ensureEntryFromUrl(url)   const cached = !!mod.transformResult @@ -99,7 +120,7 @@ export async function fetchModule(   }    if (options.inlineSourceMap !== false) {-    result = inlineSourceMap(mod, result, options.startOffset)+    result = inlineSourceMap(mod.id!, result, options.startOffset)   }    // remove shebang@@ -115,13 +136,153 @@ export async function fetchModule(   } } +async function fetchBundledModule(+  environment: DevEnvironment,+  bundledDev: BundledDev,+  url: string,+  importer: string | undefined,+  options: FetchModuleOptions,+) {+  await bundledDev._waitForInitialBuildSuccess()++  if (url.startsWith('/@vite/lazy?')) {+    const { searchParams } = new URL(url, 'http://localhost')+    const moduleId = searchParams.get('id')!+    const clientId = searchParams.get('clientId')!+    const lazyResult = await bundledDev.triggerLazyBundling(moduleId, clientId)+    if (lazyResult == null) {+      throw new Error(`unknown request: ${url}`)+    }+    // This module is invalidated immediately, so url/id do not matter+    const result: ViteFetchResult = {+      code: lazyResult.code,+      url,+      id: moduleId!,+      file: cleanUrl(moduleId!),+      invalidate: false,+    }++    // See https://github.com/rolldown/rolldown/issues/8376+    const ssrResult = await ssrTransform(+      result.code,+      lazyResult.sourcemap ? JSON.parse(lazyResult.sourcemap) : null,+      url,+      result.code,+    )+    if (!ssrResult) {+      throw new Error(`[vite] cannot apply ssr transform to '${url}'.`)+    }+    result.code = ssrResult.code+    if (options.inlineSourceMap !== false) {+      result.code = inlineSourceMap(+        result.id,+        ssrResult,+        options.startOffset,+      ).code+    }+    return result+  }++  const outDir = normalizePath(+    path.resolve(environment.config.root, environment.config.build.outDir),+  )++  let fileName: string+  let facadeId: string | undefined++  // Assume this is an entry point that was specified in rolldownOptions.input+  if (!importer) {+    const resolvedEntry = await resolveBundledEntryFilename(+      bundledDev,+      environment.config.root,+      url,+    )+    if (!resolvedEntry) {+      const entrypoints = [...bundledDev.facadeToChunk.keys()]+      throw new Error(+        `[vite] Entrypoint '${url}' was not defined in the config. ` ++          (entrypoints.length+            ? `Available entry points: \n- ${[...bundledDev.facadeToChunk.keys()].join('\n- ')}`+            : `The build did not produce any chunks. Did it finish successfully? See the logs for more information.`),+      )+    }+    ;[facadeId, fileName] = resolvedEntry+  } else if (url[0] === '.') {+    // Importer is reported as a full path on the file system.+    // This happens because we provide the `file` attribute.+    if (importer.startsWith(outDir)) {+      importer = importer.slice(outDir.length + 1)+    }+    fileName = path.posix.join(path.posix.dirname(importer), url)+  } else {+    fileName = url+  }++  const memoryFile = bundledDev.memoryFiles.get(fileName)+  const code = memoryFile?.source+  if (code == null) {+    throw new Error(+      `[vite] the module '${url}' (chunk '${fileName}') ${+        importer ? ` imported from '${importer}'` : ''+      } was not bundled. Is server established?`,+    )+  }+  const map = memoryFile?.sourcemapPath+    ? bundledDev.memoryFiles.get(memoryFile.sourcemapPath)?.source.toString()+    : undefined+  const result: ViteFetchResult = {+    code: code.toString(),+    // To make sure dynamic imports resolve assets correctly.+    // (Dynamic import resolves relative urls with importer url)+    url: fileName,+    id: fileName,+    // The potential position on the file system.+    // We don't actually keep it there, it's virtual.+    file: normalizePath(path.resolve(outDir, fileName)),+    // chunks cannot be invalidated manually+    invalidate: false,+    // TODO: seems like rolldown uses `process.cwd()` instead of `config.root`+    // We need this because __rolldown_runtime__ keeps modules internally+    // And after HMR there is no other way to receive the updated exports+    rolldownModuleId: facadeId+      ? normalizePath(path.relative(process.cwd(), facadeId))+      : undefined,+  }+  // TODO: this should be done in rolldown, there is already a function for it+  // output.format = 'module-runner'+  // See https://github.com/rolldown/rolldown/issues/8376+  const ssrResult = await ssrTransform(+    result.code,+    map ? JSON.parse(map) : null,+    result.file!,+    result.code,+  )+  if (!ssrResult) {+    throw new Error(`[vite] cannot apply ssr transform to '${url}'.`)+  }+  result.code = ssrResult.code+  if (options.inlineSourceMap !== false) {+    result.code = inlineSourceMap(+      result.id,+      ssrResult,+      options.startOffset,+    ).code+  }++  // remove shebang+  if (result.code[0] === '#')+    result.code = result.code.replace(/^#!.*/, (s) => ' '.repeat(s.length))++  return result+}+ const OTHER_SOURCE_MAP_REGEXP = new RegExp(   `//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`,   'gm', )  function inlineSourceMap(-  mod: EnvironmentModuleNode,+  id: string,   result: TransformResult,   startOffset: number | undefined, ) {@@ -147,8 +308,49 @@ function inlineSourceMap(       }     : map   result.code = `${code.trimEnd()}\n//# sourceURL=${encodeSourceURL(-    mod.id!,+    id,   )}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`    return result }++function isBundledChunkUrl(environment: DevEnvironment, url: string) {+  return environment.bundledDev?.memoryFiles.has(url)+}++async function resolveBundledEntryFilename(+  environment: BundledDev,+  root: string,+  url: string,+): Promise<[facadeId: string | undefined, chunkName: string] | undefined> {+  if (environment.memoryFiles.has(url)) {+    return [undefined, url]+  }+  // Already resolved by the user to be a url+  if (environment.facadeToChunk.has(url)) {+    return [url, environment.facadeToChunk.get(url)!]+  }+  const facadeId = await environment.resolveEntryFacade(url)+  if (facadeId && environment.facadeToChunk.has(facadeId)) {+    return [facadeId, environment.facadeToChunk.get(facadeId)!]+  }+  const moduleId = normalizePath(+    url.startsWith('file://')+      ? // new URL(path)+        fileURLToPath(url)+      : // ./index.js+        // NOTE: we don't try to find it if extension is not passed+        // It will throw an error instead+        path.resolve(root, url),+  )+  if (environment.facadeToChunk.get(moduleId)) {+    return [moduleId, environment.facadeToChunk.get(moduleId)!]+  }+  if (url[0] === '/') {+    const tryAbsoluteUrl = path.posix.join(root, url)+    const absoluteChunk = environment.facadeToChunk.get(tryAbsoluteUrl)+    if (absoluteChunk) {+      return [tryAbsoluteUrl, absoluteChunk]+    }+  }+}
packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts+316 −161
packages/vite/src/node/ssr/runtime/__tests__/utils.ts+96 −88
@@ -1,101 +1,109 @@ import fs from 'node:fs' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url'-import { onTestFinished, test } from 'vitest'+import { test as base, onTestFinished } from 'vitest' import type { InlineConfig } from '../../../config' import type { ViteDevServer } from '../../../server' import { createServer } from '../../../server'-import type { ServerModuleRunnerOptions } from '../serverModuleRunner'-import { createServerModuleRunner } from '../serverModuleRunner'+import type { RunnableDevEnvironment } from '../../../server/environments/runnableEnvironment'+import {+  type ServerModuleRunnerOptions,+  createServerModuleRunner,+} from '../serverModuleRunner' -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -- infer the fixture context from the builder-export function createModuleRunnerTester(-  config: InlineConfig = {},-  runnerConfig: ServerModuleRunnerOptions = {},-) {-  function waitForWatcher(server: ViteDevServer) {-    return new Promise<void>((resolve) => {-      if ((server.watcher as any)._readyEmitted) {-        resolve()-      } else {-        server.watcher.once('ready', () => resolve())-      }-    })-  }--  return (-    test-      // eslint-disable-next-line no-empty-pattern-      .extend('server', async ({}, { onCleanup }) => {-        // @ts-ignore-        globalThis.__HMR__ = {}--        const server = await createServer({-          root: import.meta.dirname,-          logLevel: 'error',-          server: {-            middlewareMode: true,-            watch: null,-            ws: false,-          },-          ssr: {-            external: ['@vitejs/cjs-external', '@vitejs/esm-external'],-          },-          optimizeDeps: {-            disabled: true,-            noDiscovery: true,-            include: [],+export const runnerTest = base+  .extend('fullBundle', [] as string[])+  .extend('runnerOptions', undefined as ServerModuleRunnerOptions | undefined)+  .extend('config', {} as InlineConfig)+  .extend('server', async ({ config, fullBundle }, { onCleanup }) => {+    const server = await createServer({+      configFile: false,+      root: import.meta.dirname,+      logLevel: 'error',+      ssr: {+        external: ['@vitejs/cjs-external', '@vitejs/esm-external'],+      },+      environments: {+        ssr: {+          isBundled: fullBundle.length > 0,+        },+      },+      build: {+        rolldownOptions: {+          input: fullBundle,+          ...config.build?.rolldownOptions,+        },+        ...config.build,+      },+      optimizeDeps: {+        disabled: true,+        noDiscovery: true,+        include: [],+      },+      plugins: [+        {+          name: 'vite-plugin-virtual',+          resolveId(id) {+            if (id === 'virtual0:test') {+              return `\0virtual:test`+            }+            if (id === 'virtual:test') {+              return 'virtual:test'+            }+            if (id === 'virtual:normal') {+              return '\0' + id+            }           },-          plugins: [-            {-              name: 'vite-plugin-virtual',-              resolveId(id) {-                if (id === 'virtual0:test') {-                  return `\0virtual:test`-                }-                if (id === 'virtual:test') {-                  return 'virtual:test'-                }-                if (id === 'virtual:normal') {-                  return '\0' + id-                }-              },-              load(id) {-                if (id === `\0virtual:test`) {-                  return `export const msg = 'virtual0'`-                }-                if (id === `virtual:test`) {-                  return `export const msg = 'virtual'`-                }-                if (id === '\0virtual:normal') {-                  return 'export default "ok"'-                }-              },-            },-            ...(config.plugins ?? []),-          ],-          ...config,-        })-        onCleanup(() => server.close())-        return server-      })-      .extend('environment', ({ server }) => server.environments.ssr)-      .extend('runner', async ({ server, environment }, { onCleanup }) => {-        const runner = createServerModuleRunner(environment, {-          hmr: {-            logger: false,+          load(id) {+            if (id === `\0virtual:test`) {+              return `export const msg = 'virtual0'`+            }+            if (id === `virtual:test`) {+              return `export const msg = 'virtual'`+            }+            if (id === '\0virtual:normal') {+              return 'export default "ok"'+            }           },-          // don't override by default so Vitest source maps are correct-          sourcemapInterceptor: false,-          ...runnerConfig,-        })-        onCleanup(() => runner.close())-        if (config.server?.watch) {-          await waitForWatcher(server)-        }-        return runner-      })+        },+        ...(config.plugins ?? []),+      ],+      ...config,+      server: {+        middlewareMode: true,+        watch: null,+        ws: false,+        hmr: false,+        ...config.server,+      },+    })+    onCleanup(() => server.close())+    if (config.server?.watch) {+      await waitForWatcher(server)+    }+    return server+  })+  .extend(+    'environment',+    ({ server }) => server.environments.ssr as RunnableDevEnvironment,   )+  .extend('runner', ({ environment, runnerOptions }, { onCleanup }) => {+    if (runnerOptions) {+      const runner = createServerModuleRunner(environment, runnerOptions)+      onCleanup(() => runner.close())+      return runner+    }+    return environment.runner+  })++function waitForWatcher(server: ViteDevServer) {+  return new Promise<void>((resolve) => {+    if ((server.watcher as any)._readyEmitted) {+      resolve()+    } else {+      server.watcher.once('ready', () => resolve())+    }+  }) }  type FixtureEditor = {

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Test strategyThe new HMR test suite extends coverage to a mode (full bundle mode) not documented in the codebase; test setup uses test augmentation rather than explicit config, creating intention risk for the bundled-dev feature set without corresponding structural documentation.

    Recorded file packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision b574e505f52b30 changed files+1641 −349Judge score 5/5
AboutReview principlesSupportPrivacyContact
(C) 2026 Superpositional>
Member of the NVIDIA Inception Program