1- import type { FetchFunction , ModuleRunnerTransport } from 'vite/module-runner'
1+ import type { EvaluatedModuleNode , EvaluatedModules , FetchFunction , ModuleRunnerTransport } from 'vite/module-runner'
22import type { ResolveFunctionResult } from '../../types/general'
3+ import { EnvironmentTeardownError } from '../utils'
34
45export interface VitestTransportOptions {
56 fetchModule : FetchFunction
67 resolveId : ( id : string , importer ?: string ) => Promise < ResolveFunctionResult | null >
78}
89
910export class VitestTransport implements ModuleRunnerTransport {
10- constructor ( private options : VitestTransportOptions ) { }
11+ constructor (
12+ private options : VitestTransportOptions ,
13+ private evaluatedModules : EvaluatedModules ,
14+ private callstacks : WeakMap < EvaluatedModuleNode , string [ ] > ,
15+ ) { }
1116
1217 async invoke ( event : any ) : Promise < { result : any } | { error : any } > {
1318 if ( event . type !== 'custom' ) {
@@ -29,8 +34,24 @@ export class VitestTransport implements ModuleRunnerTransport {
2934 const result = await this . options . fetchModule ( ...data as Parameters < FetchFunction > )
3035 return { result }
3136 }
32- catch ( error ) {
33- return { error }
37+ catch ( cause ) {
38+ if ( cause instanceof EnvironmentTeardownError ) {
39+ const [ id , importer ] = data as Parameters < FetchFunction >
40+ let message = `Cannot load '${ id } '${ importer ? ` imported from ${ importer } ` : '' } after the environment was torn down. `
41+ + `This is not a bug in Vitest.`
42+
43+ const moduleNode = importer ? this . evaluatedModules . getModuleById ( importer ) : undefined
44+ const callstack = moduleNode ? this . callstacks . get ( moduleNode ) : undefined
45+ if ( callstack ) {
46+ message += ` The last recorded callstack:\n- ${ [ ...callstack , importer , id ] . reverse ( ) . join ( '\n- ' ) } `
47+ }
48+ const error = new EnvironmentTeardownError ( message )
49+ if ( cause . stack ) {
50+ error . stack = cause . stack . replace ( cause . message , error . message )
51+ }
52+ return { error }
53+ }
54+ return { error : cause }
3455 }
3556 }
3657}
0 commit comments