···1111 UserEventTabOptions,
1212 UserEventTypeOptions,
1313} from '../../../context'
1414+import type { BrowserRunnerState } from '../utils'
1415import { convertElementToCssSelector, ensureAwaited, getBrowserState, getWorkerState } from '../utils'
15161617// this file should not import anything directly, only types and utils
···238239 return vitestUserEvent
239240}
240241241241-export function cdp() {
242242+export function cdp(): BrowserRunnerState['cdp'] {
242243 return getBrowserState().cdp!
243244}
244245
···17171818const BROWSER_API_PATH = '/__vitest_browser_api__'
19192020-export function setupBrowserRpc(globalServer: ParentBrowserProject) {
2020+export function setupBrowserRpc(globalServer: ParentBrowserProject): void {
2121 const vite = globalServer.vite
2222 const vitest = globalServer.vitest
2323···289289 * Replacer function for serialization methods such as JS.stringify() or
290290 * flatted.stringify().
291291 */
292292-export function stringifyReplace(key: string, value: any) {
292292+export function stringifyReplace(key: string, value: any): any {
293293 if (value instanceof Error) {
294294 const cloned = cloneByOwnProperties(value)
295295 return {
+1-1
packages/browser/src/node/serverOrchestrator.ts
···77 globalServer: ParentBrowserProject,
88 url: URL,
99 res: ServerResponse<IncomingMessage>,
1010-) {
1010+): Promise<string | undefined> {
1111 let sessionId = url.searchParams.get('sessionId')
1212 // it's possible to open the page without a context
1313 if (!sessionId) {
+2-2
packages/browser/src/node/state.ts
···22import type { WebSocketBrowserRPC } from './types'
3344export class BrowserServerState implements IBrowserServerState {
55- public readonly orchestrators = new Map<string, WebSocketBrowserRPC>()
66- public readonly testers = new Map<string, WebSocketBrowserRPC>()
55+ public readonly orchestrators: Map<string, WebSocketBrowserRPC> = new Map()
66+ public readonly testers: Map<string, WebSocketBrowserRPC> = new Map()
77}
+2-2
packages/browser/src/node/utils.ts
···11import type { BrowserProviderModule, ResolvedBrowserOptions, TestProject } from 'vitest/node'
2233-export function replacer(code: string, values: Record<string, string>) {
33+export function replacer(code: string, values: Record<string, string>): string {
44 return code.replace(/\{\s*(\w+)\s*\}/g, (_, key) => values[key] ?? _)
55}
66···4242 return customProviderModule.default
4343}
44444545-export function slash(path: string) {
4545+export function slash(path: string): string {
4646 return path.replace(/\\/g, '/').replace(/\/+/g, '/')
4747}
···11+import type { V8CoverageProvider } from './provider'
22+13// to not bundle the provider
24const name = './provider.js'
3544-export async function loadProvider() {
66+export async function loadProvider(): Promise<V8CoverageProvider> {
57 const { V8CoverageProvider } = (await import(/* @vite-ignore */ name)) as typeof import('./provider')
6879 return new V8CoverageProvider()
+4-3
packages/coverage-v8/src/provider.ts
···11import type { CoverageMap } from 'istanbul-lib-coverage'
22+import type { ProxifiedModule } from 'magicast'
23import type { Profiler } from 'node:inspector'
34import type { EncodedSourceMap, FetchResult } from 'vite-node'
45import type { AfterSuiteRunMeta } from 'vitest'
···43444445export class V8CoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<'v8'>> implements CoverageProvider {
4546 name = 'v8' as const
4646- version = version
4747+ version: string = version
4748 testExclude!: InstanceType<typeof TestExclude>
48494950 initialize(ctx: Vitest): void {
···5960 })
6061 }
61626262- createCoverageMap() {
6363+ createCoverageMap(): CoverageMap {
6364 return libCoverage.createCoverageMap({})
6465 }
6566···151152 }
152153 }
153154154154- async parseConfigModule(configFilePath: string) {
155155+ async parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>> {
155156 return parseModule(
156157 await fs.readFile(configFilePath, 'utf8'),
157158 )
···360360 }
361361}
362362363363-export async function create() {
363363+export async function create(): Promise<void> {
364364 log(c.cyan('◼'), 'This utility will help you set up a browser testing environment.\n')
365365366366 const pkgJsonPath = resolve(process.cwd(), 'package.json')
+1-1
packages/vitest/src/create/browser/examples.ts
···198198 }
199199}
200200201201-export async function generateExampleFiles(framework: string, lang: 'ts' | 'js') {
201201+export async function generateExampleFiles(framework: string, lang: 'ts' | 'js'): Promise<string> {
202202 const example = getExampleTest(framework)
203203 let fileName = example.name
204204 const folder = resolve(process.cwd(), 'vitest-example')
···11import { globalApis } from '../constants'
22import * as index from '../public/index'
3344-export function registerApiGlobally() {
44+export function registerApiGlobally(): void {
55 globalApis.forEach((api) => {
66 // @ts-expect-error I know what I am doing :P
77 globalThis[api] = index[api]
+1-1
packages/vitest/src/integrations/mock/date.ts
···2323SOFTWARE.
2424*/
25252626-export const RealDate = Date
2626+export const RealDate: DateConstructor = Date
27272828let now: null | number = null
2929
···3131 lineNumber?: undefined | number
3232}
33333434-export function groupFilters(filters: FileFilter[]) {
3434+export function groupFilters(filters: FileFilter[]): Record<string, number[]> {
3535 const groupedFilters_ = groupBy(filters, f => f.filename)
3636 const groupedFilters = Object.fromEntries(Object.entries(groupedFilters_)
3737 .map((entry) => {
+11-11
packages/vitest/src/node/core.ts
···5656 * Current Vitest version.
5757 * @example '2.0.0'
5858 */
5959- public readonly version = version
6060- static readonly version = version
5959+ public readonly version: string = version
6060+ static readonly version: string = version
6161 /**
6262 * The logger instance used to log messages. It's recommended to use this logger instead of `console`.
6363 * It's possible to override stdout and stderr streams when initiating Vitest.
···7676 /**
7777 * A path to the built Vitest directory. This is usually a folder in `node_modules`.
7878 */
7979- public readonly distPath = distDir
7979+ public readonly distPath: string = distDir
8080 /**
8181 * A list of projects that are currently running.
8282 * If projects were filtered with `--project` flag, they won't appear here.
···137137 private _onFilterWatchedSpecification: ((spec: TestSpecification) => boolean)[] = []
138138139139 /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
140140- public get invalidates() {
140140+ public get invalidates(): Set<string> {
141141 return this.watcher.invalidates
142142 }
143143144144 /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
145145- public get changedTests() {
145145+ public get changedTests(): Set<string> {
146146 return this.watcher.changedTests
147147 }
148148···193193 }
194194195195 /** @deprecated internal */
196196- setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig) {
196196+ setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig): Promise<void> {
197197 return this._setServer(options, server, cliOptions)
198198 }
199199···300300 /**
301301 * Provide a value to the test context. This value will be available to all tests with `inject`.
302302 */
303303- public provide = <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => {
303303+ public provide = <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void => {
304304 this.getRootProject().provide(key, value)
305305 }
306306···639639 /**
640640 * Vitest automatically caches test specifications for each file. This method clears the cache for the given file or the whole cache altogether.
641641 */
642642- public clearSpecificationsCache(moduleId?: string) {
642642+ public clearSpecificationsCache(moduleId?: string): void {
643643 this.specifications.clearCache(moduleId)
644644 }
645645···11801180 /**
11811181 * @deprecated use `globTestSpecifications` instead
11821182 */
11831183- public async globTestSpecs(filters: string[] = []) {
11831183+ public async globTestSpecs(filters: string[] = []): Promise<TestSpecification[]> {
11841184 return this.globTestSpecifications(filters)
11851185 }
1186118611871187 /**
11881188 * @deprecated use `globTestSpecifications` instead
11891189 */
11901190- public async globTestFiles(filters: string[] = []) {
11901190+ public async globTestFiles(filters: string[] = []): Promise<TestSpecification[]> {
11911191 return this.globTestSpecifications(filters)
11921192 }
1193119311941194 /** @deprecated filter by `this.projects` yourself */
11951195- public getModuleProjects(filepath: string) {
11951195+ public getModuleProjects(filepath: string): TestProject[] {
11961196 return this.projects.filter((project) => {
11971197 return project.getModulesByFilepath(filepath).size
11981198 // TODO: reevaluate || project.browser?.moduleGraph.getModulesByFile(id)?.size
···6666 return project.config.pool
6767}
68686969-export function getFilePoolName(project: TestProject, file: string) {
6969+export function getFilePoolName(project: TestProject, file: string): Pool {
7070 for (const [glob, pool] of project.config.poolMatchGlobs) {
7171 if ((pool as Pool) === 'browser') {
7272 throw new Error(
+7-6
packages/vitest/src/node/project.ts
···99import type { OnTestsRerunHandler, Vitest } from './core'
1010import type { GlobalSetupFile } from './globalSetup'
1111import type { Logger } from './logger'
1212+import type { Reporter } from './reporters'
1213import type { ParentProjectBrowser, ProjectBrowser } from './types/browser'
1314import type {
1415 ResolvedConfig,
···6061 /**
6162 * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
6263 */
6363- public readonly tmpDir = join(tmpdir(), nanoid())
6464+ public readonly tmpDir: string = join(tmpdir(), nanoid())
64656566 /** @internal */ vitenode!: ViteNodeServer
6667 /** @internal */ typechecker?: Typechecker
···8182 /** @deprecated */
8283 public path: string | number,
8384 vitest: Vitest,
8484- public options?: InitializeProjectOptions,
8585+ public options?: InitializeProjectOptions | undefined,
8586 ) {
8687 this.vitest = vitest
8788 this.ctx = vitest
···222223 }
223224224225 /** @deprecated */
225225- initializeGlobalSetup() {
226226+ initializeGlobalSetup(): Promise<void> {
226227 return this._initializeGlobalSetup()
227228 }
228229···299300 }
300301301302 /** @deprecated use `vitest.reporters` instead */
302302- get reporters() {
303303+ get reporters(): Reporter[] {
303304 return this.ctx.reporters
304305 }
305306···577578 }
578579579580 /** @deprecated internal */
580580- public setServer(options: UserConfig, server: ViteDevServer) {
581581+ public setServer(options: UserConfig, server: ViteDevServer): Promise<void> {
581582 return this._configureServer(options, server)
582583 }
583584···730731 workspacePath: string | number,
731732 ctx: Vitest,
732733 options: InitializeProjectOptions,
733733-) {
734734+): Promise<TestProject> {
734735 const project = new TestProject(workspacePath, ctx, options)
735736736737 const { configFile, ...restOptions } = options
···11-import type { InlineConfig } from 'vite'
11+import type { InlineConfig, ViteDevServer } from 'vite'
22import { createServer } from 'vite'
3344-export async function createViteServer(inlineConfig: InlineConfig) {
44+export async function createViteServer(inlineConfig: InlineConfig): Promise<ViteDevServer> {
55 // Vite prints an error (https://github.com/vitejs/vite/issues/14328)
66 // But Vitest works correctly either way
77 const error = console.error
+1-1
packages/vitest/src/node/watch-filter.ts
···229229 this.stdout.write(data)
230230 }
231231232232- public getLastResults() {
232232+ public getLastResults(): string[] {
233233 return this.results
234234 }
235235}
···11-export function createIndexMap(source: string) {
11+export function createIndexMap(source: string): Map<string, number> {
22 const map = new Map<string, number>()
33 let index = 0
44 let line = 1
+2-2
packages/vitest/src/utils/base.ts
···33export function groupBy<T, K extends string | number | symbol>(
44 collection: T[],
55 iteratee: (item: T) => K,
66-) {
66+): Record<K, T[]> {
77 return collection.reduce((acc, item) => {
88 const key = iteratee(item)
99 acc[key] ||= []
···1818 return console._stdout || process.stdout
1919}
20202121-export function escapeRegExp(s: string) {
2121+export function escapeRegExp(s: string): string {
2222 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
2323 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
2424}
···1919 : Math.max(numCpus - 1, 1)
2020}
21212222-export function getWorkerMemoryLimit(config: ResolvedConfig) {
2222+export function getWorkerMemoryLimit(config: ResolvedConfig): string | number {
2323 const memoryLimit = config.poolOptions?.vmThreads?.memoryLimit
24242525 if (memoryLimit) {
+1-1
packages/vitest/src/utils/serialization.ts
···1616 * Replacer function for serialization methods such as JS.stringify() or
1717 * flatted.stringify().
1818 */
1919-export function stringifyReplace(key: string, value: any) {
1919+export function stringifyReplace(key: string, value: any): any {
2020 if (value instanceof Error) {
2121 const cloned = cloneByOwnProperties(value)
2222 return {
+7-2
packages/vitest/src/utils/test-helpers.ts
···11+import type { TestProject } from '../node/project'
12import type { TestSpecification } from '../node/spec'
23import type { EnvironmentOptions, TransformModePatterns, VitestEnvironment } from '../node/types/config'
34import type { ContextTestEnvironment } from '../types/worker'
···56import mm from 'micromatch'
67import { groupBy } from './base'
7888-export const envsOrder = ['node', 'jsdom', 'happy-dom', 'edge-runtime']
99+export const envsOrder: string[] = ['node', 'jsdom', 'happy-dom', 'edge-runtime']
9101011export interface FileByEnv {
1112 file: string
···28292930export async function groupFilesByEnv(
3031 files: Array<TestSpecification>,
3131-) {
3232+): Promise<Record<string, {
3333+ file: { filepath: string; testLocations: number[] | undefined }
3434+ project: TestProject
3535+ environment: ContextTestEnvironment
3636+ }[]>> {
3237 const filesWithEnv = await Promise.all(
3338 files.map(async ({ moduleId: filepath, project, testLines }) => {
3439 const code = await fs.readFile(filepath, 'utf-8')
+1-1
packages/vitest/src/utils/workers.ts
···11import os from 'node:os'
2233-export function getWorkersCountByPercentage(percent: string) {
33+export function getWorkersCountByPercentage(percent: string): number {
44 const maxWorkersCount = os.availableParallelism?.() ?? os.cpus().length
55 const workersCountByPercentage = Math.round((Number.parseInt(percent) / 100) * maxWorkersCount)
66