[READ-ONLY] Mirror of https://github.com/vitest-dev/vitest. Next generation testing framework powered by Vite. vitest.dev
test testing-tools vite
12

Configure Feed

Select the types of activity you want to include in your feed.

refactor: enable `isolatedDeclarations` (#7473)

authored by

Kevin Deng 三咲智子 and committed by
GitHub
(Feb 13, 2025, 5:37 PM +0100) accd2eda 01b91b5e

+786 -638
+3 -3
packages/browser/src/client/channel.ts
··· 40 40 | IframeChannelIncomingEvent 41 41 | IframeChannelOutgoingEvent 42 42 43 - export const channel = new BroadcastChannel( 43 + export const channel: BroadcastChannel = new BroadcastChannel( 44 44 `vitest:${getBrowserState().sessionId}`, 45 45 ) 46 - export const globalChannel = new BroadcastChannel('vitest:global') 46 + export const globalChannel: BroadcastChannel = new BroadcastChannel('vitest:global') 47 47 48 - export function waitForChannel(event: IframeChannelOutgoingEvent['type']) { 48 + export function waitForChannel(event: IframeChannelOutgoingEvent['type']): Promise<void> { 49 49 return new Promise<void>((resolve) => { 50 50 channel.addEventListener( 51 51 'message',
+6 -6
packages/browser/src/client/client.ts
··· 6 6 7 7 const PAGE_TYPE = getBrowserState().type 8 8 9 - export const PORT = location.port 10 - export const HOST = [location.hostname, PORT].filter(Boolean).join(':') 11 - export const RPC_ID 9 + export const PORT: string = location.port 10 + export const HOST: string = [location.hostname, PORT].filter(Boolean).join(':') 11 + export const RPC_ID: string 12 12 = PAGE_TYPE === 'orchestrator' 13 13 ? getBrowserState().sessionId 14 14 : getBrowserState().testerId 15 15 const METHOD = getBrowserState().method 16 - export const ENTRY_URL = `${ 16 + export const ENTRY_URL: string = `${ 17 17 location.protocol === 'https:' ? 'wss:' : 'ws:' 18 18 }//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${getBrowserState().config.name || ''}&method=${METHOD}&token=${(window as any).VITEST_API_TOKEN}` 19 19 20 20 let setCancel = (_: CancelReason) => {} 21 - export const onCancel = new Promise<CancelReason>((resolve) => { 21 + export const onCancel: Promise<CancelReason> = new Promise((resolve) => { 22 22 setCancel = resolve 23 23 }) 24 24 ··· 135 135 return ctx 136 136 } 137 137 138 - export const client = createClient() 138 + export const client: VitestBrowserClient = createClient() 139 139 140 140 export * from './channel'
+2 -1
packages/browser/src/client/tester/context.ts
··· 11 11 UserEventTabOptions, 12 12 UserEventTypeOptions, 13 13 } from '../../../context' 14 + import type { BrowserRunnerState } from '../utils' 14 15 import { convertElementToCssSelector, ensureAwaited, getBrowserState, getWorkerState } from '../utils' 15 16 16 17 // this file should not import anything directly, only types and utils ··· 238 239 return vitestUserEvent 239 240 } 240 241 241 - export function cdp() { 242 + export function cdp(): BrowserRunnerState['cdp'] { 242 243 return getBrowserState().cdp! 243 244 } 244 245
+1 -1
packages/browser/src/client/tester/dialog.ts
··· 18 18 } 19 19 } 20 20 21 - export function setupDialogsSpy() { 21 + export function setupDialogsSpy(): void { 22 22 globalThis.alert = showPopupWarning('alert', undefined) 23 23 globalThis.confirm = showPopupWarning('confirm', false, true) 24 24 globalThis.prompt = showPopupWarning('prompt', null, 'your value')
+1 -1
packages/browser/src/client/tester/expect-element.ts
··· 3 3 import * as matchers from '@testing-library/jest-dom/matchers' 4 4 import { chai, expect } from 'vitest' 5 5 6 - export async function setupExpectDom() { 6 + export async function setupExpectDom(): Promise<void> { 7 7 expect.extend(matchers) 8 8 expect.element = <T extends Element | Locator>(elementOrLocator: T, options?: ExpectPollOptions) => { 9 9 if (!(elementOrLocator instanceof Element) && !('element' in elementOrLocator)) {
+2 -2
packages/browser/src/client/tester/locators/index.ts
··· 26 26 import { getElementError } from '../public-utils' 27 27 28 28 // we prefer using playwright locators because they are more powerful and support Shadow DOM 29 - export const selectorEngine = Ivya.create({ 29 + export const selectorEngine: Ivya = Ivya.create({ 30 30 browser: ((name: string) => { 31 31 switch (name) { 32 32 case 'edge': ··· 217 217 return this.worker.rpc as any as BrowserRPC 218 218 } 219 219 220 - protected triggerCommand<T>(command: string, ...args: any[]) { 220 + protected triggerCommand<T>(command: string, ...args: any[]): Promise<T> { 221 221 const filepath = this.worker.filepath 222 222 || this.worker.current?.file?.filepath 223 223 || undefined
+1 -1
packages/browser/src/client/tester/logger.ts
··· 4 4 5 5 const { Date, console, performance } = globalThis 6 6 7 - export function setupConsoleLogSpy() { 7 + export function setupConsoleLogSpy(): void { 8 8 const { 9 9 log, 10 10 info,
+1 -1
packages/browser/src/client/tester/msw.ts
··· 1 1 import { ModuleMockerMSWInterceptor } from '@vitest/mocker/browser' 2 2 import { getConfig } from '../utils' 3 3 4 - export function createModuleMockerInterceptor() { 4 + export function createModuleMockerInterceptor(): ModuleMockerMSWInterceptor { 5 5 const debug = getConfig().env.VITEST_BROWSER_DEBUG 6 6 return new ModuleMockerMSWInterceptor({ 7 7 globalThisAccessor: '"__vitest_mocker__"',
+1 -1
packages/browser/src/client/tester/rpc.ts
··· 31 31 32 32 const promises = new Set<Promise<unknown>>() 33 33 34 - export async function rpcDone() { 34 + export async function rpcDone(): Promise<unknown[] | undefined> { 35 35 if (!promises.size) { 36 36 return 37 37 }
+2 -5
packages/browser/src/client/tester/runner.ts
··· 16 16 config: SerializedConfig 17 17 } 18 18 19 - export const browserHashMap = new Map< 20 - string, 21 - string 22 - >() 19 + export const browserHashMap: Map<string, string> = new Map() 23 20 24 21 interface CoverageHandler { 25 22 takeCoverage: () => Promise<unknown> ··· 157 154 state: WorkerGlobalState, 158 155 mocker: VitestBrowserClientMocker, 159 156 config: SerializedConfig, 160 - ) { 157 + ): Promise<VitestRunner> { 161 158 if (cachedRunner) { 162 159 return cachedRunner 163 160 }
+1 -1
packages/browser/src/client/tester/snapshot.ts
··· 6 6 private sourceMaps = new Map<string, any>() 7 7 private traceMaps = new Map<string, TraceMap>() 8 8 9 - public addSourceMap(filepath: string, map: any) { 9 + public addSourceMap(filepath: string, map: any): void { 10 10 this.sourceMaps.set(filepath, map) 11 11 } 12 12
+4 -4
packages/browser/src/client/utils.ts
··· 1 1 import type { SerializedConfig, WorkerGlobalState } from 'vitest' 2 2 3 - export async function importId(id: string) { 3 + export async function importId(id: string): Promise<any> { 4 4 const name = `/@id/${id}`.replace(/\\/g, '/') 5 5 return getBrowserState().wrapModule(() => import(/* @vite-ignore */ name)) 6 6 } 7 7 8 - export async function importFs(id: string) { 8 + export async function importFs(id: string): Promise<any> { 9 9 const name = `/@fs/${id}`.replace(/\\/g, '/') 10 10 return getBrowserState().wrapModule(() => import(/* @vite-ignore */ name)) 11 11 } ··· 13 13 export const executor = { 14 14 isBrowser: true, 15 15 16 - executeId: (id: string) => { 16 + executeId: (id: string): Promise<any> => { 17 17 if (id[0] === '/' || id[1] === ':') { 18 18 return importFs(id) 19 19 } ··· 103 103 } 104 104 105 105 /* @__NO_SIDE_EFFECTS__ */ 106 - export function convertElementToCssSelector(element: Element) { 106 + export function convertElementToCssSelector(element: Element): string { 107 107 if (!element || !(element instanceof Element)) { 108 108 throw new Error( 109 109 `Expected DOM element to be an instance of Element, received ${typeof element}`,
+4 -4
packages/browser/src/node/cdp.ts
··· 11 11 private tester: WebSocketBrowserRPC, 12 12 ) {} 13 13 14 - send(method: string, params?: Record<string, unknown>) { 14 + send(method: string, params?: Record<string, unknown>): Promise<unknown> { 15 15 return this.session.send(method, params) 16 16 } 17 17 18 - on(event: string, id: string, once = false) { 18 + on(event: string, id: string, once = false): void { 19 19 if (!this.listenerIds[event]) { 20 20 this.listenerIds[event] = [] 21 21 } ··· 36 36 } 37 37 } 38 38 39 - off(event: string, id: string) { 39 + off(event: string, id: string): void { 40 40 if (!this.listenerIds[event]) { 41 41 this.listenerIds[event] = [] 42 42 } ··· 48 48 } 49 49 } 50 50 51 - once(event: string, listener: string) { 51 + once(event: string, listener: string): void { 52 52 this.on(event, listener, true) 53 53 } 54 54 }
+18 -18
packages/browser/src/node/commands/index.ts
··· 17 17 import { upload } from './upload' 18 18 19 19 export default { 20 - readFile, 21 - removeFile, 22 - writeFile, 23 - __vitest_fileInfo: _fileInfo, 24 - __vitest_upload: upload, 25 - __vitest_click: click, 26 - __vitest_dblClick: dblClick, 27 - __vitest_tripleClick: tripleClick, 28 - __vitest_screenshot: screenshot, 29 - __vitest_type: type, 30 - __vitest_clear: clear, 31 - __vitest_fill: fill, 32 - __vitest_tab: tab, 33 - __vitest_keyboard: keyboard, 34 - __vitest_selectOptions: selectOptions, 35 - __vitest_dragAndDrop: dragAndDrop, 36 - __vitest_hover: hover, 37 - __vitest_cleanup: keyboardCleanup, 20 + readFile: readFile as typeof readFile, 21 + removeFile: removeFile as typeof removeFile, 22 + writeFile: writeFile as typeof writeFile, 23 + __vitest_fileInfo: _fileInfo as typeof _fileInfo, 24 + __vitest_upload: upload as typeof upload, 25 + __vitest_click: click as typeof click, 26 + __vitest_dblClick: dblClick as typeof dblClick, 27 + __vitest_tripleClick: tripleClick as typeof tripleClick, 28 + __vitest_screenshot: screenshot as typeof screenshot, 29 + __vitest_type: type as typeof type, 30 + __vitest_clear: clear as typeof clear, 31 + __vitest_fill: fill as typeof fill, 32 + __vitest_tab: tab as typeof tab, 33 + __vitest_keyboard: keyboard as typeof keyboard, 34 + __vitest_selectOptions: selectOptions as typeof selectOptions, 35 + __vitest_dragAndDrop: dragAndDrop as typeof dragAndDrop, 36 + __vitest_hover: hover as typeof hover, 37 + __vitest_cleanup: keyboardCleanup as typeof keyboardCleanup, 38 38 }
+1 -1
packages/browser/src/node/commands/keyboard.ts
··· 83 83 text: string, 84 84 selectAll: () => Promise<void>, 85 85 skipRelease: boolean, 86 - ) { 86 + ): Promise<{ pressed: Set<string> }> { 87 87 if (provider instanceof PlaywrightBrowserProvider) { 88 88 const page = provider.getPage(sessionId) 89 89 const actions = parseKeyDef(defaultKeyMap, text)
+1 -1
packages/browser/src/node/constants.ts
··· 2 2 import { resolve } from 'pathe' 3 3 4 4 const pkgRoot = resolve(fileURLToPath(import.meta.url), '../..') 5 - export const distRoot = resolve(pkgRoot, 'dist') 5 + export const distRoot: string = resolve(pkgRoot, 'dist')
+1 -1
packages/browser/src/node/index.ts
··· 17 17 configFile: string | undefined, 18 18 prePlugins: Plugin[] = [], 19 19 postPlugins: Plugin[] = [], 20 - ) { 20 + ): Promise<ParentBrowserProject> { 21 21 if (project.vitest.version !== version) { 22 22 project.vitest.logger.warn( 23 23 c.yellow(
+2 -2
packages/browser/src/node/middlewares/utils.ts
··· 1 1 import type { ServerResponse } from 'node:http' 2 2 3 - export function disableCache(res: ServerResponse) { 3 + export function disableCache(res: ServerResponse): void { 4 4 res.setHeader( 5 5 'Cache-Control', 6 6 'no-cache, max-age=0, must-revalidate', ··· 8 8 res.setHeader('Content-Type', 'text/html; charset=utf-8') 9 9 } 10 10 11 - export function allowIframes(res: ServerResponse) { 11 + export function allowIframes(res: ServerResponse): void { 12 12 // remove custom iframe related headers to allow the iframe to load 13 13 res.removeHeader('X-Frame-Options') 14 14 }
+10 -9
packages/browser/src/node/project.ts
··· 1 1 import type { StackTraceParserOptions } from '@vitest/utils/source-map' 2 - import type { ErrorWithDiff, SerializedConfig } from 'vitest' 2 + import type { ViteDevServer } from 'vite' 3 + import type { ErrorWithDiff, ParsedStack, SerializedConfig } from 'vitest' 3 4 import type { 4 5 BrowserProvider, 5 6 ProjectBrowser as IProjectBrowser, ··· 23 24 public provider!: BrowserProvider 24 25 public vitest: Vitest 25 26 public config: ResolvedConfig 26 - public children = new Set<ProjectBrowser>() 27 + public children: Set<ProjectBrowser> = new Set<ProjectBrowser>() 27 28 28 29 public parent!: ParentBrowserProject 29 30 30 - public state = new BrowserServerState() 31 + public state: BrowserServerState = new BrowserServerState() 31 32 32 33 constructor( 33 34 public project: TestProject, ··· 53 54 ).then(html => (this.testerHtml = html)) 54 55 } 55 56 56 - get vite() { 57 + get vite(): ViteDevServer { 57 58 return this.parent.vite 58 59 } 59 60 60 - wrapSerializedConfig() { 61 + wrapSerializedConfig(): SerializedConfig { 61 62 const config = wrapConfig(this.project.serializedConfig) 62 63 config.env ??= {} 63 64 config.env.VITEST_BROWSER_DEBUG = process.env.VITEST_BROWSER_DEBUG || '' 64 65 return config 65 66 } 66 67 67 - async initBrowserProvider(project: TestProject) { 68 + async initBrowserProvider(project: TestProject): Promise<void> { 68 69 if (this.provider) { 69 70 return 70 71 } ··· 95 96 public parseErrorStacktrace( 96 97 e: ErrorWithDiff, 97 98 options: StackTraceParserOptions = {}, 98 - ) { 99 + ): ParsedStack[] { 99 100 return this.parent.parseErrorStacktrace(e, options) 100 101 } 101 102 102 103 public parseStacktrace( 103 104 trace: string, 104 105 options: StackTraceParserOptions = {}, 105 - ) { 106 + ): ParsedStack[] { 106 107 return this.parent.parseStacktrace(trace, options) 107 108 } 108 109 109 - async close() { 110 + async close(): Promise<void> { 110 111 await this.parent.vite.close() 111 112 } 112 113 }
+7 -7
packages/browser/src/node/projectParent.ts
··· 36 36 public stateJs: Promise<string> | string 37 37 38 38 public commands: Record<string, BrowserCommand<any>> = {} 39 - public children = new Set<ProjectBrowser>() 39 + public children: Set<ProjectBrowser> = new Set() 40 40 public vitest: Vitest 41 41 42 42 public config: ResolvedConfig ··· 110 110 ).then(js => (this.stateJs = js)) 111 111 } 112 112 113 - public setServer(vite: Vite.ViteDevServer) { 113 + public setServer(vite: Vite.ViteDevServer): void { 114 114 this.vite = vite 115 115 } 116 116 ··· 147 147 }) 148 148 } 149 149 150 - public readonly cdps = new Map<string, BrowserServerCDPHandler>() 150 + public readonly cdps: Map<string, BrowserServerCDPHandler> = new Map() 151 151 private cdpSessionsPromises = new Map<string, Promise<CDPSession>>() 152 152 153 - async ensureCDPHandler(sessionId: string, rpcId: string) { 153 + async ensureCDPHandler(sessionId: string, rpcId: string): Promise<BrowserServerCDPHandler> { 154 154 const cachedHandler = this.cdps.get(rpcId) 155 155 if (cachedHandler) { 156 156 return cachedHandler ··· 191 191 return handler 192 192 } 193 193 194 - removeCDPHandler(sessionId: string) { 194 + removeCDPHandler(sessionId: string): void { 195 195 this.cdps.delete(sessionId) 196 196 } 197 197 198 - async formatScripts(scripts: BrowserScript[] | undefined) { 198 + async formatScripts(scripts: BrowserScript[] | undefined): Promise<HtmlTagDescriptor[]> { 199 199 if (!scripts?.length) { 200 200 return [] 201 201 } ··· 228 228 return (await Promise.all(promises)) 229 229 } 230 230 231 - resolveTesterUrl(pathname: string) { 231 + resolveTesterUrl(pathname: string): { sessionId: string; testFile: string } { 232 232 const [sessionId, testFile] = pathname 233 233 .slice(this.prefixTesterUrl.length) 234 234 .split('/')
+3 -3
packages/browser/src/node/providers/index.ts
··· 2 2 import { PreviewBrowserProvider } from './preview' 3 3 import { WebdriverBrowserProvider } from './webdriver' 4 4 5 - export const webdriverio = WebdriverBrowserProvider 6 - export const playwright = PlaywrightBrowserProvider 7 - export const preview = PreviewBrowserProvider 5 + export const webdriverio: typeof WebdriverBrowserProvider = WebdriverBrowserProvider 6 + export const playwright: typeof PlaywrightBrowserProvider = PlaywrightBrowserProvider 7 + export const preview: typeof PreviewBrowserProvider = PreviewBrowserProvider
+22 -11
packages/browser/src/node/providers/playwright.ts
··· 3 3 BrowserContext, 4 4 BrowserContextOptions, 5 5 Frame, 6 + FrameLocator, 6 7 LaunchOptions, 7 8 Page, 8 9 } from 'playwright' ··· 34 35 context?: BrowserContextOptions & { actionTimeout?: number } 35 36 } 36 37 37 - public contexts = new Map<string, BrowserContext>() 38 - public pages = new Map<string, Page>() 38 + public contexts: Map<string, BrowserContext> = new Map() 39 + public pages: Map<string, Page> = new Map() 39 40 40 41 private browserPromise: Promise<Browser> | null = null 41 42 42 - getSupportedBrowsers() { 43 + getSupportedBrowsers(): readonly string[] { 43 44 return playwrightBrowsers 44 45 } 45 46 46 47 initialize( 47 48 project: TestProject, 48 49 { browser, options }: PlaywrightProviderOptions, 49 - ) { 50 + ): void { 50 51 this.project = project 51 52 this.browserName = browser 52 53 this.options = options as any ··· 125 126 return context 126 127 } 127 128 128 - public getPage(sessionId: string) { 129 + public getPage(sessionId: string): Page { 129 130 const page = this.pages.get(sessionId) 130 131 if (!page) { 131 132 throw new Error(`Page "${sessionId}" not found in ${this.browserName} browser.`) ··· 133 134 return page 134 135 } 135 136 136 - public getCommandsContext(sessionId: string) { 137 + public getCommandsContext(sessionId: string): { 138 + page: Page 139 + context: BrowserContext 140 + frame: () => Promise<Frame> 141 + readonly iframe: FrameLocator 142 + } { 137 143 const page = this.getPage(sessionId) 138 144 return { 139 145 page, 140 146 context: this.contexts.get(sessionId)!, 141 - frame() { 147 + frame(): Promise<Frame> { 142 148 return new Promise<Frame>((resolve, reject) => { 143 149 const frame = page.frame('vitest-iframe') 144 150 if (frame) { ··· 155 161 }) 156 162 }) 157 163 }, 158 - get iframe() { 164 + get iframe(): FrameLocator { 159 165 return page.frameLocator('[data-vitest="true"]')! 160 166 }, 161 167 } ··· 194 200 return page 195 201 } 196 202 197 - async openPage(sessionId: string, url: string, beforeNavigate?: () => Promise<void>) { 203 + async openPage(sessionId: string, url: string, beforeNavigate?: () => Promise<void>): Promise<void> { 198 204 const browserPage = await this.openBrowserPage(sessionId) 199 205 await beforeNavigate?.() 200 206 await browserPage.goto(url, { timeout: 0 }) 201 207 } 202 208 203 - async getCDPSession(sessionid: string) { 209 + async getCDPSession(sessionid: string): Promise<{ 210 + send: (method: string, params: any) => Promise<unknown> 211 + on: (event: string, listener: (...args: any[]) => void) => void 212 + off: (event: string, listener: (...args: any[]) => void) => void 213 + once: (event: string, listener: (...args: any[]) => void) => void 214 + }> { 204 215 const page = this.getPage(sessionid) 205 216 const cdp = await page.context().newCDPSession(page) 206 217 return { ··· 220 231 } 221 232 } 222 233 223 - async close() { 234 + async close(): Promise<void> { 224 235 const browser = this.browser 225 236 this.browser = null 226 237 await Promise.all([...this.pages.values()].map(p => p.close()))
+5 -5
packages/browser/src/node/providers/preview.ts
··· 6 6 private project!: TestProject 7 7 private open = false 8 8 9 - getSupportedBrowsers() { 9 + getSupportedBrowsers(): string[] { 10 10 // `none` is not restricted to certain browsers. 11 11 return [] 12 12 } 13 13 14 - isOpen() { 14 + isOpen(): boolean { 15 15 return this.open 16 16 } 17 17 ··· 19 19 return {} 20 20 } 21 21 22 - async initialize(project: TestProject) { 22 + async initialize(project: TestProject): Promise<void> { 23 23 this.project = project 24 24 this.open = false 25 25 if (project.config.browser.headless) { ··· 30 30 project.vitest.logger.printBrowserBanner(project) 31 31 } 32 32 33 - async openPage(_sessionId: string, url: string) { 33 + async openPage(_sessionId: string, url: string): Promise<void> { 34 34 this.open = true 35 35 if (!this.project.browser) { 36 36 throw new Error('Browser is not initialized') ··· 42 42 options.open = _open 43 43 } 44 44 45 - async close() {} 45 + async close(): Promise<void> {} 46 46 }
+10 -8
packages/browser/src/node/providers/webdriver.ts
··· 24 24 25 25 private options?: RemoteOptions 26 26 27 - getSupportedBrowsers() { 27 + getSupportedBrowsers(): readonly string[] { 28 28 return webdriverBrowsers 29 29 } 30 30 31 31 async initialize( 32 32 ctx: TestProject, 33 33 { browser, options }: WebdriverProviderOptions, 34 - ) { 34 + ): Promise<void> { 35 35 this.project = ctx 36 36 this.browserName = browser 37 37 this.options = options as RemoteOptions 38 38 } 39 39 40 - async beforeCommand() { 40 + async beforeCommand(): Promise<void> { 41 41 const page = this.browser! 42 42 const iframe = await page.findElement( 43 43 'css selector', ··· 46 46 await page.switchToFrame(iframe) 47 47 } 48 48 49 - async afterCommand() { 49 + async afterCommand(): Promise<void> { 50 50 await this.browser!.switchToParentFrame() 51 51 } 52 52 53 - getCommandsContext() { 53 + getCommandsContext(): { 54 + browser: WebdriverIO.Browser | null 55 + } { 54 56 return { 55 57 browser: this.browser, 56 58 } 57 59 } 58 60 59 - async openBrowser() { 61 + async openBrowser(): Promise<WebdriverIO.Browser> { 60 62 if (this.browser) { 61 63 return this.browser 62 64 } ··· 120 122 return capabilities 121 123 } 122 124 123 - async openPage(_sessionId: string, url: string) { 125 + async openPage(_sessionId: string, url: string): Promise<void> { 124 126 const browserInstance = await this.openBrowser() 125 127 await browserInstance.url(url) 126 128 } 127 129 128 - async close() { 130 + async close(): Promise<void> { 129 131 await Promise.all([ 130 132 this.browser?.sessionId ? this.browser?.deleteSession?.() : null, 131 133 ])
+2 -2
packages/browser/src/node/rpc.ts
··· 17 17 18 18 const BROWSER_API_PATH = '/__vitest_browser_api__' 19 19 20 - export function setupBrowserRpc(globalServer: ParentBrowserProject) { 20 + export function setupBrowserRpc(globalServer: ParentBrowserProject): void { 21 21 const vite = globalServer.vite 22 22 const vitest = globalServer.vitest 23 23 ··· 289 289 * Replacer function for serialization methods such as JS.stringify() or 290 290 * flatted.stringify(). 291 291 */ 292 - export function stringifyReplace(key: string, value: any) { 292 + export function stringifyReplace(key: string, value: any): any { 293 293 if (value instanceof Error) { 294 294 const cloned = cloneByOwnProperties(value) 295 295 return {
+1 -1
packages/browser/src/node/serverOrchestrator.ts
··· 7 7 globalServer: ParentBrowserProject, 8 8 url: URL, 9 9 res: ServerResponse<IncomingMessage>, 10 - ) { 10 + ): Promise<string | undefined> { 11 11 let sessionId = url.searchParams.get('sessionId') 12 12 // it's possible to open the page without a context 13 13 if (!sessionId) {
+2 -2
packages/browser/src/node/state.ts
··· 2 2 import type { WebSocketBrowserRPC } from './types' 3 3 4 4 export class BrowserServerState implements IBrowserServerState { 5 - public readonly orchestrators = new Map<string, WebSocketBrowserRPC>() 6 - public readonly testers = new Map<string, WebSocketBrowserRPC>() 5 + public readonly orchestrators: Map<string, WebSocketBrowserRPC> = new Map() 6 + public readonly testers: Map<string, WebSocketBrowserRPC> = new Map() 7 7 }
+2 -2
packages/browser/src/node/utils.ts
··· 1 1 import type { BrowserProviderModule, ResolvedBrowserOptions, TestProject } from 'vitest/node' 2 2 3 - export function replacer(code: string, values: Record<string, string>) { 3 + export function replacer(code: string, values: Record<string, string>): string { 4 4 return code.replace(/\{\s*(\w+)\s*\}/g, (_, key) => values[key] ?? _) 5 5 } 6 6 ··· 42 42 return customProviderModule.default 43 43 } 44 44 45 - export function slash(path: string) { 45 + export function slash(path: string): string { 46 46 return path.replace(/\\/g, '/').replace(/\/+/g, '/') 47 47 }
+3 -2
packages/browser/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 3 "compilerOptions": { 4 - "types": ["node", "vite/client"] 4 + "types": ["node", "vite/client"], 5 + "isolatedDeclarations": true 5 6 }, 6 - "exclude": ["dist", "node_modules"] 7 + "exclude": ["dist", "node_modules", "**/vite.config.ts"] 7 8 }
+3 -2
packages/coverage-istanbul/src/index.ts
··· 3 3 import type { IstanbulCoverageProvider } from './provider' 4 4 import { COVERAGE_STORE_KEY } from './constants' 5 5 6 - export default { 6 + const mod: CoverageProviderModule = { 7 7 takeCoverage() { 8 8 // @ts-expect-error -- untyped global 9 9 return globalThis[COVERAGE_STORE_KEY] ··· 46 46 47 47 return new IstanbulCoverageProvider() 48 48 }, 49 - } satisfies CoverageProviderModule 49 + } 50 + export default mod
+4 -3
packages/coverage-istanbul/src/provider.ts
··· 1 + import type { ProxifiedModule } from 'magicast' 1 2 import type { CoverageProvider, ReportContext, ResolvedCoverageOptions, Vitest } from 'vitest/node' 2 3 import { promises as fs } from 'node:fs' 3 4 // @ts-expect-error missing types ··· 21 22 22 23 export class IstanbulCoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<'istanbul'>> implements CoverageProvider { 23 24 name = 'istanbul' as const 24 - version = version 25 + version: string = version 25 26 instrumenter!: Instrumenter 26 27 testExclude!: InstanceType<typeof TestExclude> 27 28 ··· 81 82 return { code, map } 82 83 } 83 84 84 - createCoverageMap() { 85 + createCoverageMap(): libCoverage.CoverageMap { 85 86 return libCoverage.createCoverageMap({}) 86 87 } 87 88 ··· 149 150 } 150 151 } 151 152 152 - async parseConfigModule(configFilePath: string) { 153 + async parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>> { 153 154 return parseModule( 154 155 await fs.readFile(configFilePath, 'utf8'), 155 156 )
+2 -1
packages/coverage-istanbul/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 3 "compilerOptions": { 4 - "moduleResolution": "Bundler" 4 + "moduleResolution": "Bundler", 5 + "isolatedDeclarations": true 5 6 }, 6 7 "include": ["./src/**/*.ts"], 7 8 "exclude": ["./dist"]
+3 -2
packages/coverage-v8/src/browser.ts
··· 8 8 9 9 type ScriptCoverage = Awaited<ReturnType<typeof session.send<'Profiler.takePreciseCoverage'>>> 10 10 11 - export default { 11 + const mod: CoverageProviderModule = { 12 12 async startCoverage() { 13 13 if (enabled) { 14 14 return ··· 47 47 async getProvider(): Promise<V8CoverageProvider> { 48 48 return loadProvider() 49 49 }, 50 - } satisfies CoverageProviderModule 50 + } 51 + export default mod 51 52 52 53 function filterResult(coverage: ScriptCoverage['result'][number]): boolean { 53 54 if (!coverage.url.startsWith(window.location.origin)) {
+3 -2
packages/coverage-v8/src/index.ts
··· 8 8 const session = new inspector.Session() 9 9 let enabled = false 10 10 11 - export default { 11 + const mod: CoverageProviderModule = { 12 12 startCoverage({ isolate }) { 13 13 if (isolate === false && enabled) { 14 14 return ··· 60 60 async getProvider(): Promise<V8CoverageProvider> { 61 61 return loadProvider() 62 62 }, 63 - } satisfies CoverageProviderModule 63 + } 64 + export default mod 64 65 65 66 function filterResult(coverage: Profiler.ScriptCoverage): boolean { 66 67 if (!coverage.url.startsWith('file://')) {
+3 -1
packages/coverage-v8/src/load-provider.ts
··· 1 + import type { V8CoverageProvider } from './provider' 2 + 1 3 // to not bundle the provider 2 4 const name = './provider.js' 3 5 4 - export async function loadProvider() { 6 + export async function loadProvider(): Promise<V8CoverageProvider> { 5 7 const { V8CoverageProvider } = (await import(/* @vite-ignore */ name)) as typeof import('./provider') 6 8 7 9 return new V8CoverageProvider()
+4 -3
packages/coverage-v8/src/provider.ts
··· 1 1 import type { CoverageMap } from 'istanbul-lib-coverage' 2 + import type { ProxifiedModule } from 'magicast' 2 3 import type { Profiler } from 'node:inspector' 3 4 import type { EncodedSourceMap, FetchResult } from 'vite-node' 4 5 import type { AfterSuiteRunMeta } from 'vitest' ··· 43 44 44 45 export class V8CoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<'v8'>> implements CoverageProvider { 45 46 name = 'v8' as const 46 - version = version 47 + version: string = version 47 48 testExclude!: InstanceType<typeof TestExclude> 48 49 49 50 initialize(ctx: Vitest): void { ··· 59 60 }) 60 61 } 61 62 62 - createCoverageMap() { 63 + createCoverageMap(): CoverageMap { 63 64 return libCoverage.createCoverageMap({}) 64 65 } 65 66 ··· 151 152 } 152 153 } 153 154 154 - async parseConfigModule(configFilePath: string) { 155 + async parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>> { 155 156 return parseModule( 156 157 await fs.readFile(configFilePath, 'utf8'), 157 158 )
+2 -1
packages/coverage-v8/tsconfig.json
··· 2 2 "extends": "../../tsconfig.base.json", 3 3 "compilerOptions": { 4 4 "moduleResolution": "Bundler", 5 - "types": ["@vitest/browser/providers/playwright"] 5 + "types": ["@vitest/browser/providers/playwright"], 6 + "isolatedDeclarations": true 6 7 }, 7 8 "include": ["./src/**/*.ts"], 8 9 "exclude": ["./dist"]
+4 -4
packages/expect/src/constants.ts
··· 1 - export const MATCHERS_OBJECT = Symbol.for('matchers-object') 2 - export const JEST_MATCHERS_OBJECT = Symbol.for('$$jest-matchers-object') 3 - export const GLOBAL_EXPECT = Symbol.for('expect-global') 4 - export const ASYMMETRIC_MATCHERS_OBJECT = Symbol.for( 1 + export const MATCHERS_OBJECT: unique symbol = Symbol.for('matchers-object') 2 + export const JEST_MATCHERS_OBJECT: unique symbol = Symbol.for('$$jest-matchers-object') 3 + export const GLOBAL_EXPECT: unique symbol = Symbol.for('expect-global') 4 + export const ASYMMETRIC_MATCHERS_OBJECT: unique symbol = Symbol.for( 5 5 'asymmetric-matchers-object', 6 6 )
+22 -20
packages/expect/src/jest-asymmetric-matchers.ts
··· 28 28 State extends MatcherState = MatcherState, 29 29 > implements AsymmetricMatcherInterface { 30 30 // should have "jest" to be compatible with its ecosystem 31 - $$typeof = Symbol.for('jest.asymmetricMatcher') 31 + $$typeof: symbol = Symbol.for('jest.asymmetricMatcher') 32 32 33 33 constructor(protected sample: T, protected inverse = false) {} 34 34 ··· 51 51 abstract asymmetricMatch(other: unknown): boolean 52 52 abstract toString(): string 53 53 getExpectedType?(): string 54 - toAsymmetricMatcher?(): string; 54 + toAsymmetricMatcher?(): string 55 + } 55 56 56 - // implement custom chai/loupe inspect for better AssertionError.message formatting 57 - // https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 58 - [Symbol.for('chai/inspect')](options: { depth: number; truncate: number }) { 59 - // minimal pretty-format with simple manual truncation 60 - const result = stringify(this, options.depth, { min: true }) 61 - if (result.length <= options.truncate) { 62 - return result 63 - } 64 - return `${this.toString()}{…}` 57 + // implement custom chai/loupe inspect for better AssertionError.message formatting 58 + // https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 59 + // @ts-expect-error computed properties is not supported when isolatedDeclarations is enabled 60 + // FIXME: https://github.com/microsoft/TypeScript/issues/61068 61 + AsymmetricMatcher.prototype[Symbol.for('chai/inspect')] = function (options: { depth: number; truncate: number }): string { 62 + // minimal pretty-format with simple manual truncation 63 + const result = stringify(this, options.depth, { min: true }) 64 + if (result.length <= options.truncate) { 65 + return result 65 66 } 67 + return `${this.toString()}{…}` 66 68 } 67 69 68 70 export class StringContaining extends AsymmetricMatcher<string> { ··· 74 76 super(sample, inverse) 75 77 } 76 78 77 - asymmetricMatch(other: string) { 79 + asymmetricMatch(other: string): boolean { 78 80 const result = isA('String', other) && other.includes(this.sample) 79 81 80 82 return this.inverse ? !result : result ··· 90 92 } 91 93 92 94 export class Anything extends AsymmetricMatcher<void> { 93 - asymmetricMatch(other: unknown) { 95 + asymmetricMatch(other: unknown): boolean { 94 96 return other != null 95 97 } 96 98 ··· 110 112 super(sample, inverse) 111 113 } 112 114 113 - getPrototype(obj: object) { 115 + getPrototype(obj: object): any { 114 116 if (Object.getPrototypeOf) { 115 117 return Object.getPrototypeOf(obj) 116 118 } ··· 134 136 return this.hasProperty(this.getPrototype(obj), property) 135 137 } 136 138 137 - asymmetricMatch(other: any) { 139 + asymmetricMatch(other: any): boolean { 138 140 if (typeof this.sample !== 'object') { 139 141 throw new TypeError( 140 142 `You must provide an object to ${this.toString()}, not '${typeof this ··· 176 178 super(sample, inverse) 177 179 } 178 180 179 - asymmetricMatch(other: Array<T>) { 181 + asymmetricMatch(other: Array<T>): boolean { 180 182 if (!Array.isArray(this.sample)) { 181 183 throw new TypeError( 182 184 `You must provide an array to ${this.toString()}, not '${typeof this ··· 217 219 super(sample) 218 220 } 219 221 220 - fnNameFor(func: Function) { 222 + fnNameFor(func: Function): string { 221 223 if (func.name) { 222 224 return func.name 223 225 } ··· 230 232 return matches ? matches[1] : '<anonymous>' 231 233 } 232 234 233 - asymmetricMatch(other: unknown) { 235 + asymmetricMatch(other: unknown): boolean { 234 236 if (this.sample === String) { 235 237 return typeof other == 'string' || other instanceof String 236 238 } ··· 266 268 return 'Any' 267 269 } 268 270 269 - getExpectedType() { 271 + getExpectedType(): string { 270 272 if (this.sample === String) { 271 273 return 'string' 272 274 } ··· 304 306 super(new RegExp(sample), inverse) 305 307 } 306 308 307 - asymmetricMatch(other: string) { 309 + asymmetricMatch(other: string): boolean { 308 310 const result = isA('String', other) && this.sample.test(other) 309 311 310 312 return this.inverse ? !result : result
+14 -2
packages/expect/src/jest-matcher-utils.ts
··· 1 + import type { Formatter } from 'tinyrainbow' 1 2 import type { MatcherHintOptions, Tester } from './types' 2 3 import { getType, stringify } from '@vitest/utils' 3 4 import { diff, printDiffOrStringify } from '@vitest/utils/diff' ··· 18 19 received = 'received', 19 20 expected = 'expected', 20 21 options: MatcherHintOptions = {}, 21 - ) { 22 + ): string { 22 23 const { 23 24 comment = '', 24 25 isDirectExpectCall = false, // seems redundant with received === '' ··· 95 96 return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))) 96 97 } 97 98 98 - export function getMatcherUtils() { 99 + export function getMatcherUtils(): { 100 + EXPECTED_COLOR: Formatter 101 + RECEIVED_COLOR: Formatter 102 + INVERTED_COLOR: Formatter 103 + BOLD_WEIGHT: Formatter 104 + DIM_COLOR: Formatter 105 + diff: typeof diff 106 + matcherHint: typeof matcherHint 107 + printReceived: typeof printReceived 108 + printExpected: typeof printExpected 109 + printDiffOrStringify: typeof printDiffOrStringify 110 + } { 99 111 return { 100 112 EXPECTED_COLOR, 101 113 RECEIVED_COLOR,
+7 -7
packages/expect/src/jest-utils.ts
··· 38 38 39 39 const functionToString = Function.prototype.toString 40 40 41 - export function isAsymmetric(obj: any) { 41 + export function isAsymmetric(obj: any): boolean { 42 42 return ( 43 43 !!obj 44 44 && typeof obj === 'object' ··· 47 47 ) 48 48 } 49 49 50 - export function hasAsymmetric(obj: any, seen = new Set()): boolean { 50 + export function hasAsymmetric(obj: any, seen: Set<any> = new Set()): boolean { 51 51 if (seen.has(obj)) { 52 52 return false 53 53 } ··· 287 287 return Object.prototype.hasOwnProperty.call(obj, key) 288 288 } 289 289 290 - export function isA(typeName: string, value: unknown) { 290 + export function isA(typeName: string, value: unknown): boolean { 291 291 return Object.prototype.toString.apply(value) === `[object ${typeName}]` 292 292 } 293 293 ··· 304 304 ) 305 305 } 306 306 307 - export function fnNameFor(func: Function) { 307 + export function fnNameFor(func: Function): string { 308 308 if (func.name) { 309 309 return func.name 310 310 } ··· 346 346 const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@' 347 347 const IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@' 348 348 349 - export function isImmutableUnorderedKeyed(maybeKeyed: any) { 349 + export function isImmutableUnorderedKeyed(maybeKeyed: any): boolean { 350 350 return !!( 351 351 maybeKeyed 352 352 && maybeKeyed[IS_KEYED_SENTINEL] ··· 354 354 ) 355 355 } 356 356 357 - export function isImmutableUnorderedSet(maybeSet: any) { 357 + export function isImmutableUnorderedSet(maybeSet: any): boolean { 358 358 return !!( 359 359 maybeSet 360 360 && maybeSet[IS_SET_SENTINEL] ··· 687 687 deepEqualityName: string, 688 688 expected = '#{this}', 689 689 actual = '#{exp}', 690 - ) { 690 + ): string { 691 691 const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality` 692 692 693 693 if (['toStrictEqual', 'toEqual'].includes(deepEqualityName)) {
+2 -2
packages/expect/src/utils.ts
··· 19 19 promise: Promise<any>, 20 20 assertion: string, 21 21 error: Error, 22 - ) { 22 + ): Promise<any> { 23 23 const test = _test as Test | undefined 24 24 // record promise for test, that resolves before test ends 25 25 if (test && promise instanceof Promise) { ··· 78 78 name: string, 79 79 fn: (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void, 80 80 ) { 81 - return function (this: Chai.AssertionStatic & Assertion, ...args: any[]) { 81 + return function (this: Chai.AssertionStatic & Assertion, ...args: any[]): void { 82 82 // private 83 83 if (name !== 'withTest') { 84 84 utils.flag(this, '_name', name)
+3
packages/expect/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 + "compilerOptions": { 4 + "isolatedDeclarations": true 5 + }, 3 6 "include": ["./src/**/*.ts"], 4 7 "exclude": ["./dist"] 5 8 }
+3 -3
packages/ui/node/reporter.ts
··· 54 54 this.options = options 55 55 } 56 56 57 - async onInit(ctx: Vitest) { 57 + async onInit(ctx: Vitest): Promise<void> { 58 58 this.ctx = ctx 59 59 this.start = Date.now() 60 60 } 61 61 62 - async onFinished() { 62 + async onFinished(): Promise<void> { 63 63 const result: HTMLReportData = { 64 64 paths: this.ctx.state.getPaths(), 65 65 files: this.ctx.state.getFiles(), ··· 96 96 await this.writeReport(stringify(result)) 97 97 } 98 98 99 - async writeReport(report: string) { 99 + async writeReport(report: string): Promise<void> { 100 100 const htmlFile 101 101 = this.options.outputFile 102 102 || getOutputFile(this.ctx.config)
+3
packages/ui/node/tsconfig.json
··· 1 1 { 2 2 "extends": "../../../tsconfig.base.json", 3 + "compilerOptions": { 4 + "isolatedDeclarations": true 5 + }, 3 6 "include": ["./*.ts"] 4 7 }
+25 -21
packages/vite-node/src/client.ts
··· 48 48 } 49 49 50 50 export class ModuleCacheMap extends Map<string, ModuleCache> { 51 - normalizePath(fsPath: string) { 51 + normalizePath(fsPath: string): string { 52 52 return normalizeModuleId(fsPath) 53 53 } 54 54 55 55 /** 56 56 * Assign partial data to the map 57 57 */ 58 - update(fsPath: string, mod: ModuleCache) { 58 + update(fsPath: string, mod: ModuleCache): this { 59 59 fsPath = this.normalizePath(fsPath) 60 60 if (!super.has(fsPath)) { 61 61 this.setByModuleId(fsPath, mod) ··· 66 66 return this 67 67 } 68 68 69 - setByModuleId(modulePath: string, mod: ModuleCache) { 69 + setByModuleId(modulePath: string, mod: ModuleCache): this { 70 70 return super.set(modulePath, mod) 71 71 } 72 72 73 - set(fsPath: string, mod: ModuleCache) { 73 + set(fsPath: string, mod: ModuleCache): this { 74 74 return this.setByModuleId(this.normalizePath(fsPath), mod) 75 75 } 76 76 ··· 90 90 Required<Pick<ModuleCache, 'imports' | 'importers'>> 91 91 } 92 92 93 - get(fsPath: string) { 93 + get(fsPath: string): ModuleCache & Required<Pick<ModuleCache, 'importers' | 'imports'>> { 94 94 return this.getByModuleId(this.normalizePath(fsPath)) 95 95 } 96 96 ··· 98 98 return super.delete(modulePath) 99 99 } 100 100 101 - delete(fsPath: string) { 101 + delete(fsPath: string): boolean { 102 102 return this.deleteByModuleId(this.normalizePath(fsPath)) 103 103 } 104 104 ··· 117 117 */ 118 118 invalidateDepTree( 119 119 ids: string[] | Set<string>, 120 - invalidated = new Set<string>(), 121 - ) { 120 + invalidated: Set<string> = new Set<string>(), 121 + ): Set<string> { 122 122 for (const _id of ids) { 123 123 const id = this.normalizePath(_id) 124 124 if (invalidated.has(id)) { ··· 139 139 */ 140 140 invalidateSubDepTree( 141 141 ids: string[] | Set<string>, 142 - invalidated = new Set<string>(), 143 - ) { 142 + invalidated: Set<string> = new Set<string>(), 143 + ): Set<string> { 144 144 for (const _id of ids) { 145 145 const id = this.normalizePath(_id) 146 146 if (invalidated.has(id)) { ··· 161 161 /** 162 162 * Return parsed source map based on inlined source map of the module 163 163 */ 164 - getSourceMap(id: string) { 164 + getSourceMap(id: string): import('@jridgewell/trace-mapping').EncodedSourceMap | null { 165 165 const cache = this.get(id) 166 166 if (cache.map) { 167 167 return cache.map ··· 198 198 : false) 199 199 } 200 200 201 - async executeFile(file: string) { 201 + async executeFile(file: string): Promise<any> { 202 202 const url = `/@fs/${slash(resolve(file))}` 203 203 return await this.cachedRequest(url, url, []) 204 204 } 205 205 206 - async executeId(rawId: string) { 206 + async executeId(rawId: string): Promise<any> { 207 207 const [id, url] = await this.resolveUrl(rawId) 208 208 return await this.cachedRequest(id, url, []) 209 209 } ··· 264 264 } 265 265 } 266 266 267 - shouldResolveId(id: string, _importee?: string) { 267 + shouldResolveId(id: string, _importee?: string): boolean { 268 268 return ( 269 269 !isInternalRequest(id) && !isNodeBuiltin(id) && !id.startsWith('data:') 270 270 ) ··· 308 308 return [resolvedId, resolvedId] 309 309 } 310 310 311 - async resolveUrl(id: string, importee?: string) { 311 + async resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]> { 312 312 const resolveKey = `resolve:${id}` 313 313 // put info about new import as soon as possible, so we can start tracking it 314 314 this.moduleCache.setByModuleId(resolveKey, { resolving: true }) ··· 491 491 return exports 492 492 } 493 493 494 - protected getContextPrimitives() { 494 + protected getContextPrimitives(): { 495 + Object: ObjectConstructor 496 + Reflect: typeof Reflect 497 + Symbol: SymbolConstructor 498 + } { 495 499 return { Object, Reflect, Symbol } 496 500 } 497 501 498 - protected async runModule(context: Record<string, any>, transformed: string) { 502 + protected async runModule(context: Record<string, any>, transformed: string): Promise<void> { 499 503 // add 'use strict' since ESM enables it by default 500 504 const codeDefinition = `'use strict';async (${Object.keys(context).join( 501 505 ',', ··· 513 517 await fn(...Object.values(context)) 514 518 } 515 519 516 - prepareContext(context: Record<string, any>) { 520 + prepareContext(context: Record<string, any>): Record<string, any> { 517 521 return context 518 522 } 519 523 ··· 521 525 * Define if a module should be interop-ed 522 526 * This function mostly for the ability to override by subclass 523 527 */ 524 - shouldInterop(path: string, mod: any) { 528 + shouldInterop(path: string, mod: any): boolean { 525 529 if (this.options.interopDefault === false) { 526 530 return false 527 531 } ··· 530 534 return !path.endsWith('.mjs') && 'default' in mod 531 535 } 532 536 533 - protected importExternalModule(path: string) { 537 + protected importExternalModule(path: string): Promise<any> { 534 538 return import(path) 535 539 } 536 540 537 541 /** 538 542 * Import a module and interop it 539 543 */ 540 - async interopedImport(path: string) { 544 + async interopedImport(path: string): Promise<any> { 541 545 const importedModule = await this.importExternalModule(path) 542 546 543 547 if (!this.shouldInterop(path, importedModule)) {
+3 -3
packages/vite-node/src/constants.ts
··· 1 - export const KNOWN_ASSET_TYPES = [ 1 + export const KNOWN_ASSET_TYPES: string[] = [ 2 2 // images 3 3 'apng', 4 4 'bmp', ··· 34 34 'txt', 35 35 ] 36 36 37 - export const KNOWN_ASSET_RE = new RegExp( 37 + export const KNOWN_ASSET_RE: RegExp = new RegExp( 38 38 `\\.(${KNOWN_ASSET_TYPES.join('|')})$`, 39 39 ) 40 - export const CSS_LANGS_RE 40 + export const CSS_LANGS_RE: RegExp 41 41 = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
+5 -5
packages/vite-node/src/debug.ts
··· 15 15 export class Debugger { 16 16 dumpDir: string | undefined 17 17 initPromise: Promise<void> | undefined 18 - externalizeMap = new Map<string, string>() 18 + externalizeMap: Map<string, string> = new Map() 19 19 20 20 constructor(root: string, public options: DebuggerOptions) { 21 21 if (options.dumpModules) { ··· 39 39 this.initPromise = this.clearDump() 40 40 } 41 41 42 - async clearDump() { 42 + async clearDump(): Promise<void> { 43 43 if (!this.dumpDir) { 44 44 return 45 45 } ··· 55 55 )}.js` 56 56 } 57 57 58 - async recordExternalize(id: string, path: string) { 58 + async recordExternalize(id: string, path: string): Promise<void> { 59 59 if (!this.dumpDir) { 60 60 return 61 61 } ··· 63 63 await this.writeInfo() 64 64 } 65 65 66 - async dumpFile(id: string, result: TransformResult | null) { 66 + async dumpFile(id: string, result: TransformResult | null): Promise<void> { 67 67 if (!result || !this.dumpDir) { 68 68 return 69 69 } ··· 93 93 } 94 94 } 95 95 96 - async writeInfo() { 96 + async writeInfo(): Promise<void> { 97 97 if (!this.dumpDir) { 98 98 return 99 99 }
+2 -2
packages/vite-node/src/externalize.ts
··· 91 91 export async function shouldExternalize( 92 92 id: string, 93 93 options?: DepsHandlingOptions, 94 - cache = _defaultExternalizeCache, 95 - ) { 94 + cache: Map<string, Promise<string | false>> = _defaultExternalizeCache, 95 + ): Promise<string | false> { 96 96 if (!cache.has(id)) { 97 97 cache.set(id, _shouldExternalize(id, options)) 98 98 }
+3 -3
packages/vite-node/src/hmr/hmr.ts
··· 62 62 return cache.get(runner) as CacheData 63 63 } 64 64 65 - export function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter) { 65 + export function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter): void { 66 66 const maps = getCache(runner) 67 67 maps.messageBuffer.forEach(msg => emitter.emit('custom', msg)) 68 68 maps.messageBuffer.length = 0 69 69 } 70 70 71 - export async function reload(runner: ViteNodeRunner, files: string[]) { 71 + export async function reload(runner: ViteNodeRunner, files: string[]): Promise<any[]> { 72 72 // invalidate module cache but not node_modules 73 73 Array.from(runner.moduleCache.keys()).forEach((fsPath) => { 74 74 if (!fsPath.includes('node_modules')) { ··· 177 177 emitter: HMREmitter, 178 178 files: string[], 179 179 payload: HMRPayload, 180 - ) { 180 + ): Promise<void> { 181 181 const maps = getCache(runner) 182 182 switch (payload.type) { 183 183 case 'connected':
+16 -14
packages/vite-node/src/server.ts
··· 51 51 52 52 private existingOptimizedDeps = new Set<string>() 53 53 54 - fetchCaches = { 55 - ssr: new Map<string, FetchCache>(), 56 - web: new Map<string, FetchCache>(), 54 + fetchCaches: Record<'ssr' | 'web', Map<string, FetchCache>> = { 55 + ssr: new Map(), 56 + web: new Map(), 57 57 } 58 58 59 - fetchCache = new Map<string, FetchCache>() 59 + fetchCache: Map<string, FetchCache> = new Map() 60 60 61 - externalizeCache = new Map<string, Promise<string | false>>() 61 + externalizeCache: Map<string, Promise<string | false>> = new Map() 62 62 63 63 debugger?: Debugger 64 64 ··· 145 145 } 146 146 } 147 147 148 - shouldExternalize(id: string) { 148 + shouldExternalize(id: string): Promise<string | false> { 149 149 return shouldExternalize(id, this.options.deps, this.externalizeCache) 150 150 } 151 151 152 - public getTotalDuration() { 152 + public getTotalDuration(): number { 153 153 const ssrDurations = [...this.durations.ssr.values()].flat() 154 154 const webDurations = [...this.durations.web.values()].flat() 155 155 return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0) ··· 190 190 }) 191 191 } 192 192 193 - getSourceMap(source: string) { 193 + getSourceMap(source: string): EncodedSourceMap | null { 194 194 source = normalizeModuleId(source) 195 195 const fetchResult = this.fetchCache.get(source)?.result 196 196 if (fetchResult?.map) { ··· 219 219 }) 220 220 } 221 221 222 - async fetchResult(id: string, mode: 'web' | 'ssr') { 222 + async fetchResult(id: string, mode: 'web' | 'ssr'): Promise<FetchResult> { 223 223 const moduleId = normalizeModuleId(id) 224 224 this.assertMode(mode) 225 225 const promiseMap = this.fetchPromiseMap[mode] ··· 237 237 238 238 async transformRequest( 239 239 id: string, 240 - filepath = id, 240 + filepath: string = id, 241 241 transformMode?: 'web' | 'ssr', 242 - ) { 242 + ): Promise<TransformResult | null | undefined> { 243 243 const mode = transformMode || this.getTransformMode(id) 244 244 this.assertMode(mode) 245 245 const promiseMap = this.transformPromiseMap[mode] ··· 255 255 return promiseMap.get(id)! 256 256 } 257 257 258 - async transformModule(id: string, transformMode?: 'web' | 'ssr') { 258 + async transformModule(id: string, transformMode?: 'web' | 'ssr'): Promise<{ 259 + code: string | undefined 260 + }> { 259 261 if (transformMode !== 'web') { 260 262 throw new Error( 261 263 '`transformModule` only supports `transformMode: "web"`.', ··· 273 275 } 274 276 } 275 277 276 - getTransformMode(id: string) { 278 + getTransformMode(id: string): 'ssr' | 'web' { 277 279 const withoutQuery = id.split('?')[0] 278 280 279 281 if (this.options.transformMode?.web?.some(r => withoutQuery.match(r))) { ··· 388 390 protected async processTransformResult( 389 391 filepath: string, 390 392 result: TransformResult, 391 - ) { 393 + ): Promise<TransformResult> { 392 394 const mod = this.server.moduleGraph.getModuleById(filepath) 393 395 return withInlineSourcemap(result, { 394 396 filepath: mod?.file || filepath,
+2 -2
packages/vite-node/src/source-map-handler.ts
··· 467 467 retrieveSourceMap?: RetrieveMapHandler 468 468 } 469 469 470 - export const install = function (options: Options) { 470 + export const install = function (options: Options): void { 471 471 options = options || {} 472 472 473 473 // Allow sources to be found by methods other than reading the files ··· 498 498 } 499 499 } 500 500 501 - export const resetRetrieveHandlers = function () { 501 + export const resetRetrieveHandlers = function (): void { 502 502 retrieveFileHandlers.length = 0 503 503 retrieveMapHandlers.length = 0 504 504
+2 -2
packages/vite-node/src/source-map.ts
··· 24 24 filepath: string 25 25 noFirstLineMapping?: boolean 26 26 }, 27 - ) { 27 + ): TransformResult { 28 28 const map = result.map 29 29 let code = result.code 30 30 ··· 88 88 89 89 export function installSourcemapsSupport( 90 90 options: InstallSourceMapSupportOptions, 91 - ) { 91 + ): void { 92 92 install({ 93 93 retrieveSourceMap(source) { 94 94 const map = options.getSourceMap(source)
+7 -7
packages/vite-node/src/utils.ts
··· 4 4 import { fileURLToPath, pathToFileURL } from 'node:url' 5 5 import { dirname, join, resolve } from 'pathe' 6 6 7 - export const isWindows = process.platform === 'win32' 7 + export const isWindows: boolean = process.platform === 'win32' 8 8 9 9 const drive = isWindows ? process.cwd()[0] : null 10 10 const driveOpposite = drive ··· 17 17 ? new RegExp(`(?:^|/@fs/)${driveOpposite}(\:[\\/])`) 18 18 : null 19 19 20 - export function slash(str: string) { 20 + export function slash(str: string): string { 21 21 return str.replace(/\\/g, '/') 22 22 } 23 23 ··· 103 103 'wasi', 104 104 ]) 105 105 106 - export function normalizeModuleId(id: string) { 106 + export function normalizeModuleId(id: string): string { 107 107 // unique id that is not available as "test" 108 108 if (prefixedBuiltins.has(id)) { 109 109 return id ··· 118 118 .replace(/^\/+/, '/') 119 119 } 120 120 121 - export function isPrimitive(v: any) { 121 + export function isPrimitive(v: any): boolean { 122 122 return v !== Object(v) 123 123 } 124 124 ··· 193 193 cache: Map<string, T>, 194 194 basedir: string, 195 195 originalBasedir: string, 196 - ) { 196 + ): NonNullable<T> | undefined { 197 197 const pkgData = cache.get(getFnpdCacheKey(basedir)) 198 198 if (pkgData) { 199 199 traverseBetweenDirs(originalBasedir, basedir, (dir) => { ··· 208 208 data: T, 209 209 basedir: string, 210 210 originalBasedir: string, 211 - ) { 211 + ): void { 212 212 cache.set(getFnpdCacheKey(basedir), data) 213 213 traverseBetweenDirs(originalBasedir, basedir, (dir) => { 214 214 cache.set(getFnpdCacheKey(dir), data) ··· 243 243 return path 244 244 } 245 245 246 - export function createImportMetaEnvProxy() { 246 + export function createImportMetaEnvProxy(): NodeJS.ProcessEnv { 247 247 // packages/vitest/src/node/plugins/index.ts:146 248 248 const booleanKeys = ['DEV', 'PROD', 'SSR'] 249 249 return new Proxy(process.env, {
+3
packages/vite-node/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 + "compilerOptions": { 4 + "isolatedDeclarations": true 5 + }, 3 6 "include": ["./src/**/*.ts"], 4 7 "exclude": ["./dist"] 5 8 }
+6 -6
packages/vitest/src/api/setup.ts
··· 24 24 import { parseErrorStacktrace } from '../utils/source-map' 25 25 import { isValidApiRequest } from './check' 26 26 27 - export function setup(ctx: Vitest, _server?: ViteDevServer) { 27 + export function setup(ctx: Vitest, _server?: ViteDevServer): void { 28 28 const wss = new WebSocketServer({ noServer: true }) 29 29 30 30 const clients = new Map<WebSocket, WebSocketRPC>() ··· 164 164 public clients: Map<WebSocket, WebSocketRPC>, 165 165 ) {} 166 166 167 - onCollected(files?: File[]) { 167 + onCollected(files?: File[]): void { 168 168 if (this.clients.size === 0) { 169 169 return 170 170 } ··· 182 182 }) 183 183 } 184 184 185 - async onTaskUpdate(packs: TaskResultPack[]) { 185 + async onTaskUpdate(packs: TaskResultPack[]): Promise<void> { 186 186 if (this.clients.size === 0) { 187 187 return 188 188 } ··· 211 211 }) 212 212 } 213 213 214 - onFinished(files: File[], errors: unknown[]) { 214 + onFinished(files: File[], errors: unknown[]): void { 215 215 this.clients.forEach((client) => { 216 216 client.onFinished?.(files, errors)?.catch?.(noop) 217 217 }) 218 218 } 219 219 220 - onFinishedReportCoverage() { 220 + onFinishedReportCoverage(): void { 221 221 this.clients.forEach((client) => { 222 222 client.onFinishedReportCoverage?.()?.catch?.(noop) 223 223 }) 224 224 } 225 225 226 - onUserConsoleLog(log: UserConsoleLog) { 226 + onUserConsoleLog(log: UserConsoleLog): void { 227 227 this.clients.forEach((client) => { 228 228 client.onUserConsoleLog?.(log)?.catch?.(noop) 229 229 })
+6 -6
packages/vitest/src/constants.ts
··· 5 5 6 6 export const API_PATH = '/__vitest_api__' 7 7 8 - export const extraInlineDeps = [ 8 + export const extraInlineDeps: RegExp[] = [ 9 9 /^(?!.*node_modules).*\.mjs$/, 10 10 /^(?!.*node_modules).*\.cjs\.js$/, 11 11 // Vite client 12 12 /vite\w*\/dist\/client\/env.mjs/, 13 13 ] 14 14 15 - export const CONFIG_NAMES = ['vitest.config', 'vite.config'] 15 + export const CONFIG_NAMES: string[] = ['vitest.config', 'vite.config'] 16 16 17 17 const WORKSPACES_NAMES = ['vitest.workspace', 'vitest.projects'] 18 18 19 - export const CONFIG_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'] 19 + export const CONFIG_EXTENSIONS: string[] = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'] 20 20 21 - export const configFiles = CONFIG_NAMES.flatMap(name => 21 + export const configFiles: string[] = CONFIG_NAMES.flatMap(name => 22 22 CONFIG_EXTENSIONS.map(ext => name + ext), 23 23 ) 24 24 25 25 const WORKSPACES_EXTENSIONS = [...CONFIG_EXTENSIONS, '.json'] 26 26 27 - export const workspacesFiles = WORKSPACES_NAMES.flatMap(name => 27 + export const workspacesFiles: string[] = WORKSPACES_NAMES.flatMap(name => 28 28 WORKSPACES_EXTENSIONS.map(ext => name + ext), 29 29 ) 30 30 31 - export const globalApis = [ 31 + export const globalApis: string[] = [ 32 32 // suite 33 33 'suite', 34 34 'test',
+1 -1
packages/vitest/src/create/browser/creator.ts
··· 360 360 } 361 361 } 362 362 363 - export async function create() { 363 + export async function create(): Promise<void> { 364 364 log(c.cyan('◼'), 'This utility will help you set up a browser testing environment.\n') 365 365 366 366 const pkgJsonPath = resolve(process.cwd(), 'package.json')
+1 -1
packages/vitest/src/create/browser/examples.ts
··· 198 198 } 199 199 } 200 200 201 - export async function generateExampleFiles(framework: string, lang: 'ts' | 'js') { 201 + export async function generateExampleFiles(framework: string, lang: 'ts' | 'js'): Promise<string> { 202 202 const example = getExampleTest(framework) 203 203 let fileName = example.name 204 204 const folder = resolve(process.cwd(), 'vitest-example')
+44 -8
packages/vitest/src/defaults.ts
··· 9 9 10 10 export { defaultBrowserPort } from './constants' 11 11 12 - export const defaultInclude = ['**/*.{test,spec}.?(c|m)[jt]s?(x)'] 13 - export const defaultExclude = [ 12 + export const defaultInclude: string[] = ['**/*.{test,spec}.?(c|m)[jt]s?(x)'] 13 + export const defaultExclude: string[] = [ 14 14 '**/node_modules/**', 15 15 '**/dist/**', 16 16 '**/cypress/**', ··· 85 85 ), 86 86 } 87 87 88 - export const fakeTimersDefaults = { 88 + export const fakeTimersDefaults: NonNullable<UserConfig['fakeTimers']> = { 89 89 loopLimit: 10_000, 90 90 shouldClearNativeTimers: true, 91 - } satisfies NonNullable<UserConfig['fakeTimers']> 91 + } 92 92 93 - const config = { 93 + export const configDefaults: Readonly<{ 94 + allowOnly: boolean 95 + isolate: boolean 96 + watch: boolean 97 + globals: boolean 98 + environment: 'node' 99 + pool: 'forks' 100 + clearMocks: boolean 101 + restoreMocks: boolean 102 + mockReset: boolean 103 + unstubGlobals: boolean 104 + unstubEnvs: boolean 105 + include: string[] 106 + exclude: string[] 107 + teardownTimeout: number 108 + forceRerunTriggers: string[] 109 + update: boolean 110 + reporters: never[] 111 + silent: boolean 112 + hideSkippedTests: boolean 113 + api: boolean 114 + ui: boolean 115 + uiBase: string 116 + open: boolean 117 + css: { 118 + include: never[] 119 + } 120 + coverage: CoverageV8Options 121 + fakeTimers: import('@sinonjs/fake-timers').FakeTimerInstallOpts 122 + maxConcurrency: number 123 + dangerouslyIgnoreUnhandledErrors: boolean 124 + typecheck: { 125 + checker: 'tsc' 126 + include: string[] 127 + exclude: string[] 128 + } 129 + slowTestThreshold: number 130 + disableConsoleIntercept: boolean 131 + }> = Object.freeze({ 94 132 allowOnly: !isCI, 95 133 isolate: true, 96 134 watch: !isCI, ··· 128 166 }, 129 167 slowTestThreshold: 300, 130 168 disableConsoleIntercept: false, 131 - } satisfies UserConfig 132 - 133 - export const configDefaults = Object.freeze(config) 169 + })
+1 -1
packages/vitest/src/integrations/chai/config.ts
··· 1 1 import * as chai from 'chai' 2 2 3 - export function setupChaiConfig(config: ChaiConfig) { 3 + export function setupChaiConfig(config: ChaiConfig): void { 4 4 Object.assign(chai.config, config) 5 5 } 6 6
+2 -2
packages/vitest/src/integrations/chai/index.ts
··· 17 17 import { createExpectPoll } from './poll' 18 18 import './setup' 19 19 20 - export function createExpect(test?: TaskPopulated) { 20 + export function createExpect(test?: TaskPopulated): ExpectStatic { 21 21 const expect = ((value: any, message?: string): Assertion => { 22 22 const { assertionCalls } = getState(expect) 23 23 setState({ assertionCalls: assertionCalls + 1 }, expect) ··· 115 115 return expect 116 116 } 117 117 118 - const globalExpect = createExpect() 118 + const globalExpect: ExpectStatic = createExpect() 119 119 120 120 Object.defineProperty(globalThis, GLOBAL_EXPECT, { 121 121 value: globalExpect,
+3 -3
packages/vitest/src/integrations/coverage.ts
··· 75 75 options: SerializedCoverageConfig | undefined, 76 76 loader: CoverageModuleLoader, 77 77 runtimeOptions: { isolate: boolean }, 78 - ) { 78 + ): Promise<unknown> { 79 79 const coverageModule = await resolveCoverageProviderModule(options, loader) 80 80 81 81 if (coverageModule) { ··· 88 88 export async function takeCoverageInsideWorker( 89 89 options: SerializedCoverageConfig | undefined, 90 90 loader: CoverageModuleLoader, 91 - ) { 91 + ): Promise<unknown> { 92 92 const coverageModule = await resolveCoverageProviderModule(options, loader) 93 93 94 94 if (coverageModule) { ··· 102 102 options: SerializedCoverageConfig | undefined, 103 103 loader: CoverageModuleLoader, 104 104 runtimeOptions: { isolate: boolean }, 105 - ) { 105 + ): Promise<unknown> { 106 106 const coverageModule = await resolveCoverageProviderModule(options, loader) 107 107 108 108 if (coverageModule) {
+2 -2
packages/vitest/src/integrations/css/css-modules.ts
··· 1 1 import type { CSSModuleScopeStrategy } from '../../node/types/config' 2 2 import { hash } from '../../node/hash' 3 3 4 - export function generateCssFilenameHash(filepath: string) { 4 + export function generateCssFilenameHash(filepath: string): string { 5 5 return hash('md5', filepath, 'hex').slice(0, 6) 6 6 } 7 7 ··· 9 9 strategy: CSSModuleScopeStrategy, 10 10 name: string, 11 11 filename: string, 12 - ) { 12 + ): string | null { 13 13 // should be configured by Vite defaults 14 14 if (strategy === 'scoped') { 15 15 return null
+8 -2
packages/vitest/src/integrations/env/index.ts
··· 1 + import type { Environment } from '../../types/environment' 1 2 import edge from './edge-runtime' 2 3 import happy from './happy-dom' 3 4 import jsdom from './jsdom' 4 5 import node from './node' 5 6 6 - export const environments = { 7 + export const environments: { 8 + 'node': Environment 9 + 'jsdom': Environment 10 + 'happy-dom': Environment 11 + 'edge-runtime': Environment 12 + } = { 7 13 node, 8 14 jsdom, 9 15 'happy-dom': happy, 10 16 'edge-runtime': edge, 11 17 } 12 18 13 - export const envs = Object.keys(environments) 19 + export const envs: string[] = Object.keys(environments)
+1 -1
packages/vitest/src/integrations/env/jsdom-keys.ts
··· 248 248 'window', 249 249 ] 250 250 251 - export const KEYS = LIVING_KEYS.concat(OTHER_KEYS) 251 + export const KEYS: string[] = LIVING_KEYS.concat(OTHER_KEYS)
+1 -1
packages/vitest/src/integrations/env/loader.ts
··· 15 15 16 16 const _loaders = new Map<string, ViteNodeRunner>() 17 17 18 - export async function createEnvironmentLoader(options: ViteNodeRunnerOptions) { 18 + export async function createEnvironmentLoader(options: ViteNodeRunnerOptions): Promise<ViteNodeRunner> { 19 19 if (!_loaders.has(options.root)) { 20 20 const loader = new ViteNodeRunner(options) 21 21 await loader.executeId('/@vite/env')
+6 -2
packages/vitest/src/integrations/env/utils.ts
··· 6 6 global: any, 7 7 win: any, 8 8 additionalKeys: string[] = [], 9 - ) { 9 + ): Set<string> { 10 10 const keysArray = [...additionalKeys, ...KEYS] 11 11 const keys = new Set( 12 12 keysArray.concat(Object.getOwnPropertyNames(win)).filter((k) => { ··· 42 42 global: any, 43 43 win: any, 44 44 options: PopulateOptions = {}, 45 - ) { 45 + ): { 46 + keys: Set<string> 47 + skipKeys: string[] 48 + originals: Map<string | symbol, any> 49 + } { 46 50 const { bindFunctions = false } = options 47 51 const keys = getWindowKeys(global, win, options.additionalKeys) 48 52
+1 -1
packages/vitest/src/integrations/globals.ts
··· 1 1 import { globalApis } from '../constants' 2 2 import * as index from '../public/index' 3 3 4 - export function registerApiGlobally() { 4 + export function registerApiGlobally(): void { 5 5 globalApis.forEach((api) => { 6 6 // @ts-expect-error I know what I am doing :P 7 7 globalThis[api] = index[api]
+1 -1
packages/vitest/src/integrations/mock/date.ts
··· 23 23 SOFTWARE. 24 24 */ 25 25 26 - export const RealDate = Date 26 + export const RealDate: DateConstructor = Date 27 27 28 28 let now: null | number = null 29 29
+1 -1
packages/vitest/src/integrations/mock/timers.ts
··· 214 214 this._userConfig = config 215 215 } 216 216 217 - isFakeTimers() { 217 + isFakeTimers(): boolean { 218 218 return this._fakingTime 219 219 } 220 220
+1 -1
packages/vitest/src/integrations/run-once.ts
··· 36 36 * 37 37 * @experimental 38 38 */ 39 - export function isFirstRun() { 39 + export function isFirstRun(): boolean { 40 40 let firstRun = false 41 41 runOnce(() => { 42 42 firstRun = true
+2 -2
packages/vitest/src/integrations/utils.ts
··· 1 1 // Runtime utils exposed to `vitest` 2 2 3 - export function getRunningMode() { 3 + export function getRunningMode(): 'watch' | 'run' { 4 4 return process.env.VITEST_MODE === 'WATCH' ? 'watch' : 'run' 5 5 } 6 6 7 - export function isWatchMode() { 7 + export function isWatchMode(): boolean { 8 8 return getRunningMode() === 'watch' 9 9 }
+2 -2
packages/vitest/src/integrations/vi.ts
··· 714 714 return utils 715 715 } 716 716 717 - export const vitest = createVitest() 718 - export const vi = vitest 717 + export const vitest: VitestUtils = createVitest() 718 + export const vi: VitestUtils = vitest 719 719 720 720 function _mocker(): VitestMocker { 721 721 // @ts-expect-error injected by vite-nide
+2 -2
packages/vitest/src/integrations/wait.ts
··· 28 28 export function waitFor<T>( 29 29 callback: WaitForCallback<T>, 30 30 options: number | WaitForOptions = {}, 31 - ) { 31 + ): Promise<T> { 32 32 const { setTimeout, setInterval, clearTimeout, clearInterval } 33 33 = getSafeTimers() 34 34 const { interval = 50, timeout = 1000 } ··· 124 124 export function waitUntil<T>( 125 125 callback: WaitUntilCallback<T>, 126 126 options: number | WaitUntilOptions = {}, 127 - ) { 127 + ): Promise<Truthy<T>> { 128 128 const { setTimeout, setInterval, clearTimeout, clearInterval } 129 129 = getSafeTimers() 130 130 const { interval = 50, timeout = 1000 }
+1 -1
packages/vitest/src/node/browser/sessions.ts
··· 5 5 export class BrowserSessions { 6 6 private sessions = new Map<string, BrowserServerStateSession>() 7 7 8 - getSession(sessionId: string) { 8 + getSession(sessionId: string): BrowserServerStateSession | undefined { 9 9 return this.sessions.get(sessionId) 10 10 } 11 11
+4 -4
packages/vitest/src/node/cache/files.ts
··· 6 6 type FileStatsCache = Pick<Stats, 'size'> 7 7 8 8 export class FilesStatsCache { 9 - public cache = new Map<string, FileStatsCache>() 9 + public cache: Map<string, FileStatsCache> = new Map() 10 10 11 11 public getStats(key: string): FileStatsCache | undefined { 12 12 return this.cache.get(key) 13 13 } 14 14 15 - public async populateStats(root: string, specs: TestSpecification[]) { 15 + public async populateStats(root: string, specs: TestSpecification[]): Promise<void> { 16 16 const promises = specs.map((spec) => { 17 17 const key = `${spec[0].name}:${relative(root, spec.moduleId)}` 18 18 return this.updateStats(spec.moduleId, key) ··· 20 20 await Promise.all(promises) 21 21 } 22 22 23 - public async updateStats(fsPath: string, key: string) { 23 + public async updateStats(fsPath: string, key: string): Promise<void> { 24 24 if (!fs.existsSync(fsPath)) { 25 25 return 26 26 } ··· 28 28 this.cache.set(key, { size: stats.size }) 29 29 } 30 30 31 - public removeStats(fsPath: string) { 31 + public removeStats(fsPath: string): void { 32 32 this.cache.forEach((_, key) => { 33 33 if (key.endsWith(fsPath)) { 34 34 this.cache.delete(key)
+7 -4
packages/vitest/src/node/cache/index.ts
··· 1 + import type { SuiteResultCache } from './results' 1 2 import { slash } from '@vitest/utils' 2 3 import { resolve } from 'pathe' 3 4 import { hash } from '../hash' ··· 6 7 7 8 export class VitestCache { 8 9 results: ResultsCache 9 - stats = new FilesStatsCache() 10 + stats: FilesStatsCache = new FilesStatsCache() 10 11 11 12 constructor(version: string) { 12 13 this.results = new ResultsCache(version) 13 14 } 14 15 15 - getFileTestResults(key: string) { 16 + getFileTestResults(key: string): SuiteResultCache | undefined { 16 17 return this.results.getResults(key) 17 18 } 18 19 19 - getFileStats(key: string) { 20 + getFileStats(key: string): { 21 + size: number 22 + } | undefined { 20 23 return this.stats.getStats(key) 21 24 } 22 25 23 - static resolveCacheDir(root: string, dir?: string, projectName?: string) { 26 + static resolveCacheDir(root: string, dir?: string, projectName?: string): string { 24 27 const baseDir = slash(dir || 'node_modules/.vite/vitest') 25 28 return projectName 26 29 ? resolve(
+7 -7
packages/vitest/src/node/cache/results.ts
··· 19 19 this.version = version 20 20 } 21 21 22 - public getCachePath() { 22 + public getCachePath(): string | null { 23 23 return this.cachePath 24 24 } 25 25 26 - setConfig(root: string, config: ResolvedConfig['cache']) { 26 + setConfig(root: string, config: ResolvedConfig['cache']): void { 27 27 this.root = root 28 28 if (config) { 29 29 this.cachePath = resolve(config.dir, 'results.json') 30 30 } 31 31 } 32 32 33 - getResults(key: string) { 33 + getResults(key: string): SuiteResultCache | undefined { 34 34 return this.cache.get(key) 35 35 } 36 36 37 - async readFromCache() { 37 + async readFromCache(): Promise<void> { 38 38 if (!this.cachePath) { 39 39 return 40 40 } ··· 58 58 } 59 59 } 60 60 61 - updateResults(files: File[]) { 61 + updateResults(files: File[]): void { 62 62 files.forEach((file) => { 63 63 const result = file.result 64 64 if (!result) { ··· 74 74 }) 75 75 } 76 76 77 - removeFromCache(filepath: string) { 77 + removeFromCache(filepath: string): void { 78 78 this.cache.forEach((_, key) => { 79 79 if (key.endsWith(filepath)) { 80 80 this.cache.delete(key) ··· 82 82 }) 83 83 } 84 84 85 - async writeToCache() { 85 + async writeToCache(): Promise<void> { 86 86 if (!this.cachePath) { 87 87 return 88 88 }
+1 -1
packages/vitest/src/node/cli/cac.ts
··· 70 70 } 71 71 } 72 72 73 - export function createCLI(options: CliParseOptions = {}) { 73 + export function createCLI(options: CliParseOptions = {}): CAC { 74 74 const cli = cac('vitest') 75 75 76 76 cli.version(version)
+5 -5
packages/vitest/src/node/cli/cli-api.ts
··· 158 158 return ctx 159 159 } 160 160 161 - export function processCollected(ctx: Vitest, files: TestModule[], options: CliOptions) { 161 + export function processCollected(ctx: Vitest, files: TestModule[], options: CliOptions): void { 162 162 let errorsPrinted = false 163 163 164 164 forEachSuite(files, (suite) => { ··· 181 181 return formatCollectedAsString(files).forEach(test => console.log(test)) 182 182 } 183 183 184 - export function outputFileList(files: TestSpecification[], options: CliOptions) { 184 + export function outputFileList(files: TestSpecification[], options: CliOptions): void { 185 185 if (typeof options.json !== 'undefined') { 186 186 return outputJsonFileList(files, options) 187 187 } 188 188 189 - return formatFilesAsString(files, options).map(file => console.log(file)) 189 + formatFilesAsString(files, options).map(file => console.log(file)) 190 190 } 191 191 192 192 function outputJsonFileList(files: TestSpecification[], options: CliOptions) { ··· 251 251 location?: { line: number; column: number } 252 252 } 253 253 254 - export function formatCollectedAsJSON(files: TestModule[]) { 254 + export function formatCollectedAsJSON(files: TestModule[]): TestCollectJSONResult[] { 255 255 const results: TestCollectJSONResult[] = [] 256 256 257 257 files.forEach((file) => { ··· 275 275 return results 276 276 } 277 277 278 - export function formatCollectedAsString(testModules: TestModule[]) { 278 + export function formatCollectedAsString(testModules: TestModule[]): string[] { 279 279 const results: string[] = [] 280 280 281 281 testModules.forEach((testModule) => {
+1 -1
packages/vitest/src/node/cli/filter.ts
··· 31 31 lineNumber?: undefined | number 32 32 } 33 33 34 - export function groupFilters(filters: FileFilter[]) { 34 + export function groupFilters(filters: FileFilter[]): Record<string, number[]> { 35 35 const groupedFilters_ = groupBy(filters, f => f.filename) 36 36 const groupedFilters = Object.fromEntries(Object.entries(groupedFilters_) 37 37 .map((entry) => {
+11 -11
packages/vitest/src/node/core.ts
··· 56 56 * Current Vitest version. 57 57 * @example '2.0.0' 58 58 */ 59 - public readonly version = version 60 - static readonly version = version 59 + public readonly version: string = version 60 + static readonly version: string = version 61 61 /** 62 62 * The logger instance used to log messages. It's recommended to use this logger instead of `console`. 63 63 * It's possible to override stdout and stderr streams when initiating Vitest. ··· 76 76 /** 77 77 * A path to the built Vitest directory. This is usually a folder in `node_modules`. 78 78 */ 79 - public readonly distPath = distDir 79 + public readonly distPath: string = distDir 80 80 /** 81 81 * A list of projects that are currently running. 82 82 * If projects were filtered with `--project` flag, they won't appear here. ··· 137 137 private _onFilterWatchedSpecification: ((spec: TestSpecification) => boolean)[] = [] 138 138 139 139 /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */ 140 - public get invalidates() { 140 + public get invalidates(): Set<string> { 141 141 return this.watcher.invalidates 142 142 } 143 143 144 144 /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */ 145 - public get changedTests() { 145 + public get changedTests(): Set<string> { 146 146 return this.watcher.changedTests 147 147 } 148 148 ··· 193 193 } 194 194 195 195 /** @deprecated internal */ 196 - setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig) { 196 + setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig): Promise<void> { 197 197 return this._setServer(options, server, cliOptions) 198 198 } 199 199 ··· 300 300 /** 301 301 * Provide a value to the test context. This value will be available to all tests with `inject`. 302 302 */ 303 - public provide = <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => { 303 + public provide = <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void => { 304 304 this.getRootProject().provide(key, value) 305 305 } 306 306 ··· 639 639 /** 640 640 * Vitest automatically caches test specifications for each file. This method clears the cache for the given file or the whole cache altogether. 641 641 */ 642 - public clearSpecificationsCache(moduleId?: string) { 642 + public clearSpecificationsCache(moduleId?: string): void { 643 643 this.specifications.clearCache(moduleId) 644 644 } 645 645 ··· 1180 1180 /** 1181 1181 * @deprecated use `globTestSpecifications` instead 1182 1182 */ 1183 - public async globTestSpecs(filters: string[] = []) { 1183 + public async globTestSpecs(filters: string[] = []): Promise<TestSpecification[]> { 1184 1184 return this.globTestSpecifications(filters) 1185 1185 } 1186 1186 1187 1187 /** 1188 1188 * @deprecated use `globTestSpecifications` instead 1189 1189 */ 1190 - public async globTestFiles(filters: string[] = []) { 1190 + public async globTestFiles(filters: string[] = []): Promise<TestSpecification[]> { 1191 1191 return this.globTestSpecifications(filters) 1192 1192 } 1193 1193 1194 1194 /** @deprecated filter by `this.projects` yourself */ 1195 - public getModuleProjects(filepath: string) { 1195 + public getModuleProjects(filepath: string): TestProject[] { 1196 1196 return this.projects.filter((project) => { 1197 1197 return project.getModulesByFilepath(filepath).size 1198 1198 // TODO: reevaluate || project.browser?.moduleGraph.getModulesByFile(id)?.size
+2 -2
packages/vitest/src/node/error.ts
··· 39 39 error: unknown, 40 40 ctx: Vitest, 41 41 options: ErrorOptions, 42 - ) { 42 + ): { nearest: ParsedStack | undefined; output: string } { 43 43 let output = '' 44 44 const writable = new Writable({ 45 45 write(chunk, _encoding, callback) { ··· 64 64 ctx: Vitest, 65 65 logger: ErrorLogger, 66 66 options: ErrorOptions, 67 - ) { 67 + ): PrintErrorResult | undefined { 68 68 const project = options.project 69 69 ?? ctx.coreWorkspaceProject 70 70 ?? ctx.projects[0]
+2 -2
packages/vitest/src/node/git.ts
··· 29 29 .map(changedPath => resolve(this.root, changedPath)) 30 30 } 31 31 32 - async findChangedFiles(options: GitOptions) { 32 + async findChangedFiles(options: GitOptions): Promise<string[] | null> { 33 33 const root = await this.getRoot(this.cwd) 34 34 if (!root) { 35 35 return null ··· 74 74 ]) 75 75 } 76 76 77 - async getRoot(cwd: string) { 77 + async getRoot(cwd: string): Promise<string | null> { 78 78 const args = ['rev-parse', '--show-cdup'] 79 79 80 80 try {
+1 -1
packages/vitest/src/node/hash.ts
··· 1 1 import crypto from 'node:crypto' 2 2 3 - export const hash = crypto.hash ?? (( 3 + export const hash: typeof crypto.hash = crypto.hash ?? (( 4 4 algorithm: string, 5 5 data: crypto.BinaryLike, 6 6 outputEncoding: crypto.BinaryToTextEncoding,
+15 -15
packages/vitest/src/node/logger.ts
··· 55 55 } 56 56 } 57 57 58 - log(...args: any[]) { 58 + log(...args: any[]): void { 59 59 this._clearScreen() 60 60 this.console.log(...args) 61 61 } 62 62 63 - error(...args: any[]) { 63 + error(...args: any[]): void { 64 64 this._clearScreen() 65 65 this.console.error(...args) 66 66 } 67 67 68 - warn(...args: any[]) { 68 + warn(...args: any[]): void { 69 69 this._clearScreen() 70 70 this.console.warn(...args) 71 71 } 72 72 73 - clearFullScreen(message = '') { 73 + clearFullScreen(message = ''): void { 74 74 if (!this.ctx.config.clearScreen) { 75 75 this.console.log(message) 76 76 return ··· 84 84 } 85 85 } 86 86 87 - clearScreen(message: string, force = false) { 87 + clearScreen(message: string, force = false): void { 88 88 if (!this.ctx.config.clearScreen) { 89 89 this.console.log(message) 90 90 return ··· 106 106 this.console.log(`${CURSOR_TO_START}${ERASE_DOWN}${log}`) 107 107 } 108 108 109 - printError(err: unknown, options: ErrorOptions = {}) { 109 + printError(err: unknown, options: ErrorOptions = {}): void { 110 110 printError(err, this.ctx, this, options) 111 111 } 112 112 113 - clearHighlightCache(filename?: string) { 113 + clearHighlightCache(filename?: string): void { 114 114 if (filename) { 115 115 this._highlights.delete(filename) 116 116 } ··· 119 119 } 120 120 } 121 121 122 - highlight(filename: string, source: string) { 122 + highlight(filename: string, source: string): string { 123 123 if (this._highlights.has(filename)) { 124 124 return this._highlights.get(filename)! 125 125 } ··· 128 128 return code 129 129 } 130 130 131 - printNoTestFound(filters?: string[]) { 131 + printNoTestFound(filters?: string[]): void { 132 132 const config = this.ctx.config 133 133 134 134 if (config.watch && (config.changed || config.related?.length)) { ··· 190 190 this.console.error() 191 191 } 192 192 193 - printBanner() { 193 + printBanner(): void { 194 194 this.log() 195 195 196 196 const color = this.ctx.config.watch ? 'blue' : 'cyan' ··· 230 230 } 231 231 } 232 232 233 - printBrowserBanner(project: TestProject) { 233 + printBrowserBanner(project: TestProject): void { 234 234 if (!project.browser) { 235 235 return 236 236 } ··· 253 253 ) 254 254 } 255 255 256 - printUnhandledErrors(errors: unknown[]) { 256 + printUnhandledErrors(errors: unknown[]): void { 257 257 const errorMessage = c.red( 258 258 c.bold( 259 259 `\nVitest caught ${errors.length} unhandled error${ ··· 273 273 this.error(c.red(divider())) 274 274 } 275 275 276 - printSourceTypeErrors(errors: TypeCheckError[]) { 276 + printSourceTypeErrors(errors: TypeCheckError[]): void { 277 277 const errorMessage = c.red( 278 278 c.bold( 279 279 `\nVitest found ${errors.length} error${ ··· 289 289 this.log(c.red(divider())) 290 290 } 291 291 292 - getColumns() { 292 + getColumns(): number { 293 293 return 'columns' in this.outputStream ? this.outputStream.columns : 80 294 294 } 295 295 296 - onTerminalCleanup(listener: Listener) { 296 + onTerminalCleanup(listener: Listener): void { 297 297 this.cleanupListeners.push(listener) 298 298 } 299 299
+2 -2
packages/vitest/src/node/packageInstaller.ts
··· 7 7 const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) 8 8 9 9 export class VitestPackageInstaller { 10 - isPackageExists(name: string, options?: { paths?: string[] }) { 10 + isPackageExists(name: string, options?: { paths?: string[] }): boolean { 11 11 return isPackageExists(name, options) 12 12 } 13 13 14 - async ensureInstalled(dependency: string, root: string, version?: string) { 14 + async ensureInstalled(dependency: string, root: string, version?: string): Promise<boolean> { 15 15 if (process.env.VITEST_SKIP_INSTALL_CHECKS) { 16 16 return true 17 17 }
+1 -1
packages/vitest/src/node/plugins/index.ts
··· 28 28 29 29 export async function VitestPlugin( 30 30 options: UserConfig = {}, 31 - ctx = new Vitest('test'), 31 + ctx: Vitest = new Vitest('test'), 32 32 ): Promise<VitePlugin[]> { 33 33 const userConfig = deepMerge({}, options) as UserConfig 34 34
+4 -4
packages/vitest/src/node/plugins/utils.ts
··· 15 15 viteOptions: DepOptimizationOptions | undefined, 16 16 testConfig: InlineConfig, 17 17 viteCacheDir: string | undefined, 18 - ) { 18 + ): { cacheDir?: string; optimizeDeps: DepOptimizationOptions } { 19 19 const testOptions = _testOptions || {} 20 20 const newConfig: { cacheDir?: string; optimizeDeps: DepOptimizationOptions } 21 21 = {} as any ··· 85 85 return newConfig 86 86 } 87 87 88 - export function deleteDefineConfig(viteConfig: ViteConfig) { 88 + export function deleteDefineConfig(viteConfig: ViteConfig): Record<string, any> { 89 89 const defines: Record<string, any> = {} 90 90 if (viteConfig.define) { 91 91 delete viteConfig.define['import.meta.vitest'] ··· 122 122 return defines 123 123 } 124 124 125 - export function hijackVitePluginInject(viteConfig: ResolvedConfig) { 125 + export function hijackVitePluginInject(viteConfig: ResolvedConfig): void { 126 126 // disable replacing `process.env.NODE_ENV` with static string 127 127 const processEnvPlugin = viteConfig.plugins.find( 128 128 p => p.name === 'vite:client-inject', ··· 138 138 export function resolveFsAllow( 139 139 projectRoot: string, 140 140 rootConfigFile: string | false | undefined, 141 - ) { 141 + ): string[] { 142 142 if (!rootConfigFile) { 143 143 return [searchForWorkspaceRoot(projectRoot), rootDir] 144 144 }
+1 -1
packages/vitest/src/node/pool.ts
··· 66 66 return project.config.pool 67 67 } 68 68 69 - export function getFilePoolName(project: TestProject, file: string) { 69 + export function getFilePoolName(project: TestProject, file: string): Pool { 70 70 for (const [glob, pool] of project.config.poolMatchGlobs) { 71 71 if ((pool as Pool) === 'browser') { 72 72 throw new Error(
+7 -6
packages/vitest/src/node/project.ts
··· 9 9 import type { OnTestsRerunHandler, Vitest } from './core' 10 10 import type { GlobalSetupFile } from './globalSetup' 11 11 import type { Logger } from './logger' 12 + import type { Reporter } from './reporters' 12 13 import type { ParentProjectBrowser, ProjectBrowser } from './types/browser' 13 14 import type { 14 15 ResolvedConfig, ··· 60 61 /** 61 62 * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here. 62 63 */ 63 - public readonly tmpDir = join(tmpdir(), nanoid()) 64 + public readonly tmpDir: string = join(tmpdir(), nanoid()) 64 65 65 66 /** @internal */ vitenode!: ViteNodeServer 66 67 /** @internal */ typechecker?: Typechecker ··· 81 82 /** @deprecated */ 82 83 public path: string | number, 83 84 vitest: Vitest, 84 - public options?: InitializeProjectOptions, 85 + public options?: InitializeProjectOptions | undefined, 85 86 ) { 86 87 this.vitest = vitest 87 88 this.ctx = vitest ··· 222 223 } 223 224 224 225 /** @deprecated */ 225 - initializeGlobalSetup() { 226 + initializeGlobalSetup(): Promise<void> { 226 227 return this._initializeGlobalSetup() 227 228 } 228 229 ··· 299 300 } 300 301 301 302 /** @deprecated use `vitest.reporters` instead */ 302 - get reporters() { 303 + get reporters(): Reporter[] { 303 304 return this.ctx.reporters 304 305 } 305 306 ··· 577 578 } 578 579 579 580 /** @deprecated internal */ 580 - public setServer(options: UserConfig, server: ViteDevServer) { 581 + public setServer(options: UserConfig, server: ViteDevServer): Promise<void> { 581 582 return this._configureServer(options, server) 582 583 } 583 584 ··· 730 731 workspacePath: string | number, 731 732 ctx: Vitest, 732 733 options: InitializeProjectOptions, 733 - ) { 734 + ): Promise<TestProject> { 734 735 const project = new TestProject(workspacePath, ctx, options) 735 736 736 737 const { configFile, ...restOptions } = options
+16 -16
packages/vitest/src/node/reporters/base.ts
··· 37 37 this.isTTY = options.isTTY ?? isTTY 38 38 } 39 39 40 - onInit(ctx: Vitest) { 40 + onInit(ctx: Vitest): void { 41 41 this.ctx = ctx 42 42 43 43 this.ctx.logger.printBanner() 44 44 this.start = performance.now() 45 45 } 46 46 47 - log(...messages: any) { 47 + log(...messages: any): void { 48 48 this.ctx.logger.log(...messages) 49 49 } 50 50 51 - error(...messages: any) { 51 + error(...messages: any): void { 52 52 this.ctx.logger.error(...messages) 53 53 } 54 54 55 - relative(path: string) { 55 + relative(path: string): string { 56 56 return relative(this.ctx.config.root, path) 57 57 } 58 58 59 - onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { 59 + onFinished(files: File[] = this.ctx.state.getFiles(), errors: unknown[] = this.ctx.state.getUnhandledErrors()): void { 60 60 this.end = performance.now() 61 61 if (!files.length && !errors.length) { 62 62 this.ctx.logger.printNoTestFound(this.ctx.filenamePattern) ··· 66 66 } 67 67 } 68 68 69 - onTaskUpdate(packs: TaskResultPack[]) { 69 + onTaskUpdate(packs: TaskResultPack[]): void { 70 70 for (const pack of packs) { 71 71 const task = this.ctx.state.idMap.get(pack[0]) 72 72 ··· 79 79 /** 80 80 * Callback invoked with a single `Task` from `onTaskUpdate` 81 81 */ 82 - protected printTask(task: Task) { 82 + protected printTask(task: Task): void { 83 83 if ( 84 84 !('filepath' in task) 85 85 || !task.result?.state ··· 178 178 return color(` ${Math.round(task.result.duration)}${c.dim('ms')}`) 179 179 } 180 180 181 - onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { 181 + onWatcherStart(files: File[] = this.ctx.state.getFiles(), errors: unknown[] = this.ctx.state.getUnhandledErrors()): void { 182 182 const failed = errors.length > 0 || hasFailed(files) 183 183 184 184 if (failed) { ··· 203 203 this.log(BADGE_PADDING + hints.join(c.dim(', '))) 204 204 } 205 205 206 - onWatcherRerun(files: string[], trigger?: string) { 206 + onWatcherRerun(files: string[], trigger?: string): void { 207 207 this.watchFilters = files 208 208 this.failedUnwatchedFiles = this.ctx.state.getFiles().filter(file => 209 209 !files.includes(file.filepath) && hasFailed(file), ··· 247 247 this.start = performance.now() 248 248 } 249 249 250 - onUserConsoleLog(log: UserConsoleLog) { 250 + onUserConsoleLog(log: UserConsoleLog): void { 251 251 if (!this.shouldLog(log)) { 252 252 return 253 253 } ··· 305 305 write('\n') 306 306 } 307 307 308 - onTestRemoved(trigger?: string) { 308 + onTestRemoved(trigger?: string): void { 309 309 this.log(c.yellow('Test removed...') + (trigger ? c.dim(` [ ${this.relative(trigger)} ]\n`) : '')) 310 310 } 311 311 312 - shouldLog(log: UserConsoleLog) { 312 + shouldLog(log: UserConsoleLog): boolean { 313 313 if (this.ctx.config.silent) { 314 314 return false 315 315 } ··· 320 320 return true 321 321 } 322 322 323 - onServerRestart(reason?: string) { 323 + onServerRestart(reason?: string): void { 324 324 this.log(c.bold(c.magenta( 325 325 reason === 'config' 326 326 ? '\nRestarting due to config changes...' ··· 328 328 ))) 329 329 } 330 330 331 - reportSummary(files: File[], errors: unknown[]) { 331 + reportSummary(files: File[], errors: unknown[]): void { 332 332 this.printErrorsSummary(files, errors) 333 333 334 334 if (this.ctx.config.mode === 'benchmark') { ··· 339 339 } 340 340 } 341 341 342 - reportTestSummary(files: File[], errors: unknown[]) { 342 + reportTestSummary(files: File[], errors: unknown[]): void { 343 343 this.log() 344 344 345 345 const affectedFiles = [ ··· 442 442 } 443 443 } 444 444 445 - reportBenchmarkSummary(files: File[]) { 445 + reportBenchmarkSummary(files: File[]): void { 446 446 const benches = getTests(files) 447 447 const topBenches = benches.filter(i => i.result?.benchmark?.rank === 1) 448 448
+2 -2
packages/vitest/src/node/reporters/basic.ts
··· 9 9 this.isTTY = false 10 10 } 11 11 12 - onInit(ctx: Vitest) { 12 + onInit(ctx: Vitest): void { 13 13 super.onInit(ctx) 14 14 15 15 ctx.logger.log(c.inverse(c.bold(c.yellow(' DEPRECATED '))), c.yellow( ··· 19 19 )) 20 20 } 21 21 22 - reportSummary(files: File[], errors: unknown[]) { 22 + reportSummary(files: File[], errors: unknown[]): void { 23 23 // non-tty mode doesn't add a new line 24 24 this.ctx.logger.log() 25 25 return super.reportSummary(files, errors)
+4 -1
packages/vitest/src/node/reporters/benchmark/index.ts
··· 6 6 VerboseBenchmarkReporter, 7 7 } 8 8 9 - export const BenchmarkReportsMap = { 9 + export const BenchmarkReportsMap: { 10 + default: typeof BenchmarkReporter 11 + verbose: typeof VerboseBenchmarkReporter 12 + } = { 10 13 default: BenchmarkReporter, 11 14 verbose: VerboseBenchmarkReporter, 12 15 }
+2 -2
packages/vitest/src/node/reporters/benchmark/json-formatter.ts
··· 18 18 id: string 19 19 } 20 20 21 - export function createBenchmarkJsonReport(files: File[]) { 21 + export function createBenchmarkJsonReport(files: File[]): Report { 22 22 const report: Report = { files: [] } 23 23 24 24 for (const file of files) { ··· 54 54 return report 55 55 } 56 56 57 - export function flattenFormattedBenchmarkReport(report: Report) { 57 + export function flattenFormattedBenchmarkReport(report: Report): Record<string, FormattedBenchmarkResult> { 58 58 const flat: Record<FormattedBenchmarkResult['id'], FormattedBenchmarkResult> = {} 59 59 60 60 for (const file of report.files) {
+4 -4
packages/vitest/src/node/reporters/benchmark/reporter.ts
··· 1 - import type { Task, TaskResultPack } from '@vitest/runner' 1 + import type { File, Task, TaskResultPack } from '@vitest/runner' 2 2 import type { Vitest } from '../../core' 3 3 import fs from 'node:fs' 4 4 import { getFullName } from '@vitest/runner/utils' ··· 12 12 export class BenchmarkReporter extends DefaultReporter { 13 13 compare?: Parameters<typeof renderTable>[0]['compare'] 14 14 15 - async onInit(ctx: Vitest) { 15 + async onInit(ctx: Vitest): Promise<void> { 16 16 super.onInit(ctx) 17 17 18 18 if (this.ctx.config.benchmark?.compare) { ··· 47 47 super.onTaskUpdate(packs) 48 48 } 49 49 50 - printTask(task: Task) { 50 + printTask(task: Task): void { 51 51 if (task?.type !== 'suite' || !task.result?.state || task.result?.state === 'run' || task.result?.state === 'queued') { 52 52 return 53 53 } ··· 75 75 } 76 76 } 77 77 78 - async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { 78 + async onFinished(files: File[] = this.ctx.state.getFiles(), errors: unknown[] = this.ctx.state.getUnhandledErrors()): Promise<void> { 79 79 super.onFinished(files, errors) 80 80 81 81 // write output for future comparison
+2 -2
packages/vitest/src/node/reporters/blob.ts
··· 32 32 files: File[] = [], 33 33 errors: unknown[] = [], 34 34 coverage: unknown, 35 - ) { 35 + ): Promise<void> { 36 36 let outputFile 37 37 = this.options.outputFile ?? getOutputFile(this.ctx.config, 'blob') 38 38 if (!outputFile) { ··· 80 80 currentVersion: string, 81 81 blobsDirectory: string, 82 82 projectsArray: TestProject[], 83 - ) { 83 + ): Promise<{ files: File[]; errors: unknown[]; coverages: unknown[] }> { 84 84 // using process.cwd() because --merge-reports can only be used in CLI 85 85 const resolvedDir = resolve(process.cwd(), blobsDirectory) 86 86 const blobsFiles = await readdir(resolvedDir)
+11 -11
packages/vitest/src/node/reporters/default.ts
··· 29 29 } 30 30 } 31 31 32 - onTestRunStart(specifications: ReadonlyArray<TestSpecification>) { 32 + onTestRunStart(specifications: ReadonlyArray<TestSpecification>): void { 33 33 this.summary?.onTestRunStart(specifications) 34 34 } 35 35 36 - onTestModuleQueued(file: TestModule) { 36 + onTestModuleQueued(file: TestModule): void { 37 37 this.summary?.onTestModuleQueued(file) 38 38 } 39 39 40 - onTestModuleCollected(module: TestModule) { 40 + onTestModuleCollected(module: TestModule): void { 41 41 this.summary?.onTestModuleCollected(module) 42 42 } 43 43 44 - onTestModuleEnd(module: TestModule) { 44 + onTestModuleEnd(module: TestModule): void { 45 45 this.summary?.onTestModuleEnd(module) 46 46 } 47 47 48 - onTestCaseReady(test: TestCase) { 48 + onTestCaseReady(test: TestCase): void { 49 49 this.summary?.onTestCaseReady(test) 50 50 } 51 51 52 - onTestCaseResult(test: TestCase) { 52 + onTestCaseResult(test: TestCase): void { 53 53 this.summary?.onTestCaseResult(test) 54 54 } 55 55 56 - onHookStart(hook: ReportedHookContext) { 56 + onHookStart(hook: ReportedHookContext): void { 57 57 this.summary?.onHookStart(hook) 58 58 } 59 59 60 - onHookEnd(hook: ReportedHookContext) { 60 + onHookEnd(hook: ReportedHookContext): void { 61 61 this.summary?.onHookEnd(hook) 62 62 } 63 63 64 - onInit(ctx: Vitest) { 64 + onInit(ctx: Vitest): void { 65 65 super.onInit(ctx) 66 66 this.summary?.onInit(ctx, { verbose: this.verbose }) 67 67 } 68 68 69 - onPathsCollected(paths: string[] = []) { 69 + onPathsCollected(paths: string[] = []): void { 70 70 if (this.isTTY) { 71 71 if (this.renderSucceed === undefined) { 72 72 this.renderSucceed = !!this.renderSucceed ··· 78 78 } 79 79 } 80 80 81 - onTestRunEnd() { 81 + onTestRunEnd(): void { 82 82 this.summary?.onTestRunEnd() 83 83 } 84 84 }
+7 -7
packages/vitest/src/node/reporters/dot.ts
··· 17 17 private tests = new Map<Test['id'], TestCaseState>() 18 18 private finishedTests = new Set<TestCase['id']>() 19 19 20 - onInit(ctx: Vitest) { 20 + onInit(ctx: Vitest): void { 21 21 super.onInit(ctx) 22 22 23 23 if (this.isTTY) { ··· 30 30 } 31 31 } 32 32 33 - printTask(task: Task) { 33 + printTask(task: Task): void { 34 34 if (!this.isTTY) { 35 35 super.printTask(task) 36 36 } 37 37 } 38 38 39 - onWatcherRerun(files: string[], trigger?: string) { 39 + onWatcherRerun(files: string[], trigger?: string): void { 40 40 this.tests.clear() 41 41 this.renderer?.start() 42 42 super.onWatcherRerun(files, trigger) 43 43 } 44 44 45 - onFinished(files?: File[], errors?: unknown[]) { 45 + onFinished(files?: File[], errors?: unknown[]): void { 46 46 if (this.isTTY) { 47 47 const finalLog = formatTests(Array.from(this.tests.values())) 48 48 this.ctx.logger.log(finalLog) ··· 61 61 } 62 62 } 63 63 64 - onTestCaseReady(test: TestCase) { 64 + onTestCaseReady(test: TestCase): void { 65 65 if (this.finishedTests.has(test.id)) { 66 66 return 67 67 } ··· 69 69 this.renderer?.schedule() 70 70 } 71 71 72 - onTestCaseResult(test: TestCase) { 72 + onTestCaseResult(test: TestCase): void { 73 73 this.finishedTests.add(test.id) 74 74 this.tests.set(test.id, test.result().state || 'skipped') 75 75 this.renderer?.schedule() 76 76 } 77 77 78 - onTestModuleEnd() { 78 + onTestModuleEnd(): void { 79 79 if (!this.isTTY) { 80 80 return 81 81 }
+2 -2
packages/vitest/src/node/reporters/github-actions.ts
··· 9 9 export class GithubActionsReporter implements Reporter { 10 10 ctx: Vitest = undefined! 11 11 12 - onInit(ctx: Vitest) { 12 + onInit(ctx: Vitest): void { 13 13 this.ctx = ctx 14 14 } 15 15 16 - onFinished(files: File[] = [], errors: unknown[] = []) { 16 + onFinished(files: File[] = [], errors: unknown[] = []): void { 17 17 // collect all errors and associate them with projects 18 18 const projectErrors = new Array<{ 19 19 project: TestProject
+1 -1
packages/vitest/src/node/reporters/hanging-process.ts
··· 9 9 this.whyRunning = _require('why-is-node-running') 10 10 } 11 11 12 - onProcessTimeout() { 12 + onProcessTimeout(): void { 13 13 this.whyRunning?.() 14 14 } 15 15 }
+11 -11
packages/vitest/src/node/reporters/index.ts
··· 42 42 } from './json' 43 43 44 44 export const ReportersMap = { 45 - 'default': DefaultReporter, 46 - 'basic': BasicReporter, 47 - 'blob': BlobReporter, 48 - 'verbose': VerboseReporter, 49 - 'dot': DotReporter, 50 - 'json': JsonReporter, 51 - 'tap': TapReporter, 52 - 'tap-flat': TapFlatReporter, 53 - 'junit': JUnitReporter, 54 - 'hanging-process': HangingProcessReporter, 55 - 'github-actions': GithubActionsReporter, 45 + 'default': DefaultReporter as typeof DefaultReporter, 46 + 'basic': BasicReporter as typeof BasicReporter, 47 + 'blob': BlobReporter as typeof BlobReporter, 48 + 'verbose': VerboseReporter as typeof VerboseReporter, 49 + 'dot': DotReporter as typeof DotReporter, 50 + 'json': JsonReporter as typeof JsonReporter, 51 + 'tap': TapReporter as typeof TapReporter, 52 + 'tap-flat': TapFlatReporter as typeof TapFlatReporter, 53 + 'junit': JUnitReporter as typeof JUnitReporter, 54 + 'hanging-process': HangingProcessReporter as typeof HangingProcessReporter, 55 + 'github-actions': GithubActionsReporter as typeof GithubActionsReporter, 56 56 } 57 57 58 58 export type BuiltinReporters = keyof typeof ReportersMap
+3 -3
packages/vitest/src/node/reporters/json.ts
··· 88 88 this.start = Date.now() 89 89 } 90 90 91 - protected async logTasks(files: File[], coverageMap?: CoverageMap | null) { 91 + protected async logTasks(files: File[], coverageMap?: CoverageMap | null): Promise<void> { 92 92 const suites = getSuites(files) 93 93 const numTotalTestSuites = suites.length 94 94 const tests = getTests(files) ··· 196 196 await this.writeReport(JSON.stringify(result)) 197 197 } 198 198 199 - async onFinished(files = this.ctx.state.getFiles(), _errors: unknown[] = [], coverageMap?: unknown) { 199 + async onFinished(files: File[] = this.ctx.state.getFiles(), _errors: unknown[] = [], coverageMap?: unknown): Promise<void> { 200 200 await this.logTasks(files, coverageMap as CoverageMap) 201 201 } 202 202 ··· 205 205 * or logs it to the console otherwise. 206 206 * @param report 207 207 */ 208 - async writeReport(report: string) { 208 + async writeReport(report: string): Promise<void> { 209 209 const outputFile 210 210 = this.options.outputFile ?? getOutputFile(this.ctx.config, 'json') 211 211
+3 -3
packages/vitest/src/node/reporters/junit.ts
··· 1 - import type { Task } from '@vitest/runner' 1 + import type { File, Task } from '@vitest/runner' 2 2 import type { Vitest } from '../core' 3 3 import type { Reporter } from '../types/reporter' 4 4 import { existsSync, promises as fs } from 'node:fs' ··· 164 164 name: string, 165 165 attrs: Record<string, any>, 166 166 children: () => Promise<void>, 167 - ) { 167 + ): Promise<void> { 168 168 const pairs: string[] = [] 169 169 for (const key in attrs) { 170 170 const attr = attrs[key] ··· 274 274 } 275 275 } 276 276 277 - async onFinished(files = this.ctx.state.getFiles()) { 277 + async onFinished(files: File[] = this.ctx.state.getFiles()): Promise<void> { 278 278 await this.logger.log('<?xml version="1.0" encoding="UTF-8" ?>') 279 279 280 280 const transformed = files.map((file) => {
+2 -2
packages/vitest/src/node/reporters/renderers/indented-logger.ts
··· 3 3 4 4 constructor(private baseLog: (text: string) => T) {} 5 5 6 - indent() { 6 + indent(): void { 7 7 this.currentIndent += ' ' 8 8 } 9 9 10 - unindent() { 10 + unindent(): void { 11 11 this.currentIndent = this.currentIndent.substring( 12 12 0, 13 13 this.currentIndent.length - 4,
+18 -18
packages/vitest/src/node/reporters/renderers/utils.ts
··· 14 14 F_POINTER, 15 15 } from './figures' 16 16 17 - export const pointer = c.yellow(F_POINTER) 18 - export const skipped = c.dim(c.gray(F_DOWN)) 19 - export const benchmarkPass = c.green(F_DOT) 20 - export const testPass = c.green(F_CHECK) 21 - export const taskFail = c.red(F_CROSS) 22 - export const suiteFail = c.red(F_POINTER) 23 - export const pending = c.gray('·') 17 + export const pointer: string = c.yellow(F_POINTER) 18 + export const skipped: string = c.dim(c.gray(F_DOWN)) 19 + export const benchmarkPass: string = c.green(F_DOT) 20 + export const testPass: string = c.green(F_CHECK) 21 + export const taskFail: string = c.red(F_CROSS) 22 + export const suiteFail: string = c.red(F_POINTER) 23 + export const pending: string = c.gray('·') 24 24 25 25 function getCols(delta = 0) { 26 26 let length = process.stdout?.columns ··· 30 30 return Math.max(length + delta, 0) 31 31 } 32 32 33 - export function divider(text?: string, left?: number, right?: number) { 33 + export function divider(text?: string, left?: number, right?: number): string { 34 34 const cols = getCols() 35 35 36 36 if (text) { ··· 49 49 return F_LONG_DASH.repeat(cols) 50 50 } 51 51 52 - export function formatTestPath(root: string, path: string) { 52 + export function formatTestPath(root: string, path: string): string { 53 53 if (isAbsolute(path)) { 54 54 path = relative(root, path) 55 55 } ··· 64 64 export function renderSnapshotSummary( 65 65 rootDir: string, 66 66 snapshots: SnapshotSummary, 67 - ) { 67 + ): string[] { 68 68 const summary: string[] = [] 69 69 70 70 if (snapshots.added) { ··· 121 121 return summary 122 122 } 123 123 124 - export function countTestErrors(tasks: Task[]) { 124 + export function countTestErrors(tasks: Task[]): number { 125 125 return tasks.reduce((c, i) => c + (i.result?.errors?.length || 0), 0) 126 126 } 127 127 ··· 129 129 tasks: Task[], 130 130 name = 'tests', 131 131 showTotal = true, 132 - ) { 132 + ): string { 133 133 if (tasks.length === 0) { 134 134 return c.dim(`no ${name}`) 135 135 } ··· 151 151 ) 152 152 } 153 153 154 - export function getStateSymbol(task: Task) { 154 + export function getStateSymbol(task: Task): string { 155 155 if (task.mode === 'skip' || task.mode === 'todo') { 156 156 return skipped 157 157 } ··· 177 177 return ' ' 178 178 } 179 179 180 - export function duration(time: number, locale = 'en-us') { 180 + export function duration(time: number, locale = 'en-us'): string { 181 181 if (time < 1) { 182 182 return `${Number((time * 1e3).toFixed(2)).toLocaleString(locale)} ps` 183 183 } ··· 201 201 return `${Number((time / 36e11).toFixed(2)).toLocaleString(locale)} h` 202 202 } 203 203 204 - export function formatTimeString(date: Date) { 204 + export function formatTimeString(date: Date): string { 205 205 return date.toTimeString().split(' ')[0] 206 206 } 207 207 208 - export function formatTime(time: number) { 208 + export function formatTime(time: number): string { 209 209 if (time > 1000) { 210 210 return `${(time / 1000).toFixed(2)}s` 211 211 } 212 212 return `${Math.round(time)}ms` 213 213 } 214 214 215 - export function formatProjectName(name: string | undefined, suffix = ' ') { 215 + export function formatProjectName(name: string | undefined, suffix = ' '): string { 216 216 if (!name) { 217 217 return '' 218 218 } ··· 232 232 return `${c.bold(c.inverse(c[color](` ${label} `)))} ${message ? c[color](message) : ''}` 233 233 } 234 234 235 - export function padSummaryTitle(str: string) { 235 + export function padSummaryTitle(str: string): string { 236 236 return c.dim(`${str.padStart(11)} `) 237 237 } 238 238
+4 -4
packages/vitest/src/node/reporters/renderers/windowedRenderer.ts
··· 58 58 this.start() 59 59 } 60 60 61 - start() { 61 + start(): void { 62 62 this.finished = false 63 63 this.renderInterval = setInterval(() => this.schedule(), this.options.interval).unref() 64 64 } 65 65 66 - stop() { 66 + stop(): void { 67 67 this.cleanups.splice(0).map(fn => fn()) 68 68 clearInterval(this.renderInterval) 69 69 } ··· 72 72 * Write all buffered output and stop buffering. 73 73 * All intercepted writes are forwarded to actual write after this. 74 74 */ 75 - finish() { 75 + finish(): void { 76 76 this.finished = true 77 77 this.flushBuffer() 78 78 clearInterval(this.renderInterval) ··· 81 81 /** 82 82 * Queue new render update 83 83 */ 84 - schedule() { 84 + schedule(): void { 85 85 if (!this.renderScheduled) { 86 86 this.renderScheduled = true 87 87 this.flushBuffer()
+10 -10
packages/vitest/src/node/reporters/summary.ts
··· 63 63 private duration = 0 64 64 private durationInterval: NodeJS.Timeout | undefined = undefined 65 65 66 - onInit(ctx: Vitest, options: Options = {}) { 66 + onInit(ctx: Vitest, options: Options = {}): void { 67 67 this.ctx = ctx 68 68 69 69 this.options = { ··· 82 82 }) 83 83 } 84 84 85 - onTestRunStart(specifications: ReadonlyArray<TestSpecification>) { 85 + onTestRunStart(specifications: ReadonlyArray<TestSpecification>): void { 86 86 this.runningModules.clear() 87 87 this.finishedModules.clear() 88 88 this.modules = emptyCounters() ··· 94 94 this.modules.total = specifications.length 95 95 } 96 96 97 - onTestRunEnd() { 97 + onTestRunEnd(): void { 98 98 this.runningModules.clear() 99 99 this.finishedModules.clear() 100 100 this.renderer.finish() 101 101 clearInterval(this.durationInterval) 102 102 } 103 103 104 - onTestModuleQueued(module: TestModule) { 104 + onTestModuleQueued(module: TestModule): void { 105 105 // When new test module starts, take the place of previously finished test module, if any 106 106 if (this.finishedModules.size) { 107 107 const finished = this.finishedModules.keys().next().value ··· 112 112 this.renderer.schedule() 113 113 } 114 114 115 - onTestModuleCollected(module: TestModule) { 115 + onTestModuleCollected(module: TestModule): void { 116 116 let stats = this.runningModules.get(module.id) 117 117 118 118 if (!stats) { ··· 128 128 this.renderer.schedule() 129 129 } 130 130 131 - onHookStart(options: ReportedHookContext) { 131 + onHookStart(options: ReportedHookContext): void { 132 132 const stats = this.getHookStats(options) 133 133 134 134 if (!stats) { ··· 151 151 hook.onFinish = () => clearTimeout(timeout) 152 152 } 153 153 154 - onHookEnd(options: ReportedHookContext) { 154 + onHookEnd(options: ReportedHookContext): void { 155 155 const stats = this.getHookStats(options) 156 156 157 157 if (stats?.hook?.name !== options.name) { ··· 162 162 stats.hook.visible = false 163 163 } 164 164 165 - onTestCaseReady(test: TestCase) { 165 + onTestCaseReady(test: TestCase): void { 166 166 // Track slow running tests only on verbose mode 167 167 if (!this.options.verbose) { 168 168 return ··· 193 193 stats.tests.set(test.id, slowTest) 194 194 } 195 195 196 - onTestCaseResult(test: TestCase) { 196 + onTestCaseResult(test: TestCase): void { 197 197 const stats = this.runningModules.get(test.module.id) 198 198 199 199 if (!stats) { ··· 219 219 this.renderer.schedule() 220 220 } 221 221 222 - onTestModuleEnd(module: TestModule) { 222 + onTestModuleEnd(module: TestModule): void { 223 223 const state = module.state() 224 224 this.modules.completed++ 225 225
+2 -2
packages/vitest/src/node/reporters/tap-flat.ts
··· 1 - import type { Task } from '@vitest/runner' 1 + import type { File, Task } from '@vitest/runner' 2 2 import type { Vitest } from '../core' 3 3 import { TapReporter } from './tap' 4 4 ··· 25 25 super.onInit(ctx) 26 26 } 27 27 28 - onFinished(files = this.ctx.state.getFiles()) { 28 + onFinished(files: File[] = this.ctx.state.getFiles()): void { 29 29 this.ctx.logger.log('TAP version 13') 30 30 31 31 const flatTasks = files.flatMap(task => flattenTasks(task))
+3 -3
packages/vitest/src/node/reporters/tap.ts
··· 1 - import type { Task } from '@vitest/runner' 1 + import type { File, Task } from '@vitest/runner' 2 2 import type { ErrorWithDiff, ParsedStack } from '@vitest/utils' 3 3 import type { Vitest } from '../core' 4 4 import type { Reporter } from '../types/reporter' ··· 53 53 } 54 54 } 55 55 56 - protected logTasks(tasks: Task[]) { 56 + protected logTasks(tasks: Task[]): void { 57 57 this.logger.log(`1..${tasks.length}`) 58 58 59 59 for (const [i, task] of tasks.entries()) { ··· 121 121 } 122 122 } 123 123 124 - onFinished(files = this.ctx.state.getFiles()) { 124 + onFinished(files: File[] = this.ctx.state.getFiles()): void { 125 125 this.logger.log('TAP version 13') 126 126 127 127 this.logTasks(files)
+4 -3
packages/vitest/src/node/reporters/utils.ts
··· 2 2 import type { Vitest } from '../core' 3 3 import type { ResolvedConfig } from '../types/config' 4 4 import type { Reporter } from '../types/reporter' 5 - import type { BenchmarkBuiltinReporters, BuiltinReporters } from './index' 5 + import type { BlobReporter } from './blob' 6 + import type { BasicReporter, BenchmarkBuiltinReporters, BenchmarkReporter, BuiltinReporters, DefaultReporter, DotReporter, GithubActionsReporter, HangingProcessReporter, JsonReporter, JUnitReporter, TapReporter } from './index' 6 7 import { BenchmarkReportsMap, ReportersMap } from './index' 7 8 8 9 async function loadCustomReporterModule<C extends Reporter>( ··· 34 35 function createReporters( 35 36 reporterReferences: ResolvedConfig['reporters'], 36 37 ctx: Vitest, 37 - ) { 38 + ): Promise<Array<Reporter | DefaultReporter | BasicReporter | BlobReporter | DotReporter | JsonReporter | TapReporter | JUnitReporter | HangingProcessReporter | GithubActionsReporter>> { 38 39 const runner = ctx.runner 39 40 const promisedReporters = reporterReferences.map( 40 41 async (referenceOrInstance) => { ··· 72 73 function createBenchmarkReporters( 73 74 reporterReferences: Array<string | Reporter | BenchmarkBuiltinReporters>, 74 75 runner: ViteNodeRunner, 75 - ) { 76 + ): Promise<(Reporter | BenchmarkReporter)[]> { 76 77 const promisedReporters = reporterReferences.map( 77 78 async (referenceOrInstance) => { 78 79 if (typeof referenceOrInstance === 'string') {
+1 -1
packages/vitest/src/node/sequencers/RandomSequencer.ts
··· 3 3 import { BaseSequencer } from './BaseSequencer' 4 4 5 5 export class RandomSequencer extends BaseSequencer { 6 - public async sort(files: TestSpecification[]) { 6 + public async sort(files: TestSpecification[]): Promise<TestSpecification[]> { 7 7 const { sequence } = this.ctx.config 8 8 9 9 return shuffle(files, sequence.seed)
+1 -1
packages/vitest/src/node/spec.ts
··· 93 93 * for backwards compatibility 94 94 * @deprecated 95 95 */ 96 - *[Symbol.iterator]() { 96 + *[Symbol.iterator](): Generator<string | TestProject, void, unknown> { 97 97 yield this.project 98 98 yield this.moduleId 99 99 yield this.pool
+1 -1
packages/vitest/src/node/specifications.ts
··· 38 38 ) 39 39 } 40 40 41 - public async globTestSpecifications(filters: string[] = []) { 41 + public async globTestSpecifications(filters: string[] = []): Promise<TestSpecification[]> { 42 42 const files: TestSpecification[] = [] 43 43 const dir = process.cwd() 44 44 const parsedFilters = filters.map(f => parseFilter(f))
+21 -21
packages/vitest/src/node/state.ts
··· 13 13 } 14 14 15 15 export class StateManager { 16 - filesMap = new Map<string, File[]>() 16 + filesMap: Map<string, File[]> = new Map() 17 17 pathsSet: Set<string> = new Set() 18 - idMap = new Map<string, Task>() 19 - taskFileMap = new WeakMap<Task, File>() 20 - errorsSet = new Set<unknown>() 21 - processTimeoutCauses = new Set<string>() 22 - reportedTasksMap = new WeakMap<Task, TestCase | TestSuite | TestModule>() 18 + idMap: Map<string, Task> = new Map() 19 + taskFileMap: WeakMap<Task, File> = new WeakMap() 20 + errorsSet: Set<unknown> = new Set() 21 + processTimeoutCauses: Set<string> = new Set() 22 + reportedTasksMap: WeakMap<Task, TestModule | TestCase | TestSuite> = new WeakMap() 23 23 24 24 catchError(err: unknown, type: string): void { 25 25 if (isAggregateError(err)) { ··· 48 48 this.errorsSet.add(err) 49 49 } 50 50 51 - clearErrors() { 51 + clearErrors(): void { 52 52 this.errorsSet.clear() 53 53 } 54 54 55 - getUnhandledErrors() { 55 + getUnhandledErrors(): unknown[] { 56 56 return Array.from(this.errorsSet.values()) 57 57 } 58 58 59 - addProcessTimeoutCause(cause: string) { 59 + addProcessTimeoutCause(cause: string): void { 60 60 this.processTimeoutCauses.add(cause) 61 61 } 62 62 63 - getProcessTimeoutCauses() { 63 + getProcessTimeoutCauses(): string[] { 64 64 return Array.from(this.processTimeoutCauses.values()) 65 65 } 66 66 67 - getPaths() { 67 + getPaths(): string[] { 68 68 return Array.from(this.pathsSet) 69 69 } 70 70 ··· 98 98 return Array.from(this.filesMap.keys()) 99 99 } 100 100 101 - getFailedFilepaths() { 101 + getFailedFilepaths(): string[] { 102 102 return this.getFiles() 103 103 .filter(i => i.result?.state === 'fail') 104 104 .map(i => i.filepath) 105 105 } 106 106 107 - collectPaths(paths: string[] = []) { 107 + collectPaths(paths: string[] = []): void { 108 108 paths.forEach((path) => { 109 109 this.pathsSet.add(path) 110 110 }) 111 111 } 112 112 113 - collectFiles(project: TestProject, files: File[] = []) { 113 + collectFiles(project: TestProject, files: File[] = []): void { 114 114 files.forEach((file) => { 115 115 const existing = this.filesMap.get(file.filepath) || [] 116 116 const otherFiles = existing.filter( ··· 133 133 clearFiles( 134 134 project: TestProject, 135 135 paths: string[] = [], 136 - ) { 136 + ): void { 137 137 paths.forEach((path) => { 138 138 const files = this.filesMap.get(path) 139 139 const fileTask = createFileTask( ··· 161 161 }) 162 162 } 163 163 164 - updateId(task: Task, project: TestProject) { 164 + updateId(task: Task, project: TestProject): void { 165 165 if (this.idMap.get(task.id) === task) { 166 166 return 167 167 } ··· 184 184 } 185 185 } 186 186 187 - getReportedEntity(task: Task) { 187 + getReportedEntity(task: Task): TestModule | TestCase | TestSuite | undefined { 188 188 return this.reportedTasksMap.get(task) 189 189 } 190 190 191 - updateTasks(packs: TaskResultPack[]) { 191 + updateTasks(packs: TaskResultPack[]): void { 192 192 for (const [id, result, meta] of packs) { 193 193 const task = this.idMap.get(id) 194 194 if (task) { ··· 202 202 } 203 203 } 204 204 205 - updateUserLog(log: UserConsoleLog) { 205 + updateUserLog(log: UserConsoleLog): void { 206 206 const task = log.taskId && this.idMap.get(log.taskId) 207 207 if (task) { 208 208 if (!task.logs) { ··· 212 212 } 213 213 } 214 214 215 - getCountOfFailedTests() { 215 + getCountOfFailedTests(): number { 216 216 return Array.from(this.idMap.values()).filter( 217 217 t => t.result?.state === 'fail', 218 218 ).length 219 219 } 220 220 221 - cancelFiles(files: string[], project: TestProject) { 221 + cancelFiles(files: string[], project: TestProject): void { 222 222 this.collectFiles( 223 223 project, 224 224 files.map(filepath =>
+3 -3
packages/vitest/src/node/stdin.ts
··· 22 22 ] 23 23 const cancelKeys = ['space', 'c', 'h', ...keys.map(key => key[0]).flat()] 24 24 25 - export function printShortcutsHelp() { 25 + export function printShortcutsHelp(): void { 26 26 stdout().write( 27 27 ` 28 28 ${c.bold(' Watch Usage')} ··· 40 40 41 41 export function registerConsoleShortcuts( 42 42 ctx: Vitest, 43 - stdin: NodeJS.ReadStream = process.stdin, 43 + stdin: NodeJS.ReadStream | undefined = process.stdin, 44 44 stdout: NodeJS.WriteStream | Writable, 45 45 ) { 46 46 let latestFilename = '' ··· 241 241 242 242 on() 243 243 244 - return function cleanup() { 244 + return function cleanup(): void { 245 245 off() 246 246 } 247 247 }
+6 -6
packages/vitest/src/node/test-run.ts
··· 11 11 export class TestRun { 12 12 constructor(private vitest: Vitest) {} 13 13 14 - async start(specifications: TestSpecification[]) { 14 + async start(specifications: TestSpecification[]): Promise<void> { 15 15 const filepaths = specifications.map(spec => spec.moduleId) 16 16 this.vitest.state.collectPaths(filepaths) 17 17 ··· 20 20 await this.vitest.report('onTestRunStart', [...specifications]) 21 21 } 22 22 23 - async enqueued(project: TestProject, file: RunnerTestFile) { 23 + async enqueued(project: TestProject, file: RunnerTestFile): Promise<void> { 24 24 this.vitest.state.collectFiles(project, [file]) 25 25 const testModule = this.vitest.state.getReportedEntity(file) as TestModule 26 26 await this.vitest.report('onTestModuleQueued', testModule) 27 27 } 28 28 29 - async collected(project: TestProject, files: RunnerTestFile[]) { 29 + async collected(project: TestProject, files: RunnerTestFile[]): Promise<void> { 30 30 this.vitest.state.collectFiles(project, files) 31 31 await Promise.all([ 32 32 this.vitest.report('onCollected', files), ··· 37 37 ]) 38 38 } 39 39 40 - async log(log: UserConsoleLog) { 40 + async log(log: UserConsoleLog): Promise<void> { 41 41 this.vitest.state.updateUserLog(log) 42 42 await this.vitest.report('onUserConsoleLog', log) 43 43 } 44 44 45 - async updated(update: TaskResultPack[], events: TaskEventPack[]) { 45 + async updated(update: TaskResultPack[], events: TaskEventPack[]): Promise<void> { 46 46 this.vitest.state.updateTasks(update) 47 47 48 48 // TODO: what is the order or reports here? ··· 57 57 } 58 58 } 59 59 60 - async end(specifications: TestSpecification[], errors: unknown[], coverage?: unknown) { 60 + async end(specifications: TestSpecification[], errors: unknown[], coverage?: unknown): Promise<void> { 61 61 // specification won't have the File task if they were filtered by the --shard command 62 62 const modules = specifications.map(spec => spec.testModule).filter(s => s != null) 63 63 const files = modules.map(m => m.task)
+2 -2
packages/vitest/src/node/vite.ts
··· 1 - import type { InlineConfig } from 'vite' 1 + import type { InlineConfig, ViteDevServer } from 'vite' 2 2 import { createServer } from 'vite' 3 3 4 - export async function createViteServer(inlineConfig: InlineConfig) { 4 + export async function createViteServer(inlineConfig: InlineConfig): Promise<ViteDevServer> { 5 5 // Vite prints an error (https://github.com/vitejs/vite/issues/14328) 6 6 // But Vitest works correctly either way 7 7 const error = console.error
+1 -1
packages/vitest/src/node/watch-filter.ts
··· 229 229 this.stdout.write(data) 230 230 } 231 231 232 - public getLastResults() { 232 + public getLastResults(): string[] { 233 233 return this.results 234 234 } 235 235 }
+1 -1
packages/vitest/src/node/workspace/resolveWorkspace.ts
··· 170 170 vitest: Vitest, 171 171 names: Set<string>, 172 172 resolvedProjects: TestProject[], 173 - ) { 173 + ): Promise<TestProject[]> { 174 174 const removeProjects = new Set<TestProject>() 175 175 176 176 resolvedProjects.forEach((project) => {
+2 -2
packages/vitest/src/paths.ts
··· 1 1 import { resolve } from 'node:path' 2 2 import url from 'node:url' 3 3 4 - export const rootDir = resolve(url.fileURLToPath(import.meta.url), '../../') 5 - export const distDir = resolve( 4 + export const rootDir: string = resolve(url.fileURLToPath(import.meta.url), '../../') 5 + export const distDir: string = resolve( 6 6 url.fileURLToPath(import.meta.url), 7 7 '../../dist', 8 8 )
+4 -4
packages/vitest/src/public/node.ts
··· 3 3 import { Vitest } from '../node/core' 4 4 import { TestModule as _TestFile } from '../node/reporters/reported-tasks' 5 5 6 - export const version = Vitest.version 6 + export const version: string = Vitest.version 7 7 8 8 export { isValidApiRequest } from '../api/check' 9 9 export { parseCLI } from '../node/cli/cac' ··· 80 80 ResolvedBrowserOptions, 81 81 } from '../node/types/browser' 82 82 /** @deprecated use `createViteServer` instead */ 83 - export const createServer = _createServer 84 - export const createViteServer = _createServer 83 + export const createServer: typeof _createServer = _createServer 84 + export const createViteServer: typeof _createServer = _createServer 85 85 export type { 86 86 ApiConfig, 87 87 BuiltinEnvironment, ··· 125 125 /** 126 126 * @deprecated Use `TestModule` instead 127 127 */ 128 - export const TestFile = _TestFile 128 + export const TestFile: typeof _TestFile = _TestFile 129 129 export type { WorkerContext } from '../node/types/worker' 130 130 export { createViteLogger } from '../node/viteLogger' 131 131
+1 -1
packages/vitest/src/runtime/benchmark.ts
··· 16 16 return benchFns.get(key)! 17 17 } 18 18 19 - export const bench = createBenchmark(function ( 19 + export const bench: BenchmarkAPI = createBenchmark(function ( 20 20 name, 21 21 fn: BenchFunction = noop, 22 22 options: BenchOptions = {},
+1 -1
packages/vitest/src/runtime/console.ts
··· 32 32 return UNKNOWN_TEST_ID 33 33 } 34 34 35 - export function createCustomConsole(defaultState?: WorkerGlobalState) { 35 + export function createCustomConsole(defaultState?: WorkerGlobalState): Console { 36 36 const stdoutBuffer = new Map<string, any[]>() 37 37 const stderrBuffer = new Map<string, any[]>() 38 38 const timers = new Map<
+17 -10
packages/vitest/src/runtime/execute.ts
··· 1 1 import type { ViteNodeRunnerOptions } from 'vite-node' 2 - import type { ModuleCacheMap } from 'vite-node/client' 2 + import type { ModuleCacheMap, ModuleExecutionInfo } from 'vite-node/client' 3 3 import type { WorkerGlobalState } from '../types/worker' 4 4 import type { ExternalModulesExecutor } from './external-executor' 5 5 import fs from 'node:fs' ··· 28 28 externalModulesExecutor?: ExternalModulesExecutor 29 29 } 30 30 31 - export async function createVitestExecutor(options: ExecuteOptions) { 31 + export async function createVitestExecutor(options: ExecuteOptions): Promise<VitestExecutor> { 32 32 const runner = new VitestExecutor(options) 33 33 34 34 await runner.executeId('/@vite/env') ··· 91 91 }) 92 92 } 93 93 94 - export async function startVitestExecutor(options: ContextExecutorOptions) { 94 + export async function startVitestExecutor(options: ContextExecutorOptions): Promise<VitestExecutor> { 95 95 const state = (): WorkerGlobalState => 96 96 // @ts-expect-error injected untyped global 97 97 globalThis.__vitest_worker__ || options.state ··· 186 186 } 187 187 } 188 188 189 - export function getDefaultRequestStubs(context?: vm.Context) { 189 + export function getDefaultRequestStubs(context?: vm.Context): { 190 + '/@vite/client': any 191 + '@vite/client': any 192 + } { 190 193 if (!context) { 191 194 const clientStub = { 192 195 ...DEFAULT_REQUEST_STUBS['@vite/client'], ··· 249 252 } 250 253 } 251 254 252 - protected getContextPrimitives() { 255 + protected getContextPrimitives(): { 256 + Object: typeof Object 257 + Reflect: typeof Reflect 258 + Symbol: typeof Symbol 259 + } { 253 260 return this.primitives 254 261 } 255 262 ··· 258 265 return globalThis.__vitest_worker__ || this.options.state 259 266 } 260 267 261 - get moduleExecutionInfo() { 268 + get moduleExecutionInfo(): ModuleExecutionInfo | undefined { 262 269 return this.options.moduleExecutionInfo 263 270 } 264 271 ··· 274 281 : !id.startsWith('node:') 275 282 } 276 283 277 - async originalResolveUrl(id: string, importer?: string) { 284 + async originalResolveUrl(id: string, importer?: string): Promise<[url: string, fsPath: string]> { 278 285 return super.resolveUrl(id, importer) 279 286 } 280 287 281 - async resolveUrl(id: string, importer?: string) { 288 + async resolveUrl(id: string, importer?: string): Promise<[url: string, fsPath: string]> { 282 289 if (VitestMocker.pendingIds.length) { 283 290 await this.mocker.resolveMocks() 284 291 } ··· 302 309 } 303 310 } 304 311 305 - protected async runModule(context: Record<string, any>, transformed: string) { 312 + protected async runModule(context: Record<string, any>, transformed: string): Promise<void> { 306 313 const vmContext = this.options.context 307 314 308 315 if (!vmContext || !this.externalModules) { ··· 354 361 return super.dependencyRequest(id, fsPath, callstack) 355 362 } 356 363 357 - prepareContext(context: Record<string, any>) { 364 + prepareContext(context: Record<string, any>): Record<string, any> { 358 365 // support `import.meta.vitest` for test entry 359 366 if ( 360 367 this.state.filepath
+6 -6
packages/vitest/src/runtime/external-executor.ts
··· 74 74 this.resolvers = [this.vite.resolve] 75 75 } 76 76 77 - async import(identifier: string) { 77 + async import(identifier: string): Promise<object> { 78 78 const module = await this.createModule(identifier) 79 79 await this.esm.evaluateModule(module) 80 80 return module.namespace 81 81 } 82 82 83 - require(identifier: string) { 83 + require(identifier: string): any { 84 84 return this.cjs.require(identifier) 85 85 } 86 86 87 - createRequire(identifier: string) { 87 + createRequire(identifier: string): NodeJS.Require { 88 88 return this.cjs.createRequire(identifier) 89 89 } 90 90 ··· 92 92 public importModuleDynamically = async ( 93 93 specifier: string, 94 94 referencer: VMModule, 95 - ) => { 95 + ): Promise<VMModule> => { 96 96 const module = await this.resolveModule(specifier, referencer.identifier) 97 97 return await this.esm.evaluateModule(module) 98 98 } 99 99 100 - public resolveModule = async (specifier: string, referencer: string) => { 100 + public resolveModule = async (specifier: string, referencer: string): Promise<VMModule> => { 101 101 let identifier = this.resolve(specifier, referencer) as 102 102 | string 103 103 | Promise<string> ··· 109 109 return await this.createModule(identifier) 110 110 } 111 111 112 - public resolve(specifier: string, parent: string) { 112 + public resolve(specifier: string, parent: string): string { 113 113 for (const resolver of this.resolvers) { 114 114 const id = resolver(specifier, parent) 115 115 if (id) {
+2 -2
packages/vitest/src/runtime/inspector.ts
··· 49 49 50 50 const keepOpen = shouldKeepOpen(config) 51 51 52 - return function cleanup() { 52 + return function cleanup(): void { 53 53 if (isEnabled && !keepOpen && inspector) { 54 54 inspector.close() 55 55 session?.disconnect() ··· 57 57 } 58 58 } 59 59 60 - export function closeInspector(config: SerializedConfig) { 60 + export function closeInspector(config: SerializedConfig): void { 61 61 const keepOpen = shouldKeepOpen(config) 62 62 63 63 if (inspector && !keepOpen) {
+14 -14
packages/vitest/src/runtime/mocker.ts
··· 1 - import type { ManualMockedModule, MockedModuleType } from '@vitest/mocker' 1 + import type { ManualMockedModule, MockedModule, MockedModuleType } from '@vitest/mocker' 2 2 import type { MockFactory, MockOptions, PendingSuiteMock } from '../types/mocker' 3 3 import type { VitestExecutor } from './execute' 4 4 import { isAbsolute, resolve } from 'node:path' ··· 90 90 return this.executor.options.moduleDirectories || [] 91 91 } 92 92 93 - public async initializeSpyModule() { 93 + public async initializeSpyModule(): Promise<void> { 94 94 this.spyModule = await this.executor.executeId(spyModulePath) 95 95 } 96 96 ··· 102 102 return this.registries.get(suite)! 103 103 } 104 104 105 - public reset() { 105 + public reset(): void { 106 106 this.registries.clear() 107 107 } 108 108 ··· 158 158 } 159 159 } 160 160 161 - public async resolveMocks() { 161 + public async resolveMocks(): Promise<void> { 162 162 if (!VitestMocker.pendingIds.length) { 163 163 return 164 164 } ··· 232 232 } 233 233 234 234 // public method to avoid circular dependency 235 - public getMockContext() { 235 + public getMockContext(): MockContext { 236 236 return this.mockContext 237 237 } 238 238 ··· 241 241 return `mock:${dep}` 242 242 } 243 243 244 - public getDependencyMock(id: string) { 244 + public getDependencyMock(id: string): MockedModule | undefined { 245 245 const registry = this.getMockerRegistry() 246 246 return registry.get(id) 247 247 } 248 248 249 - public normalizePath(path: string) { 249 + public normalizePath(path: string): string { 250 250 return this.moduleCache.normalizePath(path) 251 251 } 252 252 253 - public resolveMockPath(mockPath: string, external: string | null) { 253 + public resolveMockPath(mockPath: string, external: string | null): string | null { 254 254 return findMockRedirect(this.root, mockPath, external) 255 255 } 256 256 ··· 258 258 object: Record<string | symbol, any>, 259 259 mockExports: Record<string | symbol, any> = {}, 260 260 behavior: MockedModuleType = 'automock', 261 - ) { 261 + ): Record<string | symbol, any> { 262 262 const spyOn = this.spyModule?.spyOn 263 263 if (!spyOn) { 264 264 throw this.createError( ··· 272 272 }, object, mockExports) 273 273 } 274 274 275 - public unmockPath(path: string) { 275 + public unmockPath(path: string): void { 276 276 const registry = this.getMockerRegistry() 277 277 const id = this.normalizePath(path) 278 278 ··· 286 286 external: string | null, 287 287 mockType: MockedModuleType | undefined, 288 288 factory: MockFactory | undefined, 289 - ) { 289 + ): void { 290 290 const registry = this.getMockerRegistry() 291 291 const id = this.normalizePath(path) 292 292 ··· 351 351 return this.executor.dependencyRequest(mock.redirect, mock.redirect, [importee]) 352 352 } 353 353 354 - public async requestWithMock(url: string, callstack: string[]) { 354 + public async requestWithMock(url: string, callstack: string[]): Promise<any> { 355 355 const id = this.normalizePath(url) 356 356 const mock = this.getDependencyMock(id) 357 357 ··· 401 401 id: string, 402 402 importer: string, 403 403 factoryOrOptions?: MockFactory | MockOptions, 404 - ) { 404 + ): void { 405 405 const mockType = getMockType(factoryOrOptions) 406 406 VitestMocker.pendingIds.push({ 407 407 action: 'mock', ··· 412 412 }) 413 413 } 414 414 415 - public queueUnmock(id: string, importer: string) { 415 + public queueUnmock(id: string, importer: string): void { 416 416 VitestMocker.pendingIds.push({ 417 417 action: 'unmock', 418 418 id,
+3 -3
packages/vitest/src/runtime/rpc.ts
··· 48 48 49 49 const promises = new Set<Promise<unknown>>() 50 50 51 - export async function rpcDone() { 51 + export async function rpcDone(): Promise<unknown[] | undefined> { 52 52 if (!promises.size) { 53 53 return 54 54 } ··· 61 61 BirpcOptions<RuntimeRPC>, 62 62 'on' | 'post' | 'serialize' | 'deserialize' 63 63 >, 64 - ) { 64 + ): { rpc: WorkerRPC; onCancel: Promise<CancelReason> } { 65 65 let setCancel = (_reason: CancelReason) => {} 66 66 const onCancel = new Promise<CancelReason>((resolve) => { 67 67 setCancel = resolve ··· 107 107 } 108 108 } 109 109 110 - export function createSafeRpc(rpc: WorkerRPC) { 110 + export function createSafeRpc(rpc: WorkerRPC): WorkerRPC { 111 111 return new Proxy(rpc, { 112 112 get(target, p, handler) { 113 113 const sendCall = get(target, p, handler)
+1 -1
packages/vitest/src/runtime/runners/benchmark.ts
··· 154 154 155 155 constructor(public config: SerializedConfig) {} 156 156 157 - async importTinybench() { 157 + async importTinybench(): Promise<typeof import('tinybench')> { 158 158 return await import('tinybench') 159 159 } 160 160
+11 -11
packages/vitest/src/runtime/runners/test.ts
··· 27 27 28 28 private assertionsErrors = new WeakMap<Readonly<Task>, Error>() 29 29 30 - public pool = this.workerState.ctx.pool 30 + public pool: string = this.workerState.ctx.pool 31 31 32 32 constructor(public config: SerializedConfig) {} 33 33 ··· 38 38 return this.__vitest_executor.executeId(filepath) 39 39 } 40 40 41 - onCollectStart(file: File) { 41 + onCollectStart(file: File): void { 42 42 this.workerState.current = file 43 43 } 44 44 45 - onAfterRunFiles() { 45 + onAfterRunFiles(): void { 46 46 this.snapshotClient.clear() 47 47 this.workerState.current = undefined 48 48 } 49 49 50 - async onAfterRunSuite(suite: Suite) { 50 + async onAfterRunSuite(suite: Suite): Promise<void> { 51 51 if (this.config.logHeapUsage && typeof process !== 'undefined') { 52 52 suite.result!.heap = process.memoryUsage().heapUsed 53 53 } ··· 68 68 this.workerState.current = suite.suite || suite.file 69 69 } 70 70 71 - onAfterRunTask(test: Task) { 71 + onAfterRunTask(test: Task): void { 72 72 if (this.config.logHeapUsage && typeof process !== 'undefined') { 73 73 test.result!.heap = process.memoryUsage().heapUsed 74 74 } ··· 76 76 this.workerState.current = test.suite || test.file 77 77 } 78 78 79 - onCancel(_reason: CancelReason) { 79 + onCancel(_reason: CancelReason): void { 80 80 this.cancelRun = true 81 81 } 82 82 83 - injectValue(key: string) { 83 + injectValue(key: string): any { 84 84 // inject has a very limiting type controlled by ProvidedContext 85 85 // some tests override it which causes the build to fail 86 86 return (inject as any)(key) 87 87 } 88 88 89 - async onBeforeRunTask(test: Task) { 89 + async onBeforeRunTask(test: Task): Promise<void> { 90 90 if (this.cancelRun) { 91 91 test.mode = 'skip' 92 92 } ··· 100 100 this.workerState.current = test 101 101 } 102 102 103 - async onBeforeRunSuite(suite: Suite) { 103 + async onBeforeRunSuite(suite: Suite): Promise<void> { 104 104 if (this.cancelRun) { 105 105 suite.mode = 'skip' 106 106 } ··· 116 116 this.workerState.current = suite 117 117 } 118 118 119 - onBeforeTryTask(test: Task) { 119 + onBeforeTryTask(test: Task): void { 120 120 this.snapshotClient.clearTest(test.file.filepath, test.id) 121 121 setState( 122 122 { ··· 133 133 ) 134 134 } 135 135 136 - onAfterTryTask(test: Task) { 136 + onAfterTryTask(test: Task): void { 137 137 const { 138 138 assertionCalls, 139 139 expectedAssertionsNumber,
+4 -3
packages/vitest/src/runtime/setup-common.ts
··· 1 1 import type { DiffOptions } from '@vitest/expect' 2 2 import type { SnapshotSerializer } from '@vitest/snapshot' 3 + import type { SerializedDiffOptions } from '@vitest/utils/diff' 3 4 import type { SerializedConfig } from './config' 4 5 import type { VitestExecutor } from './execute' 5 6 import { addSerializer } from '@vitest/snapshot' ··· 7 8 import { resetRunOnceCounter } from '../integrations/run-once' 8 9 9 10 let globalSetup = false 10 - export async function setupCommonEnv(config: SerializedConfig) { 11 + export async function setupCommonEnv(config: SerializedConfig): Promise<void> { 11 12 resetRunOnceCounter() 12 13 setupDefines(config.defines) 13 14 setupEnv(config.env) ··· 46 47 export async function loadDiffConfig( 47 48 config: SerializedConfig, 48 49 executor: VitestExecutor, 49 - ) { 50 + ): Promise<SerializedDiffOptions | undefined> { 50 51 if (typeof config.diff === 'object') { 51 52 return config.diff 52 53 } ··· 73 74 export async function loadSnapshotSerializers( 74 75 config: SerializedConfig, 75 76 executor: VitestExecutor, 76 - ) { 77 + ): Promise<void> { 77 78 const files = config.snapshotSerializers 78 79 79 80 const snapshotSerializers = await Promise.all(
+3 -3
packages/vitest/src/runtime/setup-node.ts
··· 20 20 config: SerializedConfig, 21 21 { environment }: ResolvedTestEnvironment, 22 22 executor: VitestExecutor, 23 - ) { 23 + ): Promise<void> { 24 24 await setupCommonEnv(config) 25 25 26 26 Object.defineProperty(globalThis, '__vitest_index__', { ··· 82 82 mod.exports = url 83 83 } 84 84 85 - export async function setupConsoleLogSpy() { 85 + export async function setupConsoleLogSpy(): Promise<void> { 86 86 const { createCustomConsole } = await import('./console') 87 87 88 88 globalThis.console = createCustomConsole() ··· 92 92 { environment }: ResolvedTestEnvironment, 93 93 options: Record<string, any>, 94 94 fn: () => Promise<void>, 95 - ) { 95 + ): Promise<void> { 96 96 // @ts-expect-error untyped global 97 97 globalThis.__vitest_environment__ = environment.name 98 98 expect.setState({
+4 -4
packages/vitest/src/runtime/utils.ts
··· 20 20 return workerState 21 21 } 22 22 23 - export function provideWorkerState(context: any, state: WorkerGlobalState) { 23 + export function provideWorkerState(context: any, state: WorkerGlobalState): WorkerGlobalState { 24 24 Object.defineProperty(context, NAME_WORKER_STATE, { 25 25 value: state, 26 26 configurable: true, ··· 40 40 return typeof process !== 'undefined' && !!process.send 41 41 } 42 42 43 - export function setProcessTitle(title: string) { 43 + export function setProcessTitle(title: string): void { 44 44 try { 45 45 process.title = `node (${title})` 46 46 } 47 47 catch {} 48 48 } 49 49 50 - export function resetModules(modules: ModuleCacheMap, resetMocks = false) { 50 + export function resetModules(modules: ModuleCacheMap, resetMocks = false): void { 51 51 const skipPaths = [ 52 52 // Vitest 53 53 /\/vitest\/dist\//, ··· 72 72 return new Promise(resolve => setTimeout(resolve, 0)) 73 73 } 74 74 75 - export async function waitForImportsToResolve() { 75 + export async function waitForImportsToResolve(): Promise<void> { 76 76 await waitNextTick() 77 77 const state = getWorkerState() 78 78 const promises: Promise<unknown>[] = []
+2 -2
packages/vitest/src/runtime/vm/commonjs-executor.ts
··· 180 180 m.exports = JSON.parse(code) 181 181 } 182 182 183 - public createRequire = (filename: string | URL) => { 183 + public createRequire = (filename: string | URL): NodeJS.Require => { 184 184 const _require = createRequire(filename) 185 185 const require = ((id: string) => { 186 186 const resolved = _require.resolve(id) ··· 255 255 return '.js' 256 256 } 257 257 258 - public require(identifier: string) { 258 + public require(identifier: string): any { 259 259 const ext = extname(identifier) 260 260 if (ext === '.node' || isNodeBuiltin(identifier)) { 261 261 return this.requireCoreModule(identifier)
+6 -6
packages/vitest/src/runtime/vm/esm-executor.ts
··· 49 49 public async createEsModule( 50 50 fileURL: string, 51 51 getCode: () => Promise<string> | string, 52 - ) { 52 + ): Promise<VMModule> { 53 53 const cached = this.moduleCache.get(fileURL) 54 54 if (cached) { 55 55 return cached ··· 96 96 return m 97 97 } 98 98 99 - public async createWebAssemblyModule(fileUrl: string, getCode: () => Buffer) { 99 + public async createWebAssemblyModule(fileUrl: string, getCode: () => Buffer): Promise<VMModule> { 100 100 const cached = this.moduleCache.get(fileUrl) 101 101 if (cached) { 102 102 return cached ··· 106 106 return m 107 107 } 108 108 109 - public async createNetworkModule(fileUrl: string) { 109 + public async createNetworkModule(fileUrl: string): Promise<VMModule> { 110 110 // https://nodejs.org/api/esm.html#https-and-http-imports 111 111 if (fileUrl.startsWith('http:')) { 112 112 const url = new URL(fileUrl) ··· 127 127 fetch(fileUrl).then(r => r.text())) 128 128 } 129 129 130 - public async loadWebAssemblyModule(source: Buffer, identifier: string) { 130 + public async loadWebAssemblyModule(source: Buffer, identifier: string): Promise<VMModule> { 131 131 const cached = this.moduleCache.get(identifier) 132 132 if (cached) { 133 133 return cached ··· 175 175 return syntheticModule 176 176 } 177 177 178 - public cacheModule(identifier: string, module: VMModule) { 178 + public cacheModule(identifier: string, module: VMModule): void { 179 179 this.moduleCache.set(identifier, module) 180 180 } 181 181 182 - public resolveCachedModule(identifier: string) { 182 + public resolveCachedModule(identifier: string): VMModule | Promise<VMModule> | undefined { 183 183 return this.moduleCache.get(identifier) 184 184 } 185 185
+3 -3
packages/vitest/src/runtime/vm/file-map.ts
··· 6 6 private fsCache = new Map<string, string>() 7 7 private fsBufferCache = new Map<string, Buffer>() 8 8 9 - public async readFileAsync(path: string) { 9 + public async readFileAsync(path: string): Promise<string> { 10 10 const cached = this.fsCache.get(path) 11 11 if (cached != null) { 12 12 return cached ··· 16 16 return source 17 17 } 18 18 19 - public readFile(path: string) { 19 + public readFile(path: string): string { 20 20 const cached = this.fsCache.get(path) 21 21 if (cached != null) { 22 22 return cached ··· 26 26 return source 27 27 } 28 28 29 - public readBuffer(path: string) { 29 + public readBuffer(path: string): Buffer { 30 30 const cached = this.fsBufferCache.get(path) 31 31 if (cached != null) { 32 32 return cached
+5 -1
packages/vitest/src/runtime/vm/utils.ts
··· 5 5 export function interopCommonJsModule( 6 6 interopDefault: boolean | undefined, 7 7 mod: any, 8 - ) { 8 + ): { 9 + keys: string[] 10 + moduleExports: any 11 + defaultExport: any 12 + } { 9 13 if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) { 10 14 return { 11 15 keys: [],
+4 -3
packages/vitest/src/runtime/vm/vite-executor.ts
··· 2 2 import type { RuntimeRPC } from '../../types/rpc' 3 3 import type { WorkerGlobalState } from '../../types/worker' 4 4 import type { EsmExecutor } from './esm-executor' 5 + import type { VMModule } from './types' 5 6 import { pathToFileURL } from 'node:url' 6 7 import { normalize } from 'pathe' 7 8 import { CSS_LANGS_RE, KNOWN_ASSET_RE } from 'vite-node/constants' ··· 25 26 this.esm = options.esmExecutor 26 27 } 27 28 28 - public resolve = (identifier: string, parent: string) => { 29 + public resolve = (identifier: string, parent: string): string | undefined => { 29 30 if (identifier === CLIENT_ID) { 30 31 if (this.workerState.environment.transformMode === 'web') { 31 32 return identifier ··· 53 54 return name 54 55 } 55 56 56 - public async createViteModule(fileUrl: string) { 57 + public async createViteModule(fileUrl: string): Promise<VMModule> { 57 58 if (fileUrl === CLIENT_FILE) { 58 59 return this.createViteClientModule() 59 60 } ··· 93 94 return module 94 95 } 95 96 96 - public canResolve = (fileUrl: string) => { 97 + public canResolve = (fileUrl: string): boolean => { 97 98 const transformMode = this.workerState.environment.transformMode 98 99 if (transformMode !== 'web') { 99 100 return false
+2 -2
packages/vitest/src/runtime/worker.ts
··· 113 113 } 114 114 } 115 115 116 - export function run(ctx: ContextRPC) { 116 + export function run(ctx: ContextRPC): Promise<void> { 117 117 return execute('run', ctx) 118 118 } 119 119 120 - export function collect(ctx: ContextRPC) { 120 + export function collect(ctx: ContextRPC): Promise<void> { 121 121 return execute('collect', ctx) 122 122 }
+1 -1
packages/vitest/src/runtime/workers/base.ts
··· 17 17 return _viteNode 18 18 } 19 19 20 - export async function runBaseTests(method: 'run' | 'collect', state: WorkerGlobalState) { 20 + export async function runBaseTests(method: 'run' | 'collect', state: WorkerGlobalState): Promise<void> { 21 21 const { ctx } = state 22 22 // state has new context, but we want to reuse existing ones 23 23 state.moduleCache = moduleCache
+7 -6
packages/vitest/src/runtime/workers/forks.ts
··· 1 1 import type { WorkerGlobalState } from '../../types/worker' 2 - import type { VitestWorker } from './types' 2 + import type { VitestWorker, WorkerRpcOptions } from './types' 3 3 import v8 from 'node:v8' 4 4 import { runBaseTests } from './base' 5 5 import { createForksRpcOptions, unwrapSerializableConfig } from './utils' 6 6 7 7 class ForksBaseWorker implements VitestWorker { 8 - getRpcOptions() { 8 + getRpcOptions(): WorkerRpcOptions { 9 9 return createForksRpcOptions(v8) 10 10 } 11 11 12 - async executeTests(method: 'run' | 'collect', state: WorkerGlobalState) { 12 + async executeTests(method: 'run' | 'collect', state: WorkerGlobalState): Promise<void> { 13 13 // TODO: don't rely on reassigning process.exit 14 14 // https://github.com/vitest-dev/vitest/pull/4441#discussion_r1443771486 15 15 const exit = process.exit ··· 23 23 } 24 24 } 25 25 26 - runTests(state: WorkerGlobalState) { 26 + runTests(state: WorkerGlobalState): Promise<void> { 27 27 return this.executeTests('run', state) 28 28 } 29 29 30 - collectTests(state: WorkerGlobalState) { 30 + collectTests(state: WorkerGlobalState): Promise<void> { 31 31 return this.executeTests('collect', state) 32 32 } 33 33 } 34 34 35 - export default new ForksBaseWorker() 35 + const worker: ForksBaseWorker = new ForksBaseWorker() 36 + export default worker
+4 -3
packages/vitest/src/runtime/workers/threads.ts
··· 1 1 import type { WorkerContext } from '../../node/types/worker' 2 2 import type { ContextRPC, WorkerGlobalState } from '../../types/worker' 3 - import type { VitestWorker } from './types' 3 + import type { VitestWorker, WorkerRpcOptions } from './types' 4 4 import { runBaseTests } from './base' 5 5 import { createThreadsRpcOptions } from './utils' 6 6 7 7 class ThreadsBaseWorker implements VitestWorker { 8 - getRpcOptions(ctx: ContextRPC) { 8 + getRpcOptions(ctx: ContextRPC): WorkerRpcOptions { 9 9 return createThreadsRpcOptions(ctx as WorkerContext) 10 10 } 11 11 ··· 18 18 } 19 19 } 20 20 21 - export default new ThreadsBaseWorker() 21 + const worker: ThreadsBaseWorker = new ThreadsBaseWorker() 22 + export default worker
+2 -2
packages/vitest/src/runtime/workers/utils.ts
··· 25 25 } 26 26 } 27 27 28 - export function disposeInternalListeners() { 28 + export function disposeInternalListeners(): void { 29 29 for (const fn of dispose) { 30 30 try { 31 31 fn() ··· 62 62 /** 63 63 * Reverts the wrapping done by `utils/config-helpers.ts`'s `wrapSerializableConfig` 64 64 */ 65 - export function unwrapSerializableConfig(config: SerializedConfig) { 65 + export function unwrapSerializableConfig(config: SerializedConfig): SerializedConfig { 66 66 if (config.testNamePattern && typeof config.testNamePattern === 'string') { 67 67 const testNamePattern = config.testNamePattern as string 68 68
+1 -1
packages/vitest/src/runtime/workers/vm.ts
··· 15 15 const fileMap = new FileMap() 16 16 const packageCache = new Map<string, string>() 17 17 18 - export async function runVmTests(method: 'run' | 'collect', state: WorkerGlobalState) { 18 + export async function runVmTests(method: 'run' | 'collect', state: WorkerGlobalState): Promise<void> { 19 19 const { environment, ctx, rpc } = state 20 20 21 21 if (!environment.setupVM) {
+7 -6
packages/vitest/src/runtime/workers/vmForks.ts
··· 1 1 import type { WorkerGlobalState } from '../../types/worker' 2 - import type { VitestWorker } from './types' 2 + import type { VitestWorker, WorkerRpcOptions } from './types' 3 3 import v8 from 'node:v8' 4 4 import { createForksRpcOptions, unwrapSerializableConfig } from './utils' 5 5 import { runVmTests } from './vm' 6 6 7 7 class ForksVmWorker implements VitestWorker { 8 - getRpcOptions() { 8 + getRpcOptions(): WorkerRpcOptions { 9 9 return createForksRpcOptions(v8) 10 10 } 11 11 12 - async executeTests(method: 'run' | 'collect', state: WorkerGlobalState) { 12 + async executeTests(method: 'run' | 'collect', state: WorkerGlobalState): Promise<void> { 13 13 const exit = process.exit 14 14 state.ctx.config = unwrapSerializableConfig(state.ctx.config) 15 15 ··· 21 21 } 22 22 } 23 23 24 - runTests(state: WorkerGlobalState) { 24 + runTests(state: WorkerGlobalState): Promise<void> { 25 25 return this.executeTests('run', state) 26 26 } 27 27 28 - collectTests(state: WorkerGlobalState) { 28 + collectTests(state: WorkerGlobalState): Promise<void> { 29 29 return this.executeTests('collect', state) 30 30 } 31 31 } 32 32 33 - export default new ForksVmWorker() 33 + const worker: ForksVmWorker = new ForksVmWorker() 34 + export default worker
+2 -1
packages/vitest/src/runtime/workers/vmThreads.ts
··· 18 18 } 19 19 } 20 20 21 - export default new ThreadsVmWorker() 21 + const worker: ThreadsVmWorker = new ThreadsVmWorker() 22 + export default worker
+5 -2
packages/vitest/src/typecheck/parse.ts
··· 63 63 ] 64 64 } 65 65 66 - export async function getTsconfig(root: string, config: TypecheckConfig) { 66 + export async function getTsconfig(root: string, config: TypecheckConfig): Promise<{ 67 + path: string 68 + config: Record<string, any> 69 + }> { 67 70 const configName = config.tsconfig ? basename(config.tsconfig) : undefined 68 71 const configSearchPath = config.tsconfig 69 72 ? dirname(resolve(root, config.tsconfig)) ··· 104 107 } 105 108 } 106 109 107 - export async function getRawErrsMapFromTsCompile(tscErrorStdout: string) { 110 + export async function getRawErrsMapFromTsCompile(tscErrorStdout: string): Promise<RawErrsMap> { 108 111 const rawErrsMap: RawErrsMap = new Map() 109 112 110 113 // Merge details line with main line (i.e. which contains file path)
+29 -19
packages/vitest/src/typecheck/typechecker.ts
··· 57 57 58 58 constructor(protected ctx: TestProject) {} 59 59 60 - public setFiles(files: string[]) { 60 + public setFiles(files: string[]): void { 61 61 this.files = files 62 62 } 63 63 64 - public onParseStart(fn: Callback) { 64 + public onParseStart(fn: Callback): void { 65 65 this._onParseStart = fn 66 66 } 67 67 68 - public onParseEnd(fn: Callback<[TypecheckResults]>) { 68 + public onParseEnd(fn: Callback<[TypecheckResults]>): void { 69 69 this._onParseEnd = fn 70 70 } 71 71 72 - public onWatcherRerun(fn: Callback) { 72 + public onWatcherRerun(fn: Callback): void { 73 73 this._onWatcherRerun = fn 74 74 } 75 75 ··· 79 79 return collectTests(this.ctx, filepath) 80 80 } 81 81 82 - protected getFiles() { 82 + protected getFiles(): string[] { 83 83 return this.files.filter((filename) => { 84 84 const extension = extname(filename) 85 85 return extension !== '.js' || this.allowJs 86 86 }) 87 87 } 88 88 89 - public async collectTests() { 89 + public async collectTests(): Promise<Record<string, FileInformation>> { 90 90 const tests = ( 91 91 await Promise.all( 92 92 this.getFiles().map(filepath => this.collectFileTests(filepath)), ··· 102 102 return tests 103 103 } 104 104 105 - protected markPassed(file: File) { 105 + protected markPassed(file: File): void { 106 106 if (!file.result?.state) { 107 107 file.result = { 108 108 state: 'pass', ··· 123 123 markTasks(file.tasks) 124 124 } 125 125 126 - protected async prepareResults(output: string) { 126 + protected async prepareResults(output: string): Promise<{ 127 + files: File[] 128 + sourceErrors: TypeCheckError[] 129 + time: number 130 + }> { 127 131 const typeErrors = await this.parseTscLikeOutput(output) 128 132 const testFiles = new Set(this.getFiles()) 129 133 ··· 211 215 } 212 216 } 213 217 214 - protected async parseTscLikeOutput(output: string) { 218 + protected async parseTscLikeOutput(output: string): Promise<Map<string, { 219 + error: TypeCheckError 220 + originalError: TscErrorInfo 221 + }[]>> { 215 222 const errorsMap = await getRawErrsMapFromTsCompile(output) 216 223 const typesErrors = new Map< 217 224 string, ··· 253 260 return typesErrors 254 261 } 255 262 256 - public async clear() { 263 + public async clear(): Promise<void> { 257 264 if (this.tempConfigPath) { 258 265 await rm(this.tempConfigPath, { force: true }) 259 266 } 260 267 } 261 268 262 - public async stop() { 269 + public async stop(): Promise<void> { 263 270 await this.clear() 264 271 this.process?.kill() 265 272 this.process = undefined 266 273 } 267 274 268 - protected async ensurePackageInstalled(ctx: Vitest, checker: string) { 275 + protected async ensurePackageInstalled(ctx: Vitest, checker: string): Promise<void> { 269 276 if (checker !== 'tsc' && checker !== 'vue-tsc') { 270 277 return 271 278 } ··· 273 280 await ctx.packageInstaller.ensureInstalled(packageName, ctx.config.root) 274 281 } 275 282 276 - public async prepare() { 283 + public async prepare(): Promise<void> { 277 284 const { root, typecheck } = this.ctx.config 278 285 279 286 const { config, path } = await getTsconfig(root, typecheck) ··· 282 289 this.allowJs = typecheck.allowJs || config.allowJs || false 283 290 } 284 291 285 - public getExitCode() { 292 + public getExitCode(): number | false { 286 293 return this.process?.exitCode != null && this.process.exitCode 287 294 } 288 295 289 - public getOutput() { 296 + public getOutput(): string { 290 297 return this._output 291 298 } 292 299 293 - public async start() { 300 + public async start(): Promise<void> { 294 301 if (this.process) { 295 302 return 296 303 } ··· 350 357 } 351 358 } 352 359 353 - public getResult() { 360 + public getResult(): TypecheckResults { 354 361 return this._result 355 362 } 356 363 357 - public getTestFiles() { 364 + public getTestFiles(): File[] { 358 365 return Object.values(this._tests || {}).map(i => i.file) 359 366 } 360 367 361 - public getTestPacksAndEvents() { 368 + public getTestPacksAndEvents(): { 369 + packs: TaskResultPack[] 370 + events: TaskEventPack[] 371 + } { 362 372 const packs: TaskResultPack[] = [] 363 373 const events: TaskEventPack[] = [] 364 374
+1 -1
packages/vitest/src/typecheck/utils.ts
··· 1 - export function createIndexMap(source: string) { 1 + export function createIndexMap(source: string): Map<string, number> { 2 2 const map = new Map<string, number>() 3 3 let index = 0 4 4 let line = 1
+2 -2
packages/vitest/src/utils/base.ts
··· 3 3 export function groupBy<T, K extends string | number | symbol>( 4 4 collection: T[], 5 5 iteratee: (item: T) => K, 6 - ) { 6 + ): Record<K, T[]> { 7 7 return collection.reduce((acc, item) => { 8 8 const key = iteratee(item) 9 9 acc[key] ||= [] ··· 18 18 return console._stdout || process.stdout 19 19 } 20 20 21 - export function escapeRegExp(s: string) { 21 + export function escapeRegExp(s: string): string { 22 22 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping 23 23 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string 24 24 }
+1 -1
packages/vitest/src/utils/colors.ts
··· 13 13 ]), 14 14 ) 15 15 16 - export function highlightCode(id: string, source: string, colors?: Colors) { 16 + export function highlightCode(id: string, source: string, colors?: Colors): string { 17 17 const ext = extname(id) 18 18 if (!HIGHLIGHT_SUPPORTED_EXTS.has(ext)) { 19 19 return source
+1 -1
packages/vitest/src/utils/config-helpers.ts
··· 13 13 export function getOutputFile( 14 14 config: PotentialConfig | undefined, 15 15 reporter: BuiltinReporters | BenchmarkBuiltinReporters | 'html', 16 - ) { 16 + ): string | undefined { 17 17 if (!config?.outputFile) { 18 18 return 19 19 }
+11 -10
packages/vitest/src/utils/coverage.ts
··· 1 1 import type { CoverageMap } from 'istanbul-lib-coverage' 2 + import type { TransformResult } from 'vite' 2 3 import type { Vitest } from '../node/core' 3 4 import type { BaseCoverageOptions, ReportContext, ResolvedCoverageOptions } from '../node/types/coverage' 4 5 import type { AfterSuiteRunMeta } from '../types/general' ··· 62 63 pendingPromises: Promise<void>[] = [] 63 64 coverageFilesDirectory!: string 64 65 65 - _initialize(ctx: Vitest) { 66 + _initialize(ctx: Vitest): void { 66 67 this.ctx = ctx 67 68 68 69 if (ctx.version !== this.version) { ··· 116 117 throw new Error('BaseReporter\'s createCoverageMap was not overwritten') 117 118 } 118 119 119 - async generateReports(_: CoverageMap, __: boolean | undefined) { 120 + async generateReports(_: CoverageMap, __: boolean | undefined): Promise<void> { 120 121 throw new Error('BaseReporter\'s generateReports was not overwritten') 121 122 } 122 123 ··· 124 125 throw new Error('BaseReporter\'s parseConfigModule was not overwritten') 125 126 } 126 127 127 - resolveOptions() { 128 + resolveOptions(): Options { 128 129 return this.options 129 130 } 130 131 ··· 186 187 /** Callback invoked once all results of a project for specific transform mode are read */ 187 188 onFinished: (project: Vitest['projects'][number], transformMode: AfterSuiteRunMeta['transformMode']) => Promise<void> 188 189 onDebug: ((...logs: any[]) => void) & { enabled: boolean } 189 - }) { 190 + }): Promise<void> { 190 191 let index = 0 191 192 const total = this.pendingPromises.length 192 193 ··· 218 219 } 219 220 } 220 221 221 - async cleanAfterRun() { 222 + async cleanAfterRun(): Promise<void> { 222 223 this.coverageFiles = new Map() 223 224 await fs.rm(this.coverageFilesDirectory, { recursive: true }) 224 225 ··· 228 229 } 229 230 } 230 231 231 - async onTestFailure() { 232 + async onTestFailure(): Promise<void> { 232 233 if (!this.options.reportOnFailure) { 233 234 await this.cleanAfterRun() 234 235 } ··· 248 249 } 249 250 } 250 251 251 - async reportThresholds(coverageMap: CoverageMap, allTestsRun: boolean | undefined) { 252 + async reportThresholds(coverageMap: CoverageMap, allTestsRun: boolean | undefined): Promise<void> { 252 253 const resolvedThresholds = this.resolveThresholds(coverageMap) 253 254 this.checkThresholds(resolvedThresholds) 254 255 ··· 426 427 thresholds: ResolvedThreshold[] 427 428 configurationFile: unknown // ProxifiedModule from magicast 428 429 onUpdate: () => void 429 - }) { 430 + }): Promise<void> { 430 431 let updatedThresholds = false 431 432 432 433 const config = resolveConfig(configurationFile) ··· 505 506 await this.generateReports(coverageMap, true) 506 507 } 507 508 508 - hasTerminalReporter(reporters: ResolvedCoverageOptions['reporter']) { 509 + hasTerminalReporter(reporters: ResolvedCoverageOptions['reporter']): boolean { 509 510 return reporters.some( 510 511 ([reporter]) => 511 512 reporter === 'text' ··· 542 543 { root: ctx.config.root, vitenode: ctx.vitenode }, 543 544 ] 544 545 545 - return async function transformFile(filename: string) { 546 + return async function transformFile(filename: string): Promise<TransformResult | null | undefined> { 546 547 let lastError 547 548 548 549 for (const { root, vitenode } of servers) {
+1 -1
packages/vitest/src/utils/env.ts
··· 9 9 = typeof process < 'u' 10 10 && typeof process.stdout < 'u' 11 11 && process.versions?.deno !== undefined 12 - export const isWindows = (isNode || isDeno) && process.platform === 'win32' 12 + export const isWindows: boolean = (isNode || isDeno) && process.platform === 'win32' 13 13 export const isBrowser: boolean = typeof window !== 'undefined' 14 14 export const isTTY: boolean = ((isNode || isDeno) && process.stdout?.isTTY && !isCI) 15 15 export { isCI, provider as stdProvider } from 'std-env'
+1 -1
packages/vitest/src/utils/memory-limit.ts
··· 19 19 : Math.max(numCpus - 1, 1) 20 20 } 21 21 22 - export function getWorkerMemoryLimit(config: ResolvedConfig) { 22 + export function getWorkerMemoryLimit(config: ResolvedConfig): string | number { 23 23 const memoryLimit = config.poolOptions?.vmThreads?.memoryLimit 24 24 25 25 if (memoryLimit) {
+1 -1
packages/vitest/src/utils/serialization.ts
··· 16 16 * Replacer function for serialization methods such as JS.stringify() or 17 17 * flatted.stringify(). 18 18 */ 19 - export function stringifyReplace(key: string, value: any) { 19 + export function stringifyReplace(key: string, value: any): any { 20 20 if (value instanceof Error) { 21 21 const cloned = cloneByOwnProperties(value) 22 22 return {
+7 -2
packages/vitest/src/utils/test-helpers.ts
··· 1 + import type { TestProject } from '../node/project' 1 2 import type { TestSpecification } from '../node/spec' 2 3 import type { EnvironmentOptions, TransformModePatterns, VitestEnvironment } from '../node/types/config' 3 4 import type { ContextTestEnvironment } from '../types/worker' ··· 5 6 import mm from 'micromatch' 6 7 import { groupBy } from './base' 7 8 8 - export const envsOrder = ['node', 'jsdom', 'happy-dom', 'edge-runtime'] 9 + export const envsOrder: string[] = ['node', 'jsdom', 'happy-dom', 'edge-runtime'] 9 10 10 11 export interface FileByEnv { 11 12 file: string ··· 28 29 29 30 export async function groupFilesByEnv( 30 31 files: Array<TestSpecification>, 31 - ) { 32 + ): Promise<Record<string, { 33 + file: { filepath: string; testLocations: number[] | undefined } 34 + project: TestProject 35 + environment: ContextTestEnvironment 36 + }[]>> { 32 37 const filesWithEnv = await Promise.all( 33 38 files.map(async ({ moduleId: filepath, project, testLines }) => { 34 39 const code = await fs.readFile(filepath, 'utf-8')
+1 -1
packages/vitest/src/utils/workers.ts
··· 1 1 import os from 'node:os' 2 2 3 - export function getWorkersCountByPercentage(percent: string) { 3 + export function getWorkersCountByPercentage(percent: string): number { 4 4 const maxWorkersCount = os.availableParallelism?.() ?? os.cpus().length 5 5 const workersCountByPercentage = Math.round((Number.parseInt(percent) / 100) * maxWorkersCount) 6 6
+3
packages/vitest/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 + "compilerOptions": { 4 + "isolatedDeclarations": true 5 + }, 3 6 "include": ["src/**/*"], 4 7 "exclude": ["**/dist/**"] 5 8 }
+1 -1
packages/web-worker/src/pure.ts
··· 3 3 import { assertGlobalExists } from './utils' 4 4 import { createWorkerConstructor } from './worker' 5 5 6 - export function defineWebWorkers(options?: DefineWorkerOptions) { 6 + export function defineWebWorkers(options?: DefineWorkerOptions): void { 7 7 if ( 8 8 typeof Worker === 'undefined' 9 9 || !('__VITEST_WEB_WORKER__' in globalThis.Worker)
+1 -1
packages/web-worker/src/runner.ts
··· 8 8 this.mocker = (globalThis as any).__vitest_mocker__ = mocker 9 9 } 10 10 11 - prepareContext(context: Record<string, any>) { 11 + prepareContext(context: Record<string, any>): any { 12 12 const ctx = super.prepareContext(context) 13 13 // not supported for now, we can't synchronously load modules 14 14 return Object.assign(ctx, this.context, {
+4 -4
packages/web-worker/src/utils.ts
··· 7 7 // keep the reference in case it was mocked 8 8 const readFileSync = _readFileSync 9 9 10 - export const debug = createDebug('vitest:web-worker') 10 + export const debug: createDebug.Debugger = createDebug('vitest:web-worker') 11 11 12 12 export function getWorkerState(): WorkerGlobalState { 13 13 // @ts-expect-error untyped global 14 14 return globalThis.__vitest_worker__ 15 15 } 16 16 17 - export function assertGlobalExists(name: string) { 17 + export function assertGlobalExists(name: string): void { 18 18 if (!(name in globalThis)) { 19 19 throw new Error( 20 20 `[@vitest/web-worker] Cannot initiate a custom Web Worker. "${name}" is not supported in this environment. Please, consider using jsdom or happy-dom environment.`, ··· 67 67 data: any, 68 68 transferOrOptions: StructuredSerializeOptions | Transferable[] | undefined, 69 69 clone: CloneOption, 70 - ) { 70 + ): MessageEvent { 71 71 try { 72 72 return createClonedMessageEvent(data, transferOrOptions, clone) 73 73 } ··· 109 109 return url.toString().replace(/^file:\/+/, '/') 110 110 } 111 111 112 - export function getFileIdFromUrl(url: URL | string) { 112 + export function getFileIdFromUrl(url: URL | string): string { 113 113 if (typeof self === 'undefined') { 114 114 return stripProtocol(url) 115 115 }
+2 -1
packages/web-worker/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 3 "compilerOptions": { 4 - "lib": ["ESNext", "WebWorker"] 4 + "lib": ["ESNext", "WebWorker"], 5 + "isolatedDeclarations": true 5 6 }, 6 7 "exclude": ["./dist"] 7 8 }
+1 -1
packages/ws-client/src/index.ts
··· 28 28 reconnect: () => Promise<void> 29 29 } 30 30 31 - export function createClient(url: string, options: VitestClientOptions = {}) { 31 + export function createClient(url: string, options: VitestClientOptions = {}): VitestClient { 32 32 const { 33 33 handlers = {}, 34 34 autoReconnect = true,
+10 -10
packages/ws-client/src/state.ts
··· 7 7 8 8 // Note this file is shared for both node and browser, be aware to avoid node specific logic 9 9 export class StateManager { 10 - filesMap = new Map<string, File[]>() 10 + filesMap: Map<string, File[]> = new Map() 11 11 pathsSet: Set<string> = new Set() 12 - idMap = new Map<string, Task>() 12 + idMap: Map<string, Task> = new Map() 13 13 14 - getPaths() { 14 + getPaths(): string[] { 15 15 return Array.from(this.pathsSet) 16 16 } 17 17 ··· 32 32 return Array.from(this.filesMap.keys()) 33 33 } 34 34 35 - getFailedFilepaths() { 35 + getFailedFilepaths(): string[] { 36 36 return this.getFiles() 37 37 .filter(i => i.result?.state === 'fail') 38 38 .map(i => i.filepath) 39 39 } 40 40 41 - collectPaths(paths: string[] = []) { 41 + collectPaths(paths: string[] = []): void { 42 42 paths.forEach((path) => { 43 43 this.pathsSet.add(path) 44 44 }) 45 45 } 46 46 47 - collectFiles(files: File[] = []) { 47 + collectFiles(files: File[] = []): void { 48 48 files.forEach((file) => { 49 49 const existing = this.filesMap.get(file.filepath) || [] 50 50 const otherProject = existing.filter( ··· 68 68 clearFiles( 69 69 _project: { config: { name: string | undefined; root: string } }, 70 70 paths: string[] = [], 71 - ) { 71 + ): void { 72 72 const project = _project 73 73 paths.forEach((path) => { 74 74 const files = this.filesMap.get(path) ··· 96 96 }) 97 97 } 98 98 99 - updateId(task: Task) { 99 + updateId(task: Task): void { 100 100 if (this.idMap.get(task.id) === task) { 101 101 return 102 102 } ··· 108 108 } 109 109 } 110 110 111 - updateTasks(packs: TaskResultPack[]) { 111 + updateTasks(packs: TaskResultPack[]): void { 112 112 for (const [id, result, meta] of packs) { 113 113 const task = this.idMap.get(id) 114 114 if (task) { ··· 122 122 } 123 123 } 124 124 125 - updateUserLog(log: UserConsoleLog) { 125 + updateUserLog(log: UserConsoleLog): void { 126 126 const task = log.taskId && this.idMap.get(log.taskId) 127 127 if (task) { 128 128 if (!task.logs) {
+3
packages/ws-client/tsconfig.json
··· 1 1 { 2 2 "extends": "../../tsconfig.base.json", 3 + "compilerOptions": { 4 + "isolatedDeclarations": true 5 + }, 3 6 "exclude": ["./dist"] 4 7 }