Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: correctly resolve filename, when running code #2439

Merged
merged 10 commits into from Dec 6, 2022
11 changes: 2 additions & 9 deletions packages/vite-node/src/client.ts
Expand Up @@ -222,11 +222,6 @@ export class ViteNodeRunner {
Object.defineProperty(request, 'callstack', { get: () => callstack })

const resolveId = async (dep: string, callstackPosition = 1) => {
// probably means it was passed as variable
// and wasn't transformed by Vite
// or some dependency name was passed
// runner.executeFile('@scope/name')
// runner.executeFile(myDynamicName)
if (this.options.resolveId && this.shouldResolveId(dep)) {
let importer = callstack[callstack.length - callstackPosition]
if (importer && importer.startsWith('mock:'))
Expand All @@ -238,14 +233,12 @@ export class ViteNodeRunner {
return dep
}

id = await resolveId(id, 2)

const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS
if (id in requestStubs)
return requestStubs[id]

// eslint-disable-next-line prefer-const
let { code: transformed, externalize } = await this.options.fetchModule(id)
let { code: transformed, externalize, file } = await this.options.fetchModule(id)
if (externalize) {
debugNative(externalize)
const exports = await this.interopedImport(externalize)
Expand Down Expand Up @@ -345,7 +338,7 @@ export class ViteNodeRunner {
const codeDefinition = `'use strict';async (${Object.keys(context).join(',')})=>{{`
const code = `${codeDefinition}${transformed}\n}}`
const fn = vm.runInThisContext(code, {
filename: fsPath,
filename: file,
lineOffset: 0,
columnOffset: -codeDefinition.length,
})
Expand Down
21 changes: 13 additions & 8 deletions packages/vite-node/src/server.ts
Expand Up @@ -4,17 +4,14 @@ import type { TransformResult, ViteDevServer } from 'vite'
import createDebug from 'debug'
import type { DebuggerOptions, FetchResult, RawSourceMap, ViteNodeResolveId, ViteNodeServerOptions } from './types'
import { shouldExternalize } from './externalize'
import { toArray, toFilePath } from './utils'
import { cleanUrl, normalizeModuleId, toArray, toFilePath } from './utils'
import { Debugger } from './debug'
import { withInlineSourcemap } from './source-map'

export * from './externalize'

const debugRequest = createDebug('vite-node:server:request')

// store the original reference to avoid it been mocked
const RealDate = Date

export class ViteNodeServer {
private fetchPromiseMap = new Map<string, Promise<FetchResult>>()
private transformPromiseMap = new Map<string, Promise<TransformResult | null | undefined>>()
Expand Down Expand Up @@ -83,6 +80,7 @@ export class ViteNodeServer {
}

async fetchModule(id: string): Promise<FetchResult> {
id = normalizeModuleId(id)
// reuse transform for concurrent requests
if (!this.fetchPromiseMap.has(id)) {
this.fetchPromiseMap.set(id,
Expand Down Expand Up @@ -130,9 +128,10 @@ export class ViteNodeServer {
const filePath = toFilePath(id, this.server.config.root)

const module = this.server.moduleGraph.getModuleById(id)
const timestamp = module?.lastHMRTimestamp || RealDate.now()
const timestamp = module ? module.lastHMRTimestamp : null
const time = Date.now()
const cache = this.fetchCache.get(filePath)
if (timestamp && cache && cache.timestamp >= timestamp)
if (timestamp !== null && cache && cache.timestamp >= timestamp)
return cache.result

const externalize = await this.shouldExternalize(filePath)
Expand All @@ -142,15 +141,21 @@ export class ViteNodeServer {
this.debugger?.recordExternalize(id, externalize)
}
else {
let file = module?.file
if (!file) {
const [, resolvedId] = await this.server.moduleGraph.resolveUrl(id, true)
id = resolvedId
file = cleanUrl(resolvedId)
}
const start = performance.now()
const r = await this._transformRequest(id)
duration = performance.now() - start
result = { code: r?.code, map: r?.map as unknown as RawSourceMap }
result = { file, id, code: r?.code, map: r?.map as unknown as RawSourceMap }
}

this.fetchCache.set(filePath, {
duration,
timestamp,
timestamp: time,
result,
})

Expand Down
2 changes: 2 additions & 0 deletions packages/vite-node/src/types.ts
Expand Up @@ -31,6 +31,8 @@ export interface FetchResult {
code?: string
externalize?: string
map?: RawSourceMap
id?: string
file?: string
}

export type HotContext = Omit<ViteHotContext, 'acceptDeps' | 'decline'>
Expand Down
6 changes: 6 additions & 0 deletions packages/vite-node/src/utils.ts
Expand Up @@ -34,6 +34,12 @@ export function normalizeRequestId(id: string, base?: string): string {
.replace(/\?+$/, '') // remove end query mark
}

export const queryRE = /\?.*$/s
export const hashRE = /#.*$/s

export const cleanUrl = (url: string): string =>
url.replace(hashRE, '').replace(queryRE, '')

export function normalizeModuleId(id: string) {
return id
.replace(/\\/g, '/')
Expand Down
5 changes: 5 additions & 0 deletions packages/vitest/src/node/core.ts
Expand Up @@ -311,6 +311,8 @@ export class Vitest {
}

async runFiles(paths: string[]) {
paths = Array.from(new Set(paths))

// previous run
await this.runningPromise
this.state.startCollectingPaths()
Expand Down Expand Up @@ -396,6 +398,9 @@ export class Vitest {

private _rerunTimer: any
private async scheduleRerun(triggerId: string) {
const mod = this.server.moduleGraph.getModuleById(triggerId)
if (mod)
mod.lastHMRTimestamp = Date.now()
const currentCount = this.restartsCount
clearTimeout(this._rerunTimer)
await this.runningPromise
Expand Down