11import type { Span } from '@opentelemetry/api'
22import type { StaticMockCall } from '@vitest/mocker/node'
3- import type { DevEnvironment, EnvironmentModuleNode, Rollup, TransformResult } from 'vite'
3+ import type {
4+ DevEnvironment,
5+ EnvironmentModuleNode,
6+ ResolvedConfig as ViteResolvedConfig,
7+ Rollup,
8+ TransformResult,
9+ } from 'vite'
410import type { FetchFunctionOptions, FetchResult } from 'vite/module-runner'
511import type {
612 FetchCachedFileSystemResult,
@@ -9,17 +15,23 @@ import type {
915 VitestFetchResult,
1016} from '../../types/general'
1117import type { OTELCarrier, Traces } from '../../utils/traces'
12- import type { FileSystemModuleCache } from '../cache/fsModuleCache'
18+ import type {
19+ CachedInlineModuleMeta,
20+ CachedModuleImports,
21+ FileSystemModuleCache,
22+ } from '../cache/fsModuleCache'
1323import type { VitestResolver } from '../resolver'
1424import type { ResolvedConfig } from '../types/config'
1525import { existsSync, mkdirSync } from 'node:fs'
1626import { readFile } from 'node:fs/promises'
1727import { isExternalUrl, unwrapId } from '@vitest/utils/helpers'
1828import { join } from 'pathe'
29+ import c from 'tinyrainbow'
1930import { fetchModule } from 'vite'
2031import { createDebugger } from '../../utils/debugger'
2132import { hash } from '../hash'
2233import { detectModuleType } from '../resolver'
34+ import { fsPathFromId } from '../vite'
2335import { normalizeResolvedIdToUrl } from './normalizeUrl'
2436
2537const debugFs = createDebugger('vitest:cache:fs')
@@ -164,15 +176,15 @@ class ModuleFetcher {
164176 moduleGraphModule,
165177 options,
166178 )
167- const importedUrls = this.getSerializedImports( moduleGraphModule)
179+ const imports = this.getCachedImports(environment, moduleGraphModule)
168180 const map = moduleGraphModule.transformResult?.map
169181 const mappings = map && !('version' in map) && map.mappings === ''
170182
171183 const cachedResult = await this.cacheResult(
172184 result,
173185 cachePath,
174186 moduleGraphModule.transformResult,
175- importedUrls ,
187+ imports ,
176188 !!mappings,
177189 )
178190 // remember where the code is stored on disk so that repeat fetches and the
@@ -184,11 +196,19 @@ class ModuleFetcher {
184196 return cachedResult
185197 }
186198
187- // we need this for UI to be able to show a module graph
188- private getSerializedImports(node: EnvironmentModuleNode): string[] {
189- const imports: string[] = []
190- node.importedModules.forEach((importer) => {
191- imports.push(importer.url)
199+ private getCachedImports(
200+ environment: DevEnvironment,
201+ node: EnvironmentModuleNode,
202+ ): CachedModuleImports {
203+ const imports: CachedModuleImports = { urls: [], ids: {} }
204+ node.importedModules.forEach(({ url, id }) => {
205+ if (id == null) {
206+ return
207+ }
208+ imports.urls.push(url)
209+ if (id !== urlToId(environment, url)) {
210+ imports.ids[url] = id
211+ }
192212 })
193213 return imports
194214 }
@@ -245,12 +265,7 @@ class ModuleFetcher {
245265 environment: DevEnvironment,
246266 moduleGraphModule: EnvironmentModuleNode,
247267 ): Promise<string> {
248- if (
249- moduleGraphModule.file &&
250- // \x00 is a virtual file convention
251- !moduleGraphModule.file.startsWith('\x00') &&
252- !moduleGraphModule.file.startsWith('virtual:')
253- ) {
268+ if (moduleGraphModule.file && !isVirtualFile(moduleGraphModule.file)) {
254269 const result = await this.readFileConcurrently(moduleGraphModule.file)
255270 if (result != null) {
256271 return result
@@ -302,6 +317,11 @@ class ModuleFetcher {
302317 return
303318 }
304319
320+ const importedModules = await this.resolveCachedImports(environment, cachedModule)
321+ if (!importedModules) {
322+ return
323+ }
324+
305325 // keep the module graph in sync
306326 let map: Rollup.SourceMap | null | { mappings: '' } = extractSourceMap(cachedModule.code)
307327 if (map && cachedModule.file) {
@@ -331,15 +351,10 @@ class ModuleFetcher {
331351 }
332352 }
333353
334- await Promise.all(
335- cachedModule.importedUrls.map(async (url) => {
336- const moduleNode = await environment.moduleGraph.ensureEntryFromUrl(url).catch(() => null)
337- if (moduleNode) {
338- moduleNode.importers.add(moduleGraphModule)
339- moduleGraphModule.importedModules.add(moduleNode)
340- }
341- }),
342- )
354+ for (const moduleNode of importedModules) {
355+ moduleNode.importers.add(moduleGraphModule)
356+ moduleGraphModule.importedModules.add(moduleNode)
357+ }
343358
344359 return {
345360 cached: true as const,
@@ -352,6 +367,43 @@ class ModuleFetcher {
352367 }
353368 }
354369
370+ // the cached code imports the urls that Vite resolved when the module was
371+ // transformed, so the entry is stale once any of them points elsewhere
372+ private async resolveCachedImports(
373+ environment: DevEnvironment,
374+ cachedModule: CachedInlineModuleMeta,
375+ ): Promise<EnvironmentModuleNode[] | undefined> {
376+ const safeModulePaths = getSafeModulePaths(environment)
377+ const { urls, ids } = cachedModule.imports
378+ const importedModules = await Promise.all(
379+ urls.map(async (url) => {
380+ const id = Object.hasOwn(ids, url) ? ids[url] : urlToId(environment, url)
381+ const moduleNode = await environment.moduleGraph.ensureEntryFromUrl(url).catch(() => null)
382+ const stale =
383+ !moduleNode ||
384+ moduleNode.id !== id ||
385+ // the resolver trusts /@fs/ urls without checking that the file exists
386+ (url.startsWith('/@fs/') && moduleNode.file != null && !existsSync(moduleNode.file))
387+ if (stale) {
388+ debugFs?.(
389+ `${c.red('[stale]')} ${cachedModule.id} imports ${url}, which no longer resolves to ${id}`,
390+ )
391+ return null
392+ }
393+ // import analysis marks out-of-root imports as safe to load from
394+ // outside `server.fs.allow`; a cached importer never goes through it
395+ if (url.startsWith('/@fs/') && moduleNode.file) {
396+ safeModulePaths?.add(moduleNode.file)
397+ }
398+ return moduleNode
399+ }),
400+ )
401+ const resolved = importedModules.filter((moduleNode) => moduleNode != null)
402+ if (resolved.length === importedModules.length) {
403+ return resolved
404+ }
405+ }
406+
355407 private async fetchAndProcess(
356408 environment: DevEnvironment,
357409 url: string,
@@ -382,7 +434,7 @@ class ModuleFetcher {
382434 }
383435
384436 private sourceLoader(file: string | null): (() => Promise<string | null>) | undefined {
385- if (!file || file.startsWith('\x00') || file.startsWith('virtual:' )) {
437+ if (!file || isVirtualFile( file)) {
386438 return undefined
387439 }
388440 return () => this.readFileConcurrently(file)
@@ -414,7 +466,7 @@ class ModuleFetcher {
414466 result: FetchResult,
415467 cachePath: string,
416468 transformResult: TransformResult | null,
417- importedUrls: string[] = [] ,
469+ imports?: CachedModuleImports ,
418470 mappings = false,
419471 ): Promise<FetchResult | FetchCachedFileSystemResult> {
420472 const returnResult = 'code' in result ? getCachedResult(result, cachePath) : result
@@ -424,7 +476,7 @@ class ModuleFetcher {
424476 }
425477
426478 const savePromise = this.fsCache
427- .saveCachedModule(cachePath, result, transformResult, importedUrls , mappings)
479+ .saveCachedModule(cachePath, result, transformResult, imports , mappings)
428480 .then(() => returnResult)
429481 .catch((error) => {
430482 debugFs?.(`failed to cache ${cachePath}, serving it inline: ${error}`)
@@ -455,6 +507,30 @@ class ModuleFetcher {
455507 }
456508}
457509
510+ // \x00 is a virtual file convention
511+ function isVirtualFile(file: string): boolean {
512+ return file.startsWith('\x00') || file.startsWith('virtual:')
513+ }
514+
515+ // inverts the url that import analysis writes for a resolved id
516+ function urlToId(environment: DevEnvironment, url: string): string {
517+ if (url.startsWith('/@fs/')) {
518+ return fsPathFromId(url)
519+ }
520+ if (url[0] === '/') {
521+ return environment.config.root + url
522+ }
523+ return url
524+ }
525+
526+ // Vite keeps the set out of its public types
527+ function getSafeModulePaths(environment: DevEnvironment): Set<string> | undefined {
528+ const config = environment.getTopLevelConfig() as ViteResolvedConfig & {
529+ safeModulePaths?: Set<string>
530+ }
531+ return config.safeModulePaths
532+ }
533+
458534export interface VitestFetchFunction {
459535 (
460536 url: string,
0 commit comments