This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+4
View File
@@ -1,5 +1,7 @@
# @vitest/expect
[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner)
Jest's expect matchers as a Chai plugin.
## Usage
@@ -19,3 +21,5 @@ chai.use(JestChaiExpect)
// adds asymmetric matchers like stringContaining, objectContaining
chai.use(JestAsymmetricMatchers)
```
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/expect) | [Documentation](https://vitest.dev/api/expect)
+180 -56
View File
@@ -1,6 +1,4 @@
import { Test } from '@vitest/runner';
import { MockInstance } from '@vitest/spy';
import { Constructable } from '@vitest/utils';
import { Formatter } from 'tinyrainbow';
import { StandardSchemaV1 } from '@standard-schema/spec';
import { diff, printDiffOrStringify } from '@vitest/utils/diff';
@@ -9,11 +7,6 @@ import { stringify } from '@vitest/utils/display';
import * as chai from 'chai';
export { chai };
declare const MATCHERS_OBJECT: unique symbol;
declare const JEST_MATCHERS_OBJECT: unique symbol;
declare const GLOBAL_EXPECT: unique symbol;
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
interface AsymmetricMatcherInterface {
asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean;
toString: () => string;
@@ -131,9 +124,18 @@ interface MatcherState {
customTesters: Array<Tester>;
assertionCalls: number;
currentTestName?: string;
/**
* @deprecated exists only in types
*/
dontThrow?: () => void;
/**
* @deprecated exists only in types
*/
error?: Error;
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
/**
* @deprecated exists only in types
*/
expand?: boolean;
expectedAssertionsNumber?: number | null;
expectedAssertionsNumberErrorGen?: (() => Error) | null;
@@ -141,6 +143,9 @@ interface MatcherState {
isExpectingAssertionsError?: Error | null;
isNot: boolean;
promise: string;
/**
* @deprecated exists only in types
*/
suppressedErrors: Array<Error>;
testPath?: string;
utils: ReturnType<typeof getMatcherUtils> & {
@@ -151,13 +156,19 @@ interface MatcherState {
};
soft?: boolean;
poll?: boolean;
task?: Readonly<Test>;
/**
* The same assertion instance that chai plugins receive.
* @experimental
* @see {@link https://www.chaijs.com/guide/plugins/} Core Plugin Concepts
*/
readonly assertion: Assertion;
}
interface SyncExpectationResult {
pass: boolean;
message: () => string;
actual?: any;
expected?: any;
meta?: object;
}
type AsyncExpectationResult = Promise<SyncExpectationResult>;
type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
@@ -234,8 +245,6 @@ interface AsymmetricMatchersContaining extends CustomMatcher {
/**
* Matches if the received number is within a certain precision of the expected number.
*
* @param precision - Optional decimal precision for comparison. Default is 2.
*
* @example
* expect(10.45).toEqual(expect.closeTo(10.5, 1));
* expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
@@ -452,6 +461,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalledTimes(2);
* @deprecated Use `toHaveBeenCalledTimes` instead
*/
toBeCalledTimes: (times: number) => void;
/**
@@ -470,6 +480,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalled();
* @deprecated Use `toHaveBeenCalled` instead
*/
toBeCalled: () => void;
/**
@@ -488,6 +499,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalledWith('arg1', 42);
* @deprecated Use `toHaveBeenCalledWith` instead
*/
toBeCalledWith: <E extends any[]>(...args: E) => void;
/**
@@ -500,15 +512,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
/**
* Ensure that a mock function is called with specific arguments on an Nth call.
*
* Alias for `expect.toHaveBeenNthCalledWith`.
*
* @example
* expect(mockFunc).nthCalledWith(2, 'secondArg');
*/
nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void;
/**
* If you have a mock function, you can use `.toHaveBeenLastCalledWith`
* to test what arguments it was last called with.
*
@@ -519,16 +522,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void;
/**
* If you have a mock function, you can use `.lastCalledWith`
* to test what arguments it was last called with.
*
* Alias for `expect.toHaveBeenLastCalledWith`.
*
* @example
* expect(mockFunc).lastCalledWith('lastArg');
*/
lastCalledWith: <E extends any[]>(...args: E) => void;
/**
* Used to test that a function throws when it is called.
*
* Also under the alias `expect.toThrowError`.
@@ -536,8 +529,9 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* @example
* expect(() => functionWithError()).toThrow('Error message');
* expect(() => parseJSON('invalid')).toThrow(SyntaxError);
* expect(() => { throw 42 }).toThrow(42);
*/
toThrow: (expected?: string | Constructable | RegExp | Error) => void;
toThrow: (expected?: any) => void;
/**
* Used to test that a function throws when it is called.
*
@@ -546,8 +540,10 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* @example
* expect(() => functionWithError()).toThrowError('Error message');
* expect(() => parseJSON('invalid')).toThrowError(SyntaxError);
* expect(() => { throw 42 }).toThrowError(42);
* @deprecated Use `toThrow` instead
*/
toThrowError: (expected?: string | Constructable | RegExp | Error) => void;
toThrowError: (expected?: any) => void;
/**
* Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
*
@@ -555,6 +551,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturn();
* @deprecated Use `toHaveReturned` instead
*/
toReturn: () => void;
/**
@@ -574,6 +571,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturnTimes(3);
* @deprecated Use `toHaveReturnedTimes` instead
*/
toReturnTimes: (times: number) => void;
/**
@@ -593,6 +591,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturnWith('returnValue');
* @deprecated Use `toHaveReturnedWith` instead
*/
toReturnWith: <E>(value: E) => void;
/**
@@ -616,17 +615,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveLastReturnedWith: <E>(value: E) => void;
/**
* Use to test the specific value that a mock function last returned.
* If the last call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Alias for `expect.toHaveLastReturnedWith`.
*
* @example
* expect(mockFunc).lastReturnedWith('lastValue');
*/
lastReturnedWith: <E>(value: E) => void;
/**
* Use to test the specific value that a mock function returned for the nth call.
* If the nth call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
@@ -637,17 +625,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue');
*/
toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void;
/**
* Use to test the specific value that a mock function returned for the nth call.
* If the nth call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Alias for `expect.toHaveNthReturnedWith`.
*
* @example
* expect(mockFunc).nthReturnedWith(2, 'nthValue');
*/
nthReturnedWith: <E>(nthCall: number, value: E) => void;
}
type VitestAssertion<
A,
@@ -655,7 +632,7 @@ type VitestAssertion<
> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T> } & ((type: string, message?: string) => Assertion);
type Promisify<O> = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify<O[K]> & ((...args: A) => Promise<R>) : O[K] };
type PromisifyAssertion<T> = Promisify<Assertion<T>>;
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, Matchers<T> {
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, ChaiMockAssertion, Matchers<T> {
/**
* Ensures a value is of a specific type.
*
@@ -759,6 +736,140 @@ interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAss
*/
rejects: PromisifyAssertion<T>;
}
/**
* Chai-style assertions for spy/mock testing.
* These provide sinon-chai compatible assertion names that delegate to Jest-style implementations.
*/
interface ChaiMockAssertion {
/**
* Checks that a spy was called at least once.
* Chai-style equivalent of `toHaveBeenCalled`.
*
* @example
* expect(spy).to.have.been.called
*/
readonly called: Assertion;
/**
* Checks that a spy was called a specific number of times.
* Chai-style equivalent of `toHaveBeenCalledTimes`.
*
* @example
* expect(spy).to.have.callCount(3)
*/
callCount: (count: number) => void;
/**
* Checks that a spy was called with specific arguments at least once.
* Chai-style equivalent of `toHaveBeenCalledWith`.
*
* @example
* expect(spy).to.have.been.calledWith('arg1', 'arg2')
*/
calledWith: <E extends any[]>(...args: E) => void;
/**
* Checks that a spy was called exactly once.
* Chai-style equivalent of `toHaveBeenCalledOnce`.
*
* @example
* expect(spy).to.have.been.calledOnce
*/
readonly calledOnce: Assertion;
/**
* Checks that a spy was called exactly once with specific arguments.
* Chai-style equivalent of `toHaveBeenCalledExactlyOnceWith`.
*
* @example
* expect(spy).to.have.been.calledOnceWith('arg1', 'arg2')
*/
calledOnceWith: <E extends any[]>(...args: E) => void;
/**
* Checks that the last call to a spy was made with specific arguments.
* Chai-style equivalent of `toHaveBeenLastCalledWith`.
*
* @example
* expect(spy).to.have.been.lastCalledWith('arg1', 'arg2')
*/
lastCalledWith: <E extends any[]>(...args: E) => void;
/**
* Checks that the nth call to a spy was made with specific arguments.
* Chai-style equivalent of `toHaveBeenNthCalledWith`.
*
* @example
* expect(spy).to.have.been.nthCalledWith(2, 'arg1', 'arg2')
*/
nthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
/**
* Checks that a spy returned a specific value at least once.
* Chai-style equivalent of `toHaveReturnedWith`.
*
* @example
* expect(spy).to.have.returned('value')
*/
returned: <E>(value: E) => void;
/**
* Checks that a spy returned a specific value at least once.
* Chai-style equivalent of `toHaveReturnedWith`.
*
* @example
* expect(spy).to.have.returnedWith('value')
*/
returnedWith: <E>(value: E) => void;
/**
* Checks that a spy returned successfully a specific number of times.
* Chai-style equivalent of `toHaveReturnedTimes`.
*
* @example
* expect(spy).to.have.returnedTimes(3)
*/
returnedTimes: (count: number) => void;
/**
* Checks that the last return value of a spy matches the expected value.
* Chai-style equivalent of `toHaveLastReturnedWith`.
*
* @example
* expect(spy).to.have.lastReturnedWith('value')
*/
lastReturnedWith: <E>(value: E) => void;
/**
* Checks that the nth return value of a spy matches the expected value.
* Chai-style equivalent of `toHaveNthReturnedWith`.
*
* @example
* expect(spy).to.have.nthReturnedWith(2, 'value')
*/
nthReturnedWith: <E>(n: number, value: E) => void;
/**
* Checks that a spy was called before another spy.
* Chai-style equivalent of `toHaveBeenCalledBefore`.
*
* @example
* expect(spy1).to.have.been.calledBefore(spy2)
*/
calledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
/**
* Checks that a spy was called after another spy.
* Chai-style equivalent of `toHaveBeenCalledAfter`.
*
* @example
* expect(spy1).to.have.been.calledAfter(spy2)
*/
calledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
/**
* Checks that a spy was called exactly twice.
* Chai-style equivalent of `toHaveBeenCalledTimes(2)`.
*
* @example
* expect(spy).to.have.been.calledTwice
*/
readonly calledTwice: Assertion;
/**
* Checks that a spy was called exactly three times.
* Chai-style equivalent of `toHaveBeenCalledTimes(3)`.
*
* @example
* expect(spy).to.have.been.calledThrice
*/
readonly calledThrice: Assertion;
}
declare global {
namespace jest {
interface Matchers<
@@ -768,6 +879,13 @@ declare global {
}
}
declare const ChaiStyleAssertions: ChaiPlugin;
declare const MATCHERS_OBJECT: unique symbol;
declare const JEST_MATCHERS_OBJECT: unique symbol;
declare const GLOBAL_EXPECT: unique symbol;
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
declare const customMatchers: MatchersObject;
declare const JestChaiExpect: ChaiPlugin;
@@ -777,6 +895,7 @@ declare const JestExtend: ChaiPlugin;
declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean;
declare function isAsymmetric(obj: any): obj is AsymmetricMatcher<any>;
declare function hasAsymmetric(obj: any, seen?: Set<any>): boolean;
declare function isError(value: unknown): value is Error;
declare function isA(typeName: string, value: unknown): boolean;
declare function fnNameFor(func: Function): string;
declare function hasProperty(obj: object | null, property: string): boolean;
@@ -802,5 +921,10 @@ declare function isStandardSchema(obj: any): obj is StandardSchemaV1;
declare function getState<State extends MatcherState = MatcherState>(expect: ExpectStatic): State;
declare function setState<State extends MatcherState = MatcherState>(state: Partial<State>, expect: ExpectStatic): void;
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };
export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext };
declare function createAssertionMessage(util: Chai.ChaiUtils, assertion: Chai.Assertion, hasArgs: boolean): string;
declare function recordAsyncExpect(_test: any, promise: Promise<any>, assertion: string, error: Error, isSoft?: boolean): Promise<any>;
/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */
declare function wrapAssertion(utils: Chai.ChaiUtils, name: string, fn: (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike<void>): (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike<void>;
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion };
export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiMockAssertion, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext };
+157 -80
View File
@@ -1,6 +1,6 @@
import { printDiffOrStringify, diff } from '@vitest/utils/diff';
import { stringify } from '@vitest/utils/display';
import { getType, isObject, noop, assertTypes } from '@vitest/utils/helpers';
import { getType, isObject, noop, assertTypes, ordinal } from '@vitest/utils/helpers';
import c from 'tinyrainbow';
import { isMockFunction } from '@vitest/spy';
import { processError } from '@vitest/utils/error';
@@ -8,6 +8,56 @@ import { use, util } from 'chai';
import * as chai from 'chai';
export { chai };
const ChaiStyleAssertions = (chai, utils) => {
function defProperty(name, delegateTo) {
utils.addProperty(chai.Assertion.prototype, name, function() {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this);
});
}
function defPropertyWithArgs(name, delegateTo, ...args) {
utils.addProperty(chai.Assertion.prototype, name, function() {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this, ...args);
});
}
function defMethod(name, delegateTo) {
utils.addMethod(chai.Assertion.prototype, name, function(...args) {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this, ...args);
});
}
// API to (somewhat) mirror sinon-chai
// https://github.com/chaijs/sinon-chai
defProperty("called", "toHaveBeenCalled");
defProperty("calledOnce", "toHaveBeenCalledOnce");
defPropertyWithArgs("calledTwice", "toHaveBeenCalledTimes", 2);
defPropertyWithArgs("calledThrice", "toHaveBeenCalledTimes", 3);
defMethod("callCount", "toHaveBeenCalledTimes");
defMethod("calledWith", "toHaveBeenCalledWith");
defMethod("calledOnceWith", "toHaveBeenCalledExactlyOnceWith");
defMethod("lastCalledWith", "toHaveBeenLastCalledWith");
defMethod("nthCalledWith", "toHaveBeenNthCalledWith");
defMethod("returned", "toHaveReturned");
defMethod("returnedWith", "toHaveReturnedWith");
defMethod("returnedTimes", "toHaveReturnedTimes");
defMethod("lastReturnedWith", "toHaveLastReturnedWith");
defMethod("nthReturnedWith", "toHaveNthReturnedWith");
defMethod("calledBefore", "toHaveBeenCalledBefore");
defMethod("calledAfter", "toHaveBeenCalledAfter");
// TODO: implement
// defMethod('thrown', 'toHaveThrown')
};
const MATCHERS_OBJECT = Symbol.for("matchers-object");
const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
const GLOBAL_EXPECT = Symbol.for("expect-global");
@@ -198,6 +248,18 @@ function asymmetricMatch(a, b, customTesters) {
return b.asymmetricMatch(a, customTesters);
}
}
// https://github.com/jestjs/jest/blob/905bcbced3d40cdf7aadc4cdf6fb731c4bb3dbe3/packages/expect-utils/src/utils.ts#L509
function isError(value) {
if (typeof Error.isError === "function") {
return Error.isError(value);
}
switch (Object.prototype.toString.call(value)) {
case "[object Error]":
case "[object Exception]":
case "[object DOMException]": return true;
default: return value instanceof Error;
}
}
// Equality function lovingly adapted from isEqual in
// [Underscore](http://underscorejs.org)
function eq(a, b, aStack, bStack, customTesters, hasKey) {
@@ -286,7 +348,7 @@ function eq(a, b, aStack, bStack, customTesters, hasKey) {
if (className === "[object Array]" && a.length !== b.length) {
return false;
}
if (a instanceof Error && b instanceof Error) {
if (isError(a) && isError(b)) {
try {
return isErrorEqual(a, b, aStack, bStack, customTesters, hasKey);
} finally {
@@ -320,17 +382,17 @@ function isErrorEqual(a, b, aStack, bStack, customTesters, hasKey) {
// - [[Prototype]] of objects are compared using the === operator.
// - Only enumerable "own" properties are considered.
// - Error names, messages, causes, and errors are always compared, even if these are not enumerable properties. errors is also compared.
let result = Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && a.name === b.name && a.message === b.message;
let result = Object.prototype.toString.call(a) === Object.prototype.toString.call(b) && a.name === b.name && a.message === b.message;
// check Error.cause asymmetrically
if (typeof b.cause !== "undefined") {
result && (result = eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey));
result &&= eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey);
}
// AggregateError.errors
if (a instanceof AggregateError && b instanceof AggregateError) {
result && (result = eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey));
result &&= eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey);
}
// spread to compare enumerable properties
result && (result = eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey));
result &&= eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey);
return result;
}
function keys(obj, hasKey) {
@@ -524,7 +586,7 @@ function hasPropertyInObject(object, key) {
return Object.hasOwn(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
}
function isObjectWithKeys(a) {
return isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date);
return isObject(a) && !isError(a) && !Array.isArray(a) && !(a instanceof Date) && !(a instanceof Set) && !(a instanceof Map);
}
function subsetEquality(object, subset, customTesters = []) {
const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality);
@@ -607,10 +669,7 @@ function pluralize(word, count) {
return `${count} ${word}${count === 1 ? "" : "s"}`;
}
function getObjectKeys(object) {
return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => {
var _Object$getOwnPropert;
return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(object, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable;
})];
return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => Object.getOwnPropertyDescriptor(object, s)?.enumerable)];
}
function getObjectSubset(object, subset, customTesters) {
let stripped = 0;
@@ -788,10 +847,7 @@ class ObjectContaining extends AsymmetricMatcher {
return this.hasProperty(this.getPrototype(obj), property);
}
getProperties(obj) {
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => {
var _Object$getOwnPropert;
return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(obj, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable;
})];
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => Object.getOwnPropertyDescriptor(obj, s)?.enumerable)];
}
asymmetricMatch(other, customTesters) {
if (typeof this.sample !== "object") {
@@ -800,13 +856,12 @@ class ObjectContaining extends AsymmetricMatcher {
let result = true;
const properties = this.getProperties(this.sample);
for (const property of properties) {
var _Object$getOwnPropert2, _Object$getOwnPropert3;
if (!this.hasProperty(other, property)) {
result = false;
break;
}
const value = ((_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(this.sample, property)) === null || _Object$getOwnPropert2 === void 0 ? void 0 : _Object$getOwnPropert2.value) ?? this.sample[property];
const otherValue = ((_Object$getOwnPropert3 = Object.getOwnPropertyDescriptor(other, property)) === null || _Object$getOwnPropert3 === void 0 ? void 0 : _Object$getOwnPropert3.value) ?? other[property];
const value = this.sample[property];
const otherValue = other[property];
if (!equals(value, otherValue, customTesters)) {
result = false;
break;
@@ -987,9 +1042,8 @@ class SchemaMatching extends AsymmetricMatcher {
return "object";
}
toAsymmetricMatcher() {
var _this$result;
const { utils } = this.getMatcherContext();
const issues = ((_this$result = this.result) === null || _this$result === void 0 ? void 0 : _this$result.issues) || [];
const issues = this.result?.issues || [];
if (issues.length > 0) {
return `${this.toString()} ${utils.stringify(this.result, undefined, { printBasicPrototype: false })}`;
}
@@ -1017,13 +1071,14 @@ const JestAsymmetricMatchers = (chai, utils) => {
};
function createAssertionMessage(util, assertion, hasArgs) {
const soft = util.flag(assertion, "soft") ? ".soft" : "";
const not = util.flag(assertion, "negate") ? "not." : "";
const name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`;
const promiseName = util.flag(assertion, "promise");
const promise = promiseName ? `.${promiseName}` : "";
return `expect(actual)${promise}.${not}${name}`;
return `expect${soft}(actual)${promise}.${not}${name}`;
}
function recordAsyncExpect(_test, promise, assertion, error) {
function recordAsyncExpect(_test, promise, assertion, error, isSoft) {
const test = _test;
// record promise for test, that resolves before test ends
if (test && promise instanceof Promise) {
@@ -1041,17 +1096,23 @@ function recordAsyncExpect(_test, promise, assertion, error) {
if (!test.promises) {
test.promises = [];
}
// setup `expect.soft` handler here instead of `wrapAssertion`
// to avoid double error tracking while keeping non-await promise detection.
if (isSoft) {
promise = promise.then(noop, (err) => {
handleTestError(test, err);
});
}
test.promises.push(promise);
let resolved = false;
test.onFinished ?? (test.onFinished = []);
test.onFinished ??= [];
test.onFinished.push(() => {
if (!resolved) {
var _vitest_worker__;
const processor = ((_vitest_worker__ = globalThis.__vitest_worker__) === null || _vitest_worker__ === void 0 ? void 0 : _vitest_worker__.onFilterStackTrace) || ((s) => s || "");
const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || "");
const stack = processor(error.stack);
console.warn([
`Promise returned by \`${assertion}\` was not awaited. `,
"Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
"Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in the next Vitest major. ",
"Please remember to await the assertion.\n",
stack
].join(""));
@@ -1063,9 +1124,11 @@ function recordAsyncExpect(_test, promise, assertion, error) {
return promise.then(onFulfilled, onRejected);
},
catch(onRejected) {
resolved = true;
return promise.catch(onRejected);
},
finally(onFinally) {
resolved = true;
return promise.finally(onFinally);
},
[Symbol.toStringTag]: "Promise"
@@ -1074,12 +1137,12 @@ function recordAsyncExpect(_test, promise, assertion, error) {
return promise;
}
function handleTestError(test, err) {
var _test$result;
test.result || (test.result = { state: "fail" });
test.result ||= { state: "fail" };
test.result.state = "fail";
(_test$result = test.result).errors || (_test$result.errors = []);
test.result.errors ||= [];
test.result.errors.push(processError(err));
}
/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */
function wrapAssertion(utils, name, fn) {
return function(...args) {
// private
@@ -1087,7 +1150,11 @@ function wrapAssertion(utils, name, fn) {
utils.flag(this, "_name", name);
}
if (!utils.flag(this, "soft")) {
return fn.apply(this, args);
// avoid WebKit's proper tail call to preserve stacktrace offset for inline snapshot
// https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit
try {
return fn.apply(this, args);
} finally {}
}
const test = utils.flag(this, "vitest-test");
if (!test) {
@@ -1437,15 +1504,15 @@ const JestChaiExpect = (chai, utils) => {
throw new AssertionError(formatCalls(spy, msg, args));
}
});
def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
def("toHaveBeenNthCalledWith", function(times, ...args) {
const spy = getSpy(this);
const spyName = spy.getMockName();
const nthCall = spy.mock.calls[times - 1];
const callCount = spy.mock.calls.length;
const isCalled = times <= callCount;
this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled);
this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinal(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinal(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled);
});
def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
def("toHaveBeenLastCalledWith", function(...args) {
const spy = getSpy(this);
const spyName = spy.getMockName();
const lastCall = spy.mock.calls.at(-1);
@@ -1516,7 +1583,7 @@ const JestChaiExpect = (chai, utils) => {
const name = expected.name || expected.prototype.constructor.name;
return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown);
}
if (expected instanceof Error) {
if (isError(expected)) {
const equal = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown);
}
@@ -1524,7 +1591,8 @@ const JestChaiExpect = (chai, utils) => {
const matcher = expected;
return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher, thrown);
}
throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`);
const equal = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected a thrown value to equal #{exp}", "expected a thrown value not to equal #{exp}", expected, thrown);
});
[{
name: "toHaveResolved",
@@ -1592,7 +1660,7 @@ const JestChaiExpect = (chai, utils) => {
},
action: "resolve"
}, {
name: ["toHaveLastReturnedWith", "lastReturnedWith"],
name: "toHaveLastReturnedWith",
condition: (spy, value) => {
const result = spy.mock.results.at(-1);
return Boolean(result && result.type === "return" && equals(result.value, value));
@@ -1604,7 +1672,7 @@ const JestChaiExpect = (chai, utils) => {
const results = action === "return" ? spy.mock.results : spy.mock.settledResults;
const result = results.at(-1);
const spyName = spy.getMockName();
this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value);
this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
});
[{
@@ -1615,7 +1683,7 @@ const JestChaiExpect = (chai, utils) => {
},
action: "resolve"
}, {
name: ["toHaveNthReturnedWith", "nthReturnedWith"],
name: "toHaveNthReturnedWith",
condition: (spy, index, value) => {
const result = spy.mock.results[index - 1];
return result && result.type === "return" && equals(result.value, value);
@@ -1627,8 +1695,8 @@ const JestChaiExpect = (chai, utils) => {
const spyName = spy.getMockName();
const results = action === "return" ? spy.mock.results : spy.mock.settledResults;
const result = results[nthCall - 1];
const ordinalCall = `${ordinalOf(nthCall)} call`;
this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value);
const ordinalCall = `${ordinal(nthCall)} call`;
this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
});
// @ts-expect-error @internal
@@ -1647,7 +1715,7 @@ const JestChaiExpect = (chai, utils) => {
if (utils.flag(this, "poll")) {
throw new SyntaxError(`expect.poll() is not supported in combination with .resolves`);
}
if (typeof (obj === null || obj === void 0 ? void 0 : obj.then) !== "function") {
if (typeof obj?.then !== "function") {
throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
}
const proxy = new Proxy(this, { get: (target, key, receiver) => {
@@ -1657,16 +1725,20 @@ const JestChaiExpect = (chai, utils) => {
}
return (...args) => {
utils.flag(this, "_name", key);
const promise = obj.then((value) => {
const promise = Promise.resolve(obj).then((value) => {
utils.flag(this, "object", value);
return result.call(this, ...args);
}, (err) => {
const _error = new AssertionError(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: false });
_error.cause = err;
_error.stack = error.stack.replace(error.message, _error.message);
throw _error;
}).catch((err) => {
if (isError(err) && error.stack) {
err.stack = error.stack.replace(error.message, err.message);
}
throw err;
});
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error);
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
@@ -1681,7 +1753,7 @@ const JestChaiExpect = (chai, utils) => {
if (utils.flag(this, "poll")) {
throw new SyntaxError(`expect.poll() is not supported in combination with .rejects`);
}
if (typeof (wrapper === null || wrapper === void 0 ? void 0 : wrapper.then) !== "function") {
if (typeof wrapper?.then !== "function") {
throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
}
const proxy = new Proxy(this, { get: (target, key, receiver) => {
@@ -1691,42 +1763,32 @@ const JestChaiExpect = (chai, utils) => {
}
return (...args) => {
utils.flag(this, "_name", key);
const promise = wrapper.then((value) => {
const promise = Promise.resolve(wrapper).then((value) => {
const _error = new AssertionError(`promise resolved "${utils.inspect(value)}" instead of rejecting`, {
showDiff: true,
expected: new Error("rejected promise"),
actual: value
});
_error.stack = error.stack.replace(error.message, _error.message);
throw _error;
}, (err) => {
utils.flag(this, "object", err);
return result.call(this, ...args);
}).catch((err) => {
if (isError(err) && error.stack) {
err.stack = error.stack.replace(error.message, err.message);
}
throw err;
});
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error);
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
});
};
function ordinalOf(i) {
const j = i % 10;
const k = i % 100;
if (j === 1 && k !== 11) {
return `${i}st`;
}
if (j === 2 && k !== 12) {
return `${i}nd`;
}
if (j === 3 && k !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
function formatCalls(spy, msg, showActualCall) {
if (spy.mock.calls.length) {
msg += c.gray(`\n\nReceived: \n\n${spy.mock.calls.map((callArg, i) => {
let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:\n\n`);
msg += c.gray(`\n\nReceived:\n\n${spy.mock.calls.map((callArg, i) => {
let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call:\n\n`);
if (showActualCall) {
methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true });
} else {
@@ -1741,8 +1803,8 @@ function formatCalls(spy, msg, showActualCall) {
}
function formatReturns(spy, results, msg, showActualReturn) {
if (results.length) {
msg += c.gray(`\n\nReceived: \n\n${results.map((callReturn, i) => {
let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return:\n\n`);
msg += c.gray(`\n\nReceived:\n\n${results.map((callReturn, i) => {
let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call return:\n\n`);
if (showActualReturn) {
methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true });
} else {
@@ -1769,13 +1831,12 @@ function getMatcherState(assertion, expect) {
subsetEquality
};
let task = util.flag(assertion, "vitest-test");
const currentTestName = (task === null || task === void 0 ? void 0 : task.fullTestName) ?? "";
if ((task === null || task === void 0 ? void 0 : task.type) !== "test") {
const currentTestName = task?.fullTestName ?? "";
if (task?.type !== "test") {
task = undefined;
}
const matcherState = {
...getState(expect),
task,
currentTestName,
customTesters: getCustomEqualityTesters(),
isNot,
@@ -1784,8 +1845,10 @@ function getMatcherState(assertion, expect) {
equals,
suppressedErrors: [],
soft: util.flag(assertion, "soft"),
poll: util.flag(assertion, "poll")
poll: util.flag(assertion, "poll"),
assertion
};
Object.assign(matcherState, { task });
return {
state: matcherState,
isNot,
@@ -1794,36 +1857,50 @@ function getMatcherState(assertion, expect) {
};
}
class JestExtendError extends Error {
constructor(message, actual, expected) {
constructor(message, actual, expected, __vitest_error_context__) {
super(message);
this.actual = actual;
this.expected = expected;
this.__vitest_error_context__ = __vitest_error_context__;
}
}
function JestExtendPlugin(c, expect, matchers) {
return (_, utils) => {
Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
function expectWrapper(...args) {
function __VITEST_EXTEND_ASSERTION__(...args) {
const { state, isNot, obj, customMessage } = getMatcherState(this, expect);
const result = expectAssertion.call(state, obj, ...args);
if (result && typeof result === "object" && typeof result.then === "function") {
const thenable = result;
return thenable.then(({ pass, message, actual, expected }) => {
return thenable.then(({ pass, message, actual, expected, meta }) => {
if (pass && isNot || !pass && !isNot) {
const errorMessage = customMessage != null ? customMessage : message();
throw new JestExtendError(errorMessage, actual, expected);
const errorMessage = (customMessage ? `${customMessage}: ` : "") + message();
throw new JestExtendError(errorMessage, actual, expected, {
assertionName: expectAssertionName,
meta
});
}
});
}
const { pass, message, actual, expected } = result;
const { pass, message, actual, expected, meta } = result;
if (pass && isNot || !pass && !isNot) {
const errorMessage = customMessage != null ? customMessage : message();
throw new JestExtendError(errorMessage, actual, expected);
const errorMessage = (customMessage ? `${customMessage}: ` : "") + message();
throw new JestExtendError(errorMessage, actual, expected, {
assertionName: expectAssertionName,
meta
});
}
}
const softWrapper = wrapAssertion(utils, expectAssertionName, expectWrapper);
const softWrapper = wrapAssertion(utils, expectAssertionName, __VITEST_EXTEND_ASSERTION__);
utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper);
utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper);
// `expect.poll()` inspects the installed Chai assertion method,
// so copy the internal marker from the original matcher function.
// this is only for domain snapshot matchers for now.
if (expectAssertion.__vitest_poll_takeover__) {
const addedMethod = c.Assertion.prototype[expectAssertionName];
Object.defineProperty(addedMethod, "__vitest_poll_takeover__", { value: true });
}
class CustomMatcher extends AsymmetricMatcher {
constructor(inverse = false, ...sample) {
super(sample, inverse);
@@ -1872,4 +1949,4 @@ const JestExtend = (chai, utils) => {
});
};
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion };
+14 -8
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/expect",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Jest's expect matchers as a Chai plugin",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme",
"homepage": "https://vitest.dev/api/expect",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,12 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"chai",
"assertion"
],
"sideEffects": false,
"exports": {
".": {
@@ -29,15 +35,15 @@
"dist"
],
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"chai": "^6.2.1",
"tinyrainbow": "^3.0.3",
"@vitest/spy": "4.0.18",
"@vitest/utils": "4.0.18"
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0",
"@vitest/spy": "4.1.9",
"@vitest/utils": "4.1.9"
},
"devDependencies": {
"@vitest/runner": "4.0.18"
"@vitest/runner": "4.1.9"
},
"scripts": {
"build": "premove dist && rollup -c",
+2
View File
@@ -1,5 +1,7 @@
# @vitest/mocker
[![NPM version](https://img.shields.io/npm/v/@vitest/mocker?color=a1b858&label=)](https://npmx.dev/package/@vitest/mocker)
Vitest's module mocker implementation.
[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md)
+1
View File
@@ -1,6 +1,7 @@
import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
import { registerModuleMocker } from './register.js';
import './chunk-mocker.js';
import './chunk-helpers.js';
import './index.js';
import './chunk-registry.js';
import './chunk-pathe.M-eThtNZ.js';
+1
View File
@@ -5,6 +5,7 @@ interface AutomockOptions {
* @default "__vitest_mocker__"
*/
globalThisAccessor?: string;
id?: string;
}
declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString;
+5
View File
@@ -1,3 +1,8 @@
import 'node:fs';
import 'node:url';
import 'magic-string';
export { a as automockModule } from './chunk-automock.js';
import 'estree-walker';
import 'node:module';
import 'node:path';
import './chunk-helpers.js';
+4 -4
View File
@@ -1,9 +1,9 @@
import { M as ModuleMockerInterceptor } from './mocker.d-TnKRhz7N.js';
export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, d as ModuleMockerConfig, e as ModuleMockerRPC, R as ResolveIdResult, f as ResolveMockResult, c as createCompilerHints } from './mocker.d-TnKRhz7N.js';
import { M as ModuleMockerInterceptor } from './mocker.d-QEntlm6J.js';
export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, c as ModuleMockerConfig, d as ModuleMockerRPC, R as ResolveIdResult, e as ResolveMockResult, f as createCompilerHints } from './mocker.d-QEntlm6J.js';
import { StartOptions, SetupWorker } from 'msw/browser';
import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js';
import { M as MockerRegistry, a as MockedModule } from './types.d-BjI5eAwu.js';
import '@vitest/spy';
import './index.d-C-sLYZi-.js';
import './index.d-B41z0AuW.js';
interface ModuleMockerMSWInterceptorOptions {
/**
+1
View File
@@ -2,6 +2,7 @@ export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js';
import { M as MockerRegistry } from './chunk-registry.js';
import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js';
export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
import './chunk-helpers.js';
import './index.js';
import './chunk-pathe.M-eThtNZ.js';
+187 -15
View File
File diff suppressed because one or more lines are too long
+44
View File
@@ -0,0 +1,44 @@
/**
* Get original stacktrace without source map support the most performant way.
* - Create only 1 stack frame.
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
*/
function createSimpleStackTrace(options) {
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
const limit = Error.stackTraceLimit;
const prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
Error.prepareStackTrace = (e) => e.stack;
const err = new Error(message);
const stackTrace = err.stack || "";
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = limit;
return stackTrace;
}
function filterOutComments(s) {
const result = [];
let commentState = "none";
for (let i = 0; i < s.length; ++i) {
if (commentState === "singleline") {
if (s[i] === "\n") {
commentState = "none";
}
} else if (commentState === "multiline") {
if (s[i - 1] === "*" && s[i] === "/") {
commentState = "none";
}
} else if (commentState === "none") {
if (s[i] === "/" && s[i + 1] === "/") {
commentState = "singleline";
} else if (s[i] === "/" && s[i + 1] === "*") {
commentState = "multiline";
i += 2;
} else {
result.push(s[i]);
}
}
}
return result.join("");
}
export { createSimpleStackTrace as c, filterOutComments as f };
+665
View File
@@ -0,0 +1,665 @@
import MagicString from 'magic-string';
import { e as esmWalker } from './chunk-automock.js';
// AST walker module for ESTree compatible trees
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
visitNode(baseVisitor, type, node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
function visitNode(baseVisitor, type, node, st, c) {
if (baseVisitor[type] == null) { throw new Error(("No walker function defined for node type " + type)) }
baseVisitor[type](node, st, c);
}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i = 0, list = node.cases; i < list.length; i += 1) {
var cs = list[i];
c(cs, st);
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
if (node.attributes)
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
{
var attr = list[i];
c(attr, st);
} }
};
base.ExportAllDeclaration = function (node, st, c) {
if (node.exported)
{ c(node.exported, st); }
c(node.source, st, "Expression");
if (node.attributes)
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
{
var attr = list[i];
c(attr, st);
} }
};
base.ImportAttribute = function (node, st, c) {
c(node.value, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
if (node.attributes)
{ for (var i$1 = 0, list$1 = node.attributes; i$1 < list$1.length; i$1 += 1)
{
var attr = list$1[i$1];
c(attr, st);
} }
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
if (node.options) { c(node.options, st, "Expression"); }
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
if (node.value) { c(node.value, st, "Expression"); }
};
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
To fix this issue you can either:
- import the mocks API directly from 'vitest'
- enable the 'globals' option`;
function API_NOT_FOUND_CHECK(names) {
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function getNodeTail(code, node) {
let end = node.end;
if (code[node.end] === ";") {
end += 1;
}
if (code[node.end] === "\n") {
return end + 1;
}
if (code[node.end + 1] === "\n") {
end += 1;
}
return end;
}
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
const hashbangRE = /^#!.*\n/;
// Public redistributions of Vitest that re-export its mocking API (`vi`)
// verbatim under their own specifier. Imports from these are treated as the
// hoisted module so `vi.mock()` is hoisted for e.g.
// `import { vi } from 'vite-plus/test'`, exactly as it is for `vitest`.
const REDISTRIBUTED_HOISTED_MODULES = ["vite-plus/test"];
// this is a fork of Vite SSR transform
function hoistMocks(code, id, parse, options = {}) {
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
if (!needHoisting) {
return;
}
const s = options.magicString?.() || new MagicString(code);
let ast;
try {
ast = parse(code);
} catch (err) {
console.error(`Cannot parse ${id}:\n${err.message}.`);
return;
}
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
"mock",
"unmock",
"doMock",
"doUnmock"
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
// hoist at the start of the file, after the hashbang
const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0;
let hoistIndex = hashbangEnd;
let hoistedModuleImported = false;
let uid = 0;
const idToImportMap = new Map();
const imports = [];
// this will transform import statements into dynamic ones, if there are imports
// it will keep the import as is, if we don't need to mock anything
// in browser environment it will wrap the module value with "vitest_wrap_module" function
// that returns a proxy to the module so that named exports can be mocked
function defineImport(importNode) {
const source = importNode.source.value;
// always hoist vitest import to top of the file, so
// "vi" helpers can access it. Vitest redistributions that re-export the
// mocking API under their own specifier are recognized the same way.
if (hoistedModule === source || REDISTRIBUTED_HOISTED_MODULES.includes(source)) {
hoistedModuleImported = true;
return;
}
const importId = `__vi_import_${uid++}__`;
imports.push({
id: importId,
node: importNode
});
return importId;
}
// 1. check all import statements and record id -> importName map
for (const node of ast.body) {
// import foo from 'foo' --> foo -> __import_foo__.default
// import { baz } from 'foo' --> baz -> __import_foo__.baz
// import * as ok from 'foo' --> ok -> __import_foo__
if (node.type === "ImportDeclaration") {
const importId = defineImport(node);
if (!importId) {
continue;
}
for (const spec of node.specifiers) {
if (spec.type === "ImportSpecifier") {
if (spec.imported.type === "Identifier") {
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
} else {
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
}
} else if (spec.type === "ImportDefaultSpecifier") {
idToImportMap.set(spec.local.name, `${importId}.default`);
} else {
// namespace specifier
idToImportMap.set(spec.local.name, importId);
}
}
}
}
const declaredConst = new Set();
const hoistedNodes = new Set();
function createSyntaxError(node, message) {
const _error = new SyntaxError(message);
Error.captureStackTrace(_error, createSyntaxError);
const serializedError = {
name: "SyntaxError",
message: _error.message,
stack: _error.stack
};
if (options.codeFrameGenerator) {
serializedError.frame = options.codeFrameGenerator(node, id, code);
}
return serializedError;
}
function assertNotDefaultExport(node, error) {
const defaultExport = findNodeAround(ast, node.start, "ExportDefaultDeclaration")?.node;
if (defaultExport?.declaration === node || defaultExport?.declaration.type === "AwaitExpression" && defaultExport.declaration.argument === node) {
throw createSyntaxError(defaultExport, error);
}
}
function assertNotNamedExport(node, error) {
const nodeExported = findNodeAround(ast, node.start, "ExportNamedDeclaration")?.node;
if (nodeExported?.declaration === node) {
throw createSyntaxError(nodeExported, error);
}
}
function getVariableDeclaration(node) {
const declarationNode = findNodeAround(ast, node.start, "VariableDeclaration")?.node;
const init = declarationNode?.declarations[0]?.init;
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
return declarationNode;
}
}
const usedUtilityExports = new Set();
let hasImportMetaVitest = false;
esmWalker(ast, {
onImportMeta(node) {
const property = code.slice(node.end, node.end + 7);
if (property === ".vitest") {
hasImportMetaVitest = true;
}
},
onIdentifier(id, info, parentStack) {
const binding = idToImportMap.get(id.name);
if (!binding) {
return;
}
if (info.hasBindingShortcut) {
s.appendLeft(id.end, `: ${binding}`);
} else if (info.classDeclaration) {
if (!declaredConst.has(id.name)) {
declaredConst.add(id.name);
// locate the top-most node containing the class declaration
const topNode = parentStack[parentStack.length - 2];
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
}
} else if (!info.classExpression) {
s.update(id.start, id.end, binding);
}
},
onDynamicImport(_node) {
// TODO: vi.mock(import) breaks it, and vi.mock('', () => import) also does,
// only move imports that are outside of vi.mock
// backwards compat, don't do if not passed
// if (!options.globalThisAccessor) {
// return
// }
// const globalThisAccessor = options.globalThisAccessor
// const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`
// const importSubstring = code.substring(node.start, node.end)
// const hasIgnore = importSubstring.includes('/* @vite-ignore */')
// s.overwrite(
// node.start,
// (node.source as Positioned<Expression>).start,
// replaceString + (hasIgnore ? '/* @vite-ignore */ ' : ''),
// )
// s.overwrite(node.end - 1, node.end, '))')
},
onCallExpression(node) {
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
const methodName = node.callee.property.name;
usedUtilityExports.add(node.callee.object.name);
if (hoistableMockMethodNames.includes(methodName)) {
const method = `${node.callee.object.name}.${methodName}`;
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
}
// rewrite vi.mock(import('..')) into vi.mock('..')
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
const moduleInfo = node.arguments[0];
// vi.mock(import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "ImportExpression") {
const source = moduleInfo.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
// vi.mock(await import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
const source = moduleInfo.argument.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
hoistedNodes.add(node);
} else if (dynamicImportMockMethodNames.includes(methodName)) {
const moduleInfo = node.arguments[0];
let source = null;
if (moduleInfo.type === "ImportExpression") {
source = moduleInfo.source;
}
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
source = moduleInfo.argument.source;
}
if (source) {
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
if (hoistedMethodNames.includes(methodName)) {
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
// hoist "const variable = vi.hoisted(() => {})"
hoistedNodes.add(declarationNode);
} else {
const awaitedExpression = findNodeAround(ast, node.start, "AwaitExpression")?.node;
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
const moveNode = awaitedExpression?.argument === node ? awaitedExpression : node;
hoistedNodes.add(moveNode);
}
}
}
}
});
function getNodeName(node) {
const callee = node.callee || {};
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
const argument = node.arguments[0];
const argStr = argument.type === "Literal" || argument.type === "ImportExpression" ? code.slice(argument.start, argument.end) : "";
return `${callee.object.name}.${callee.property.name}(${argStr})`;
}
return "\"hoisted method\"";
}
function getNodeCall(node) {
if (node.type === "CallExpression") {
return node;
}
if (node.type === "VariableDeclaration") {
const { declarations } = node;
const init = declarations[0].init;
if (init) {
return getNodeCall(init);
}
}
if (node.type === "AwaitExpression") {
const { argument } = node;
if (argument.type === "CallExpression") {
return getNodeCall(argument);
}
}
return node;
}
function createError(outsideNode, insideNode) {
const outsideCall = getNodeCall(outsideNode);
const insideCall = getNodeCall(insideNode);
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
}
// validate hoistedNodes doesn't have nodes inside other nodes
const arrayNodes = Array.from(hoistedNodes);
for (let i = 0; i < arrayNodes.length; i++) {
const node = arrayNodes[i];
for (let j = i + 1; j < arrayNodes.length; j++) {
const otherNode = arrayNodes[j];
if (node.start >= otherNode.start && node.end <= otherNode.end) {
throw createError(otherNode, node);
}
if (otherNode.start >= node.start && otherNode.end <= node.end) {
throw createError(node, otherNode);
}
}
}
// validate that hoisted nodes are defined on the top level
// ignore `import.meta.vitest` because it needs to be inside an IfStatement
// and it can be used anywhere in the code (inside methods too)
if (!hasImportMetaVitest) {
for (const node of ast.body) {
hoistedNodes.delete(node);
if (node.type === "ExpressionStatement") {
hoistedNodes.delete(node.expression);
}
}
for (const invalidNode of hoistedNodes) {
console.warn(`Warning: A ${getNodeName(getNodeCall(invalidNode))} call in "${id}" is not at the top level of the module. ` + `Although it appears nested, it will be hoisted and executed before any tests run. ` + `Move it to the top level to reflect its actual execution order. This will become an error in a future version.\n` + `See: https://vitest.dev/guide/mocking/modules#how-it-works`);
}
}
// hoist vi.mock/vi.hoisted
for (const node of arrayNodes) {
const end = getNodeTail(code, node);
// don't hoist into itself if it's already at the top
if (hoistIndex === end || hoistIndex === node.start) {
hoistIndex = end;
} else {
s.move(node.start, end, hoistIndex);
}
}
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
for (const { node: importNode, id: importId } of imports) {
const source = importNode.source.value;
const sourceString = JSON.stringify(source);
let importLine = `const ${importId} = await `;
if (options.globalThisAccessor) {
importLine += `globalThis[${options.globalThisAccessor}].wrapDynamicImport(() => import(${sourceString}));\n`;
} else {
importLine += `import(${sourceString});\n`;
}
s.update(importNode.start, importNode.end, importLine);
if (importNode.start === hoistIndex) {
// no need to hoist, but update hoistIndex to keep the order
hoistIndex = importNode.end;
} else {
// There will be an error if the module is called before it is imported,
// so the module import statement is hoisted to the top
s.move(importNode.start, importNode.end, hoistIndex);
}
}
if (!hoistedModuleImported && arrayNodes.length > 0) {
const utilityImports = [...usedUtilityExports];
// "vi" or "vitest" is imported from a module other than "vitest"
if (utilityImports.some((name) => idToImportMap.has(name))) {
s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports));
} else if (utilityImports.length) {
s.appendLeft(hashbangEnd, `import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
}
}
return s;
}
export { hoistMocks as h };
+41 -30
View File
@@ -1,25 +1,8 @@
import { c as createSimpleStackTrace } from './chunk-helpers.js';
import { mockObject } from './index.js';
import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js';
import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js';
/**
* Get original stacktrace without source map support the most performant way.
* - Create only 1 stack frame.
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
*/
function createSimpleStackTrace(options) {
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
const limit = Error.stackTraceLimit;
const prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
Error.prepareStackTrace = (e) => e.stack;
const err = new Error(message);
const stackTrace = err.stack || "";
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = limit;
return stackTrace;
}
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
@@ -126,6 +109,8 @@ for (let i = 0; i < chars.length; i++) {
}
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (!urlLike.includes(":")) {
@@ -150,6 +135,9 @@ function extractLocation(urlLike) {
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows ? 5 : 4);
}
if (url.includes("vitest=")) {
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
}
return [
url,
parts[2] || undefined,
@@ -243,7 +231,7 @@ function parseSingleV8Stack(raw) {
// normalize Windows path (\ -> /)
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
if (method) {
method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
}
return {
method,
@@ -254,7 +242,7 @@ function parseSingleV8Stack(raw) {
}
function createCompilerHints(options) {
const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__";
const globalThisAccessor = options?.globalThisKey || "__vitest_mocker__";
function _mocker() {
// @ts-expect-error injected by the plugin
return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) {
@@ -310,7 +298,7 @@ function getImporter(name) {
return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
});
const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]);
return (stack === null || stack === void 0 ? void 0 : stack.file) || "";
return stack?.file || "";
}
const hot = import.meta.hot || {
@@ -385,7 +373,7 @@ class ModuleMocker {
throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
}
const ext = extname(resolved.id);
const url = new URL(resolved.url, location.href);
const url = new URL(resolved.url, this.getBaseUrl());
const query = `_vitest_original&ext${ext}`;
const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`;
return this.wrapDynamicImport(() => import(
@@ -397,12 +385,15 @@ class ModuleMocker {
}
// vite injects this helper for optimized modules, so we try to follow the same behavior
const m = mod.default;
return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : {
return m?.__esModule ? m : {
...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
default: m
};
});
}
getBaseUrl() {
return location.href;
}
async importMock(rawId, importer) {
await this.prepare();
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
@@ -410,7 +401,7 @@ class ModuleMocker {
let mock = this.registry.get(mockUrl);
if (!mock) {
if (redirectUrl) {
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString();
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
} else {
mock = new AutomockedModule(rawId, resolvedId, mockUrl);
@@ -420,7 +411,7 @@ class ModuleMocker {
return await mock.resolve();
}
if (mock.type === "automock" || mock.type === "autospy") {
const url = new URL(`/@id/${resolvedId}`, location.href);
const url = new URL(`/@id/${resolvedId}`, this.getBaseUrl());
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`;
const moduleObject = await import(
/* @vite-ignore */
@@ -433,8 +424,16 @@ class ModuleMocker {
mock.redirect
);
}
mockObject(object, moduleType = "automock") {
return mockObject({
mockObject(object, mockExportsOrModuleType, moduleType) {
let mockExports;
if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
moduleType = mockExportsOrModuleType;
mockExports = undefined;
} else {
mockExports = mockExportsOrModuleType;
}
moduleType ??= "automock";
const result = mockObject({
globalConstructors: {
Object,
Function,
@@ -444,10 +443,14 @@ class ModuleMocker {
},
createMockInstance: this.createMockInstance,
type: moduleType
}, object);
}, object, mockExports);
return result;
}
getMockContext() {
return { callstack: null };
}
queueMock(rawId, importer, factoryOrOptions) {
const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : factoryOrOptions?.spy ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
this.mockedIds.add(resolvedId);
const factory = typeof factoryOrOptions === "function" ? async () => {
@@ -456,7 +459,7 @@ class ModuleMocker {
// merges all exports from default into the module object
return needsInterop ? { default: data } : data;
} : undefined;
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null;
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString() : null;
let module;
if (mockType === "manual") {
module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
@@ -500,6 +503,14 @@ class ModuleMocker {
}
return moduleFactory;
}
getMockedModuleById(id) {
return this.registry.getById(id);
}
reset() {
this.registry.clear();
this.mockedIds.clear();
this.queue.clear();
}
resolveMockPath(path) {
const config = this.config;
const fsRoot = join("/@fs/", config.root);
+21 -7
View File
@@ -152,21 +152,25 @@ class ManualMockedModule {
this.url = url;
this.factory = factory;
}
async resolve() {
resolve() {
if (this.cache) {
return this.cache;
}
let exports$1;
try {
exports$1 = await this.factory();
exports$1 = this.factory();
} catch (err) {
const vitestError = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock");
vitestError.cause = err;
throw vitestError;
throw createHelpfulError(err);
}
if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
if (typeof exports$1 === "object" && typeof exports$1?.then === "function") {
return exports$1.then((result) => {
assertValidExports(this.raw, result);
return this.cache = result;
}, (error) => {
throw createHelpfulError(error);
});
}
assertValidExports(this.raw, exports$1);
return this.cache = exports$1;
}
static fromJSON(data, factory) {
@@ -181,5 +185,15 @@ class ManualMockedModule {
};
}
}
function createHelpfulError(cause) {
const error = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock");
error.cause = cause;
return error;
}
function assertValidExports(raw, exports$1) {
if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
throw new TypeError(`[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
}
}
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b };
+18 -7
View File
@@ -3,14 +3,25 @@ function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") {
const source = `const module = globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");`;
const keys = exports$1.map((name) => {
if (name === "default") {
return `export default module["default"];`;
}
return `export const ${name} = module["${name}"];`;
const source = `
const __factoryModule__ = await globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");
`;
const keys = exports$1.map((name, index) => {
return `let __${index} = __factoryModule__["${name}"]
export { __${index} as "${name}" }`;
}).join("\n");
return `${source}\n${keys}`;
let code = `${source}\n${keys}`;
// this prevents recursion
code += `
if (__factoryModule__.__factoryPromise != null) {
__factoryModule__.__factoryPromise.then((resolvedModule) => {
${exports$1.map((name, index) => {
return `__${index} = resolvedModule["${name}"];`;
}).join("\n")}
})
}
`;
return code;
}
export { cleanUrl as a, createManualModuleSource as c };
+739
View File
@@ -0,0 +1,739 @@
import MagicString from 'magic-string';
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
// This definition file follows a somewhat unusual format. ESTree allows
// runtime type checks based on the `type` parameter. In order to explain this
// to typescript we want to use discriminated union types:
// https://github.com/Microsoft/TypeScript/pull/9163
//
// For ESTree this is a bit tricky because the high level interfaces like
// Node or Function are pulling double duty. We want to pass common fields down
// to the interfaces that extend them (like Identifier or
// ArrowFunctionExpression), but you can't extend a type union or enforce
// common fields on them. So we've split the high level interfaces into two
// types, a base type which passes down inherited fields, and a type union of
// all types which extend the base type. Only the type union is exported, and
// the union is how other types refer to the collection of inheriting types.
//
// This makes the definitions file here somewhat more difficult to maintain,
// but it has the notable advantage of making ESTree much easier to use as
// an end user.
interface BaseNodeWithoutComments {
// Every leaf interface that extends BaseNode must specify a type property.
// The type property should be a string literal. For example, Identifier
// has: `type: "Identifier"`
type: string;
loc?: SourceLocation | null | undefined;
range?: [number, number] | undefined;
}
interface BaseNode extends BaseNodeWithoutComments {
leadingComments?: Comment[] | undefined;
trailingComments?: Comment[] | undefined;
}
interface NodeMap {
AssignmentProperty: AssignmentProperty;
CatchClause: CatchClause;
Class: Class;
ClassBody: ClassBody;
Expression: Expression;
Function: Function;
Identifier: Identifier;
Literal: Literal;
MethodDefinition: MethodDefinition;
ModuleDeclaration: ModuleDeclaration;
ModuleSpecifier: ModuleSpecifier;
Pattern: Pattern;
PrivateIdentifier: PrivateIdentifier;
Program: Program;
Property: Property;
PropertyDefinition: PropertyDefinition;
SpreadElement: SpreadElement;
Statement: Statement;
Super: Super;
SwitchCase: SwitchCase;
TemplateElement: TemplateElement;
VariableDeclarator: VariableDeclarator;
}
type Node$1 = NodeMap[keyof NodeMap];
interface Comment extends BaseNodeWithoutComments {
type: "Line" | "Block";
value: string;
}
interface SourceLocation {
source?: string | null | undefined;
start: Position;
end: Position;
}
interface Position {
/** >= 1 */
line: number;
/** >= 0 */
column: number;
}
interface Program extends BaseNode {
type: "Program";
sourceType: "script" | "module";
body: Array<Directive | Statement | ModuleDeclaration>;
comments?: Comment[] | undefined;
}
interface Directive extends BaseNode {
type: "ExpressionStatement";
expression: Literal;
directive: string;
}
interface BaseFunction extends BaseNode {
params: Pattern[];
generator?: boolean | undefined;
async?: boolean | undefined;
// The body is either BlockStatement or Expression because arrow functions
// can have a body that's either. FunctionDeclarations and
// FunctionExpressions have only BlockStatement bodies.
body: BlockStatement | Expression;
}
type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
type Statement =
| ExpressionStatement
| BlockStatement
| StaticBlock
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| Declaration;
interface BaseStatement extends BaseNode {}
interface EmptyStatement extends BaseStatement {
type: "EmptyStatement";
}
interface BlockStatement extends BaseStatement {
type: "BlockStatement";
body: Statement[];
innerComments?: Comment[] | undefined;
}
interface StaticBlock extends Omit<BlockStatement, "type"> {
type: "StaticBlock";
}
interface ExpressionStatement extends BaseStatement {
type: "ExpressionStatement";
expression: Expression;
}
interface IfStatement extends BaseStatement {
type: "IfStatement";
test: Expression;
consequent: Statement;
alternate?: Statement | null | undefined;
}
interface LabeledStatement extends BaseStatement {
type: "LabeledStatement";
label: Identifier;
body: Statement;
}
interface BreakStatement extends BaseStatement {
type: "BreakStatement";
label?: Identifier | null | undefined;
}
interface ContinueStatement extends BaseStatement {
type: "ContinueStatement";
label?: Identifier | null | undefined;
}
interface WithStatement extends BaseStatement {
type: "WithStatement";
object: Expression;
body: Statement;
}
interface SwitchStatement extends BaseStatement {
type: "SwitchStatement";
discriminant: Expression;
cases: SwitchCase[];
}
interface ReturnStatement extends BaseStatement {
type: "ReturnStatement";
argument?: Expression | null | undefined;
}
interface ThrowStatement extends BaseStatement {
type: "ThrowStatement";
argument: Expression;
}
interface TryStatement extends BaseStatement {
type: "TryStatement";
block: BlockStatement;
handler?: CatchClause | null | undefined;
finalizer?: BlockStatement | null | undefined;
}
interface WhileStatement extends BaseStatement {
type: "WhileStatement";
test: Expression;
body: Statement;
}
interface DoWhileStatement extends BaseStatement {
type: "DoWhileStatement";
body: Statement;
test: Expression;
}
interface ForStatement extends BaseStatement {
type: "ForStatement";
init?: VariableDeclaration | Expression | null | undefined;
test?: Expression | null | undefined;
update?: Expression | null | undefined;
body: Statement;
}
interface BaseForXStatement extends BaseStatement {
left: VariableDeclaration | Pattern;
right: Expression;
body: Statement;
}
interface ForInStatement extends BaseForXStatement {
type: "ForInStatement";
}
interface DebuggerStatement extends BaseStatement {
type: "DebuggerStatement";
}
type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
interface BaseDeclaration extends BaseStatement {}
interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
type: "FunctionDeclaration";
/** It is null when a function declaration is a part of the `export default function` statement */
id: Identifier | null;
body: BlockStatement;
}
interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
id: Identifier;
}
interface VariableDeclaration extends BaseDeclaration {
type: "VariableDeclaration";
declarations: VariableDeclarator[];
kind: "var" | "let" | "const" | "using" | "await using";
}
interface VariableDeclarator extends BaseNode {
type: "VariableDeclarator";
id: Pattern;
init?: Expression | null | undefined;
}
interface ExpressionMap {
ArrayExpression: ArrayExpression;
ArrowFunctionExpression: ArrowFunctionExpression;
AssignmentExpression: AssignmentExpression;
AwaitExpression: AwaitExpression;
BinaryExpression: BinaryExpression;
CallExpression: CallExpression;
ChainExpression: ChainExpression;
ClassExpression: ClassExpression;
ConditionalExpression: ConditionalExpression;
FunctionExpression: FunctionExpression;
Identifier: Identifier;
ImportExpression: ImportExpression;
Literal: Literal;
LogicalExpression: LogicalExpression;
MemberExpression: MemberExpression;
MetaProperty: MetaProperty;
NewExpression: NewExpression;
ObjectExpression: ObjectExpression;
SequenceExpression: SequenceExpression;
TaggedTemplateExpression: TaggedTemplateExpression;
TemplateLiteral: TemplateLiteral;
ThisExpression: ThisExpression;
UnaryExpression: UnaryExpression;
UpdateExpression: UpdateExpression;
YieldExpression: YieldExpression;
}
type Expression = ExpressionMap[keyof ExpressionMap];
interface BaseExpression extends BaseNode {}
type ChainElement = SimpleCallExpression | MemberExpression;
interface ChainExpression extends BaseExpression {
type: "ChainExpression";
expression: ChainElement;
}
interface ThisExpression extends BaseExpression {
type: "ThisExpression";
}
interface ArrayExpression extends BaseExpression {
type: "ArrayExpression";
elements: Array<Expression | SpreadElement | null>;
}
interface ObjectExpression extends BaseExpression {
type: "ObjectExpression";
properties: Array<Property | SpreadElement>;
}
interface PrivateIdentifier extends BaseNode {
type: "PrivateIdentifier";
name: string;
}
interface Property extends BaseNode {
type: "Property";
key: Expression | PrivateIdentifier;
value: Expression | Pattern; // Could be an AssignmentProperty
kind: "init" | "get" | "set";
method: boolean;
shorthand: boolean;
computed: boolean;
}
interface PropertyDefinition extends BaseNode {
type: "PropertyDefinition";
key: Expression | PrivateIdentifier;
value?: Expression | null | undefined;
computed: boolean;
static: boolean;
}
interface FunctionExpression extends BaseFunction, BaseExpression {
id?: Identifier | null | undefined;
type: "FunctionExpression";
body: BlockStatement;
}
interface SequenceExpression extends BaseExpression {
type: "SequenceExpression";
expressions: Expression[];
}
interface UnaryExpression extends BaseExpression {
type: "UnaryExpression";
operator: UnaryOperator;
prefix: true;
argument: Expression;
}
interface BinaryExpression extends BaseExpression {
type: "BinaryExpression";
operator: BinaryOperator;
left: Expression | PrivateIdentifier;
right: Expression;
}
interface AssignmentExpression extends BaseExpression {
type: "AssignmentExpression";
operator: AssignmentOperator;
left: Pattern | MemberExpression;
right: Expression;
}
interface UpdateExpression extends BaseExpression {
type: "UpdateExpression";
operator: UpdateOperator;
argument: Expression;
prefix: boolean;
}
interface LogicalExpression extends BaseExpression {
type: "LogicalExpression";
operator: LogicalOperator;
left: Expression;
right: Expression;
}
interface ConditionalExpression extends BaseExpression {
type: "ConditionalExpression";
test: Expression;
alternate: Expression;
consequent: Expression;
}
interface BaseCallExpression extends BaseExpression {
callee: Expression | Super;
arguments: Array<Expression | SpreadElement>;
}
type CallExpression = SimpleCallExpression | NewExpression;
interface SimpleCallExpression extends BaseCallExpression {
type: "CallExpression";
optional: boolean;
}
interface NewExpression extends BaseCallExpression {
type: "NewExpression";
}
interface MemberExpression extends BaseExpression, BasePattern {
type: "MemberExpression";
object: Expression | Super;
property: Expression | PrivateIdentifier;
computed: boolean;
optional: boolean;
}
type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
interface BasePattern extends BaseNode {}
interface SwitchCase extends BaseNode {
type: "SwitchCase";
test?: Expression | null | undefined;
consequent: Statement[];
}
interface CatchClause extends BaseNode {
type: "CatchClause";
param: Pattern | null;
body: BlockStatement;
}
interface Identifier extends BaseNode, BaseExpression, BasePattern {
type: "Identifier";
name: string;
}
type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
interface SimpleLiteral extends BaseNode, BaseExpression {
type: "Literal";
value: string | boolean | number | null;
raw?: string | undefined;
}
interface RegExpLiteral extends BaseNode, BaseExpression {
type: "Literal";
value?: RegExp | null | undefined;
regex: {
pattern: string;
flags: string;
};
raw?: string | undefined;
}
interface BigIntLiteral extends BaseNode, BaseExpression {
type: "Literal";
value?: bigint | null | undefined;
bigint: string;
raw?: string | undefined;
}
type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
type BinaryOperator =
| "=="
| "!="
| "==="
| "!=="
| "<"
| "<="
| ">"
| ">="
| "<<"
| ">>"
| ">>>"
| "+"
| "-"
| "*"
| "/"
| "%"
| "**"
| "|"
| "^"
| "&"
| "in"
| "instanceof";
type LogicalOperator = "||" | "&&" | "??";
type AssignmentOperator =
| "="
| "+="
| "-="
| "*="
| "/="
| "%="
| "**="
| "<<="
| ">>="
| ">>>="
| "|="
| "^="
| "&="
| "||="
| "&&="
| "??=";
type UpdateOperator = "++" | "--";
interface ForOfStatement extends BaseForXStatement {
type: "ForOfStatement";
await: boolean;
}
interface Super extends BaseNode {
type: "Super";
}
interface SpreadElement extends BaseNode {
type: "SpreadElement";
argument: Expression;
}
interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
type: "ArrowFunctionExpression";
expression: boolean;
body: BlockStatement | Expression;
}
interface YieldExpression extends BaseExpression {
type: "YieldExpression";
argument?: Expression | null | undefined;
delegate: boolean;
}
interface TemplateLiteral extends BaseExpression {
type: "TemplateLiteral";
quasis: TemplateElement[];
expressions: Expression[];
}
interface TaggedTemplateExpression extends BaseExpression {
type: "TaggedTemplateExpression";
tag: Expression;
quasi: TemplateLiteral;
}
interface TemplateElement extends BaseNode {
type: "TemplateElement";
tail: boolean;
value: {
/** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
cooked?: string | null | undefined;
raw: string;
};
}
interface AssignmentProperty extends Property {
value: Pattern;
kind: "init";
method: boolean; // false
}
interface ObjectPattern extends BasePattern {
type: "ObjectPattern";
properties: Array<AssignmentProperty | RestElement>;
}
interface ArrayPattern extends BasePattern {
type: "ArrayPattern";
elements: Array<Pattern | null>;
}
interface RestElement extends BasePattern {
type: "RestElement";
argument: Pattern;
}
interface AssignmentPattern extends BasePattern {
type: "AssignmentPattern";
left: Pattern;
right: Expression;
}
type Class = ClassDeclaration | ClassExpression;
interface BaseClass extends BaseNode {
superClass?: Expression | null | undefined;
body: ClassBody;
}
interface ClassBody extends BaseNode {
type: "ClassBody";
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
}
interface MethodDefinition extends BaseNode {
type: "MethodDefinition";
key: Expression | PrivateIdentifier;
value: FunctionExpression;
kind: "constructor" | "method" | "get" | "set";
computed: boolean;
static: boolean;
}
interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
type: "ClassDeclaration";
/** It is null when a class declaration is a part of the `export default class` statement */
id: Identifier | null;
}
interface ClassDeclaration extends MaybeNamedClassDeclaration {
id: Identifier;
}
interface ClassExpression extends BaseClass, BaseExpression {
type: "ClassExpression";
id?: Identifier | null | undefined;
}
interface MetaProperty extends BaseExpression {
type: "MetaProperty";
meta: Identifier;
property: Identifier;
}
type ModuleDeclaration =
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration;
interface BaseModuleDeclaration extends BaseNode {}
type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
interface BaseModuleSpecifier extends BaseNode {
local: Identifier;
}
interface ImportDeclaration extends BaseModuleDeclaration {
type: "ImportDeclaration";
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
attributes: ImportAttribute[];
source: Literal;
}
interface ImportSpecifier extends BaseModuleSpecifier {
type: "ImportSpecifier";
imported: Identifier | Literal;
}
interface ImportAttribute extends BaseNode {
type: "ImportAttribute";
key: Identifier | Literal;
value: Literal;
}
interface ImportExpression extends BaseExpression {
type: "ImportExpression";
source: Expression;
options?: Expression | null | undefined;
}
interface ImportDefaultSpecifier extends BaseModuleSpecifier {
type: "ImportDefaultSpecifier";
}
interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
type: "ImportNamespaceSpecifier";
}
interface ExportNamedDeclaration extends BaseModuleDeclaration {
type: "ExportNamedDeclaration";
declaration?: Declaration | null | undefined;
specifiers: ExportSpecifier[];
attributes: ImportAttribute[];
source?: Literal | null | undefined;
}
interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
type: "ExportSpecifier";
local: Identifier | Literal;
exported: Identifier | Literal;
}
interface ExportDefaultDeclaration extends BaseModuleDeclaration {
type: "ExportDefaultDeclaration";
declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
}
interface ExportAllDeclaration extends BaseModuleDeclaration {
type: "ExportAllDeclaration";
exported: Identifier | Literal | null;
attributes: ImportAttribute[];
source: Literal;
}
interface AwaitExpression extends BaseExpression {
type: "AwaitExpression";
argument: Expression;
}
type Positioned<T> = T & {
start: number;
end: number;
};
type Node = Positioned<Node$1>;
interface HoistMocksOptions {
/**
* List of modules that should always be imported before compiler hints.
* @default 'vitest'
*/
hoistedModule?: string;
/**
* @default ["vi", "vitest"]
*/
utilsObjectNames?: string[];
/**
* @default ["mock", "unmock"]
*/
hoistableMockMethodNames?: string[];
/**
* @default ["mock", "unmock", "doMock", "doUnmock"]
*/
dynamicImportMockMethodNames?: string[];
/**
* @default ["hoisted"]
*/
hoistedMethodNames?: string[];
globalThisAccessor?: string;
regexpHoistable?: RegExp;
codeFrameGenerator?: CodeFrameGenerator;
magicString?: () => MagicString;
}
declare function hoistMocks(code: string, id: string, parse: (code: string) => any, options?: HoistMocksOptions): MagicString | undefined;
interface CodeFrameGenerator {
(node: Positioned<Node>, id: string, code: string): string;
}
export { createManualModuleSource as c, hoistMocks as h };
export type { HoistMocksOptions as H };
@@ -1,4 +1,4 @@
import './types.d-B8CCKmHt.js';
import './types.d-BjI5eAwu.js';
type Key = string | symbol;
type CreateMockInstanceProcedure = (options?: {
+2 -2
View File
@@ -1,2 +1,2 @@
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-C-sLYZi-.js';
export { A as AutomockedModule, h as AutomockedModuleSerialized, f as AutospiedModule, i as AutospiedModuleSerialized, g as ManualMockedModule, j as ManualMockedModuleSerialized, a as MockedModule, k as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, l as RedirectedModuleSerialized, e as ServerIdResolution, S as ServerMockResolution } from './types.d-B8CCKmHt.js';
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-B41z0AuW.js';
export { A as AutomockedModule, g as AutomockedModuleSerialized, h as AutospiedModule, i as AutospiedModuleSerialized, j as ManualMockedModule, k as ManualMockedModuleSerialized, a as MockedModule, l as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, e as ModuleMockContext, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, n as RedirectedModuleSerialized, f as ServerIdResolution, S as ServerMockResolution, T as TestModuleMocker } from './types.d-BjI5eAwu.js';
+18 -3
View File
@@ -81,9 +81,24 @@ function mockObject(options, object, mockExports = {}) {
define(newContainer, property, value);
continue;
}
// Sometimes this assignment fails for some unknown reason. If it does,
// just move along.
if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
if (options.type === "autospy" && type === "Module") {
// Replace with clean object to recursively autospy exported module objects:
// export * as ns from "./ns"
// or
// import * as ns from "./ns"
// export { ns }
const exports$1 = Object.create(null);
Object.defineProperty(exports$1, Symbol.toStringTag, {
value: "Module",
configurable: true,
writable: true
});
try {
newContainer[property] = exports$1;
} catch {
continue;
}
} else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
continue;
}
if (isFunction) {
@@ -1,6 +1,6 @@
import { MaybeMockedDeep } from '@vitest/spy';
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, M as MockerRegistry, d as MockedModuleType } from './types.d-B8CCKmHt.js';
import { C as CreateMockInstanceProcedure } from './index.d-C-sLYZi-.js';
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, T as TestModuleMocker, M as MockerRegistry, d as MockedModuleType, e as ModuleMockContext } from './types.d-BjI5eAwu.js';
import { C as CreateMockInstanceProcedure } from './index.d-B41z0AuW.js';
interface CompilerHintsOptions {
/**
@@ -33,7 +33,7 @@ interface ModuleMockerInterceptor {
invalidate: () => Promise<void>;
}
declare class ModuleMocker {
declare class ModuleMocker implements TestModuleMocker {
private interceptor;
private rpc;
private createMockInstance;
@@ -47,11 +47,16 @@ declare class ModuleMocker {
getFactoryModule(id: string): any;
invalidate(): Promise<void>;
importActual<T>(id: string, importer: string): Promise<T>;
protected getBaseUrl(): string;
importMock<T>(rawId: string, importer: string): Promise<T>;
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
getMockContext(): ModuleMockContext;
queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
queueUnmock(id: string, importer: string): void;
wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
getMockedModuleById(id: string): MockedModule | undefined;
reset(): void;
private resolveMockPath;
}
interface ResolveIdResult {
@@ -77,5 +82,5 @@ interface ModuleMockerConfig {
root: string;
}
export { ModuleMocker as b, createCompilerHints as c };
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as d, ModuleMockerRPC as e, ResolveMockResult as f };
export { ModuleMocker as b, createCompilerHints as f };
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as c, ModuleMockerRPC as d, ResolveMockResult as e };
+5 -734
View File
@@ -1,12 +1,12 @@
import { H as HoistMocksOptions } from './hoistMocks.d-w2ILr1dG.js';
export { c as createManualModuleSource } from './hoistMocks.d-w2ILr1dG.js';
import { AutomockOptions } from './automock.js';
export { automockModule } from './automock.js';
import { Plugin, Rollup, ViteDevServer } from 'vite';
import { SourceMap } from 'magic-string';
import { M as MockerRegistry, S as ServerMockResolution, e as ServerIdResolution } from './types.d-B8CCKmHt.js';
import { M as MockerRegistry, S as ServerMockResolution, f as ServerIdResolution } from './types.d-BjI5eAwu.js';
export { findMockRedirect } from './redirect.js';
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
declare function automockPlugin(options?: AutomockOptions): Plugin;
interface DynamicImportPluginOptions {
@@ -18,732 +18,6 @@ interface DynamicImportPluginOptions {
}
declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin;
// This definition file follows a somewhat unusual format. ESTree allows
// runtime type checks based on the `type` parameter. In order to explain this
// to typescript we want to use discriminated union types:
// https://github.com/Microsoft/TypeScript/pull/9163
//
// For ESTree this is a bit tricky because the high level interfaces like
// Node or Function are pulling double duty. We want to pass common fields down
// to the interfaces that extend them (like Identifier or
// ArrowFunctionExpression), but you can't extend a type union or enforce
// common fields on them. So we've split the high level interfaces into two
// types, a base type which passes down inherited fields, and a type union of
// all types which extend the base type. Only the type union is exported, and
// the union is how other types refer to the collection of inheriting types.
//
// This makes the definitions file here somewhat more difficult to maintain,
// but it has the notable advantage of making ESTree much easier to use as
// an end user.
interface BaseNodeWithoutComments {
// Every leaf interface that extends BaseNode must specify a type property.
// The type property should be a string literal. For example, Identifier
// has: `type: "Identifier"`
type: string;
loc?: SourceLocation | null | undefined;
range?: [number, number] | undefined;
}
interface BaseNode extends BaseNodeWithoutComments {
leadingComments?: Comment[] | undefined;
trailingComments?: Comment[] | undefined;
}
interface NodeMap {
AssignmentProperty: AssignmentProperty;
CatchClause: CatchClause;
Class: Class;
ClassBody: ClassBody;
Expression: Expression;
Function: Function;
Identifier: Identifier;
Literal: Literal;
MethodDefinition: MethodDefinition;
ModuleDeclaration: ModuleDeclaration;
ModuleSpecifier: ModuleSpecifier;
Pattern: Pattern;
PrivateIdentifier: PrivateIdentifier;
Program: Program;
Property: Property;
PropertyDefinition: PropertyDefinition;
SpreadElement: SpreadElement;
Statement: Statement;
Super: Super;
SwitchCase: SwitchCase;
TemplateElement: TemplateElement;
VariableDeclarator: VariableDeclarator;
}
type Node$1 = NodeMap[keyof NodeMap];
interface Comment extends BaseNodeWithoutComments {
type: "Line" | "Block";
value: string;
}
interface SourceLocation {
source?: string | null | undefined;
start: Position;
end: Position;
}
interface Position {
/** >= 1 */
line: number;
/** >= 0 */
column: number;
}
interface Program extends BaseNode {
type: "Program";
sourceType: "script" | "module";
body: Array<Directive | Statement | ModuleDeclaration>;
comments?: Comment[] | undefined;
}
interface Directive extends BaseNode {
type: "ExpressionStatement";
expression: Literal;
directive: string;
}
interface BaseFunction extends BaseNode {
params: Pattern[];
generator?: boolean | undefined;
async?: boolean | undefined;
// The body is either BlockStatement or Expression because arrow functions
// can have a body that's either. FunctionDeclarations and
// FunctionExpressions have only BlockStatement bodies.
body: BlockStatement | Expression;
}
type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
type Statement =
| ExpressionStatement
| BlockStatement
| StaticBlock
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| Declaration;
interface BaseStatement extends BaseNode {}
interface EmptyStatement extends BaseStatement {
type: "EmptyStatement";
}
interface BlockStatement extends BaseStatement {
type: "BlockStatement";
body: Statement[];
innerComments?: Comment[] | undefined;
}
interface StaticBlock extends Omit<BlockStatement, "type"> {
type: "StaticBlock";
}
interface ExpressionStatement extends BaseStatement {
type: "ExpressionStatement";
expression: Expression;
}
interface IfStatement extends BaseStatement {
type: "IfStatement";
test: Expression;
consequent: Statement;
alternate?: Statement | null | undefined;
}
interface LabeledStatement extends BaseStatement {
type: "LabeledStatement";
label: Identifier;
body: Statement;
}
interface BreakStatement extends BaseStatement {
type: "BreakStatement";
label?: Identifier | null | undefined;
}
interface ContinueStatement extends BaseStatement {
type: "ContinueStatement";
label?: Identifier | null | undefined;
}
interface WithStatement extends BaseStatement {
type: "WithStatement";
object: Expression;
body: Statement;
}
interface SwitchStatement extends BaseStatement {
type: "SwitchStatement";
discriminant: Expression;
cases: SwitchCase[];
}
interface ReturnStatement extends BaseStatement {
type: "ReturnStatement";
argument?: Expression | null | undefined;
}
interface ThrowStatement extends BaseStatement {
type: "ThrowStatement";
argument: Expression;
}
interface TryStatement extends BaseStatement {
type: "TryStatement";
block: BlockStatement;
handler?: CatchClause | null | undefined;
finalizer?: BlockStatement | null | undefined;
}
interface WhileStatement extends BaseStatement {
type: "WhileStatement";
test: Expression;
body: Statement;
}
interface DoWhileStatement extends BaseStatement {
type: "DoWhileStatement";
body: Statement;
test: Expression;
}
interface ForStatement extends BaseStatement {
type: "ForStatement";
init?: VariableDeclaration | Expression | null | undefined;
test?: Expression | null | undefined;
update?: Expression | null | undefined;
body: Statement;
}
interface BaseForXStatement extends BaseStatement {
left: VariableDeclaration | Pattern;
right: Expression;
body: Statement;
}
interface ForInStatement extends BaseForXStatement {
type: "ForInStatement";
}
interface DebuggerStatement extends BaseStatement {
type: "DebuggerStatement";
}
type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
interface BaseDeclaration extends BaseStatement {}
interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
type: "FunctionDeclaration";
/** It is null when a function declaration is a part of the `export default function` statement */
id: Identifier | null;
body: BlockStatement;
}
interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
id: Identifier;
}
interface VariableDeclaration extends BaseDeclaration {
type: "VariableDeclaration";
declarations: VariableDeclarator[];
kind: "var" | "let" | "const" | "using" | "await using";
}
interface VariableDeclarator extends BaseNode {
type: "VariableDeclarator";
id: Pattern;
init?: Expression | null | undefined;
}
interface ExpressionMap {
ArrayExpression: ArrayExpression;
ArrowFunctionExpression: ArrowFunctionExpression;
AssignmentExpression: AssignmentExpression;
AwaitExpression: AwaitExpression;
BinaryExpression: BinaryExpression;
CallExpression: CallExpression;
ChainExpression: ChainExpression;
ClassExpression: ClassExpression;
ConditionalExpression: ConditionalExpression;
FunctionExpression: FunctionExpression;
Identifier: Identifier;
ImportExpression: ImportExpression;
Literal: Literal;
LogicalExpression: LogicalExpression;
MemberExpression: MemberExpression;
MetaProperty: MetaProperty;
NewExpression: NewExpression;
ObjectExpression: ObjectExpression;
SequenceExpression: SequenceExpression;
TaggedTemplateExpression: TaggedTemplateExpression;
TemplateLiteral: TemplateLiteral;
ThisExpression: ThisExpression;
UnaryExpression: UnaryExpression;
UpdateExpression: UpdateExpression;
YieldExpression: YieldExpression;
}
type Expression = ExpressionMap[keyof ExpressionMap];
interface BaseExpression extends BaseNode {}
type ChainElement = SimpleCallExpression | MemberExpression;
interface ChainExpression extends BaseExpression {
type: "ChainExpression";
expression: ChainElement;
}
interface ThisExpression extends BaseExpression {
type: "ThisExpression";
}
interface ArrayExpression extends BaseExpression {
type: "ArrayExpression";
elements: Array<Expression | SpreadElement | null>;
}
interface ObjectExpression extends BaseExpression {
type: "ObjectExpression";
properties: Array<Property | SpreadElement>;
}
interface PrivateIdentifier extends BaseNode {
type: "PrivateIdentifier";
name: string;
}
interface Property extends BaseNode {
type: "Property";
key: Expression | PrivateIdentifier;
value: Expression | Pattern; // Could be an AssignmentProperty
kind: "init" | "get" | "set";
method: boolean;
shorthand: boolean;
computed: boolean;
}
interface PropertyDefinition extends BaseNode {
type: "PropertyDefinition";
key: Expression | PrivateIdentifier;
value?: Expression | null | undefined;
computed: boolean;
static: boolean;
}
interface FunctionExpression extends BaseFunction, BaseExpression {
id?: Identifier | null | undefined;
type: "FunctionExpression";
body: BlockStatement;
}
interface SequenceExpression extends BaseExpression {
type: "SequenceExpression";
expressions: Expression[];
}
interface UnaryExpression extends BaseExpression {
type: "UnaryExpression";
operator: UnaryOperator;
prefix: true;
argument: Expression;
}
interface BinaryExpression extends BaseExpression {
type: "BinaryExpression";
operator: BinaryOperator;
left: Expression | PrivateIdentifier;
right: Expression;
}
interface AssignmentExpression extends BaseExpression {
type: "AssignmentExpression";
operator: AssignmentOperator;
left: Pattern | MemberExpression;
right: Expression;
}
interface UpdateExpression extends BaseExpression {
type: "UpdateExpression";
operator: UpdateOperator;
argument: Expression;
prefix: boolean;
}
interface LogicalExpression extends BaseExpression {
type: "LogicalExpression";
operator: LogicalOperator;
left: Expression;
right: Expression;
}
interface ConditionalExpression extends BaseExpression {
type: "ConditionalExpression";
test: Expression;
alternate: Expression;
consequent: Expression;
}
interface BaseCallExpression extends BaseExpression {
callee: Expression | Super;
arguments: Array<Expression | SpreadElement>;
}
type CallExpression = SimpleCallExpression | NewExpression;
interface SimpleCallExpression extends BaseCallExpression {
type: "CallExpression";
optional: boolean;
}
interface NewExpression extends BaseCallExpression {
type: "NewExpression";
}
interface MemberExpression extends BaseExpression, BasePattern {
type: "MemberExpression";
object: Expression | Super;
property: Expression | PrivateIdentifier;
computed: boolean;
optional: boolean;
}
type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
interface BasePattern extends BaseNode {}
interface SwitchCase extends BaseNode {
type: "SwitchCase";
test?: Expression | null | undefined;
consequent: Statement[];
}
interface CatchClause extends BaseNode {
type: "CatchClause";
param: Pattern | null;
body: BlockStatement;
}
interface Identifier extends BaseNode, BaseExpression, BasePattern {
type: "Identifier";
name: string;
}
type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
interface SimpleLiteral extends BaseNode, BaseExpression {
type: "Literal";
value: string | boolean | number | null;
raw?: string | undefined;
}
interface RegExpLiteral extends BaseNode, BaseExpression {
type: "Literal";
value?: RegExp | null | undefined;
regex: {
pattern: string;
flags: string;
};
raw?: string | undefined;
}
interface BigIntLiteral extends BaseNode, BaseExpression {
type: "Literal";
value?: bigint | null | undefined;
bigint: string;
raw?: string | undefined;
}
type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
type BinaryOperator =
| "=="
| "!="
| "==="
| "!=="
| "<"
| "<="
| ">"
| ">="
| "<<"
| ">>"
| ">>>"
| "+"
| "-"
| "*"
| "/"
| "%"
| "**"
| "|"
| "^"
| "&"
| "in"
| "instanceof";
type LogicalOperator = "||" | "&&" | "??";
type AssignmentOperator =
| "="
| "+="
| "-="
| "*="
| "/="
| "%="
| "**="
| "<<="
| ">>="
| ">>>="
| "|="
| "^="
| "&="
| "||="
| "&&="
| "??=";
type UpdateOperator = "++" | "--";
interface ForOfStatement extends BaseForXStatement {
type: "ForOfStatement";
await: boolean;
}
interface Super extends BaseNode {
type: "Super";
}
interface SpreadElement extends BaseNode {
type: "SpreadElement";
argument: Expression;
}
interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
type: "ArrowFunctionExpression";
expression: boolean;
body: BlockStatement | Expression;
}
interface YieldExpression extends BaseExpression {
type: "YieldExpression";
argument?: Expression | null | undefined;
delegate: boolean;
}
interface TemplateLiteral extends BaseExpression {
type: "TemplateLiteral";
quasis: TemplateElement[];
expressions: Expression[];
}
interface TaggedTemplateExpression extends BaseExpression {
type: "TaggedTemplateExpression";
tag: Expression;
quasi: TemplateLiteral;
}
interface TemplateElement extends BaseNode {
type: "TemplateElement";
tail: boolean;
value: {
/** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
cooked?: string | null | undefined;
raw: string;
};
}
interface AssignmentProperty extends Property {
value: Pattern;
kind: "init";
method: boolean; // false
}
interface ObjectPattern extends BasePattern {
type: "ObjectPattern";
properties: Array<AssignmentProperty | RestElement>;
}
interface ArrayPattern extends BasePattern {
type: "ArrayPattern";
elements: Array<Pattern | null>;
}
interface RestElement extends BasePattern {
type: "RestElement";
argument: Pattern;
}
interface AssignmentPattern extends BasePattern {
type: "AssignmentPattern";
left: Pattern;
right: Expression;
}
type Class = ClassDeclaration | ClassExpression;
interface BaseClass extends BaseNode {
superClass?: Expression | null | undefined;
body: ClassBody;
}
interface ClassBody extends BaseNode {
type: "ClassBody";
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
}
interface MethodDefinition extends BaseNode {
type: "MethodDefinition";
key: Expression | PrivateIdentifier;
value: FunctionExpression;
kind: "constructor" | "method" | "get" | "set";
computed: boolean;
static: boolean;
}
interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
type: "ClassDeclaration";
/** It is null when a class declaration is a part of the `export default class` statement */
id: Identifier | null;
}
interface ClassDeclaration extends MaybeNamedClassDeclaration {
id: Identifier;
}
interface ClassExpression extends BaseClass, BaseExpression {
type: "ClassExpression";
id?: Identifier | null | undefined;
}
interface MetaProperty extends BaseExpression {
type: "MetaProperty";
meta: Identifier;
property: Identifier;
}
type ModuleDeclaration =
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration;
interface BaseModuleDeclaration extends BaseNode {}
type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
interface BaseModuleSpecifier extends BaseNode {
local: Identifier;
}
interface ImportDeclaration extends BaseModuleDeclaration {
type: "ImportDeclaration";
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
attributes: ImportAttribute[];
source: Literal;
}
interface ImportSpecifier extends BaseModuleSpecifier {
type: "ImportSpecifier";
imported: Identifier | Literal;
}
interface ImportAttribute extends BaseNode {
type: "ImportAttribute";
key: Identifier | Literal;
value: Literal;
}
interface ImportExpression extends BaseExpression {
type: "ImportExpression";
source: Expression;
options?: Expression | null | undefined;
}
interface ImportDefaultSpecifier extends BaseModuleSpecifier {
type: "ImportDefaultSpecifier";
}
interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
type: "ImportNamespaceSpecifier";
}
interface ExportNamedDeclaration extends BaseModuleDeclaration {
type: "ExportNamedDeclaration";
declaration?: Declaration | null | undefined;
specifiers: ExportSpecifier[];
attributes: ImportAttribute[];
source?: Literal | null | undefined;
}
interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
type: "ExportSpecifier";
local: Identifier | Literal;
exported: Identifier | Literal;
}
interface ExportDefaultDeclaration extends BaseModuleDeclaration {
type: "ExportDefaultDeclaration";
declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
}
interface ExportAllDeclaration extends BaseModuleDeclaration {
type: "ExportAllDeclaration";
exported: Identifier | Literal | null;
attributes: ImportAttribute[];
source: Literal;
}
interface AwaitExpression extends BaseExpression {
type: "AwaitExpression";
argument: Expression;
}
type Positioned<T> = T & {
start: number;
end: number;
};
type Node = Positioned<Node$1>;
interface HoistMocksOptions {
/**
* List of modules that should always be imported before compiler hints.
* @default 'vitest'
*/
hoistedModule?: string;
/**
* @default ["vi", "vitest"]
*/
utilsObjectNames?: string[];
/**
* @default ["mock", "unmock"]
*/
hoistableMockMethodNames?: string[];
/**
* @default ["mock", "unmock", "doMock", "doUnmock"]
*/
dynamicImportMockMethodNames?: string[];
/**
* @default ["hoisted"]
*/
hoistedMethodNames?: string[];
regexpHoistable?: RegExp;
codeFrameGenerator?: CodeFrameGenerator;
}
interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistable"> {
include?: string | RegExp | (string | RegExp)[];
exclude?: string | RegExp | (string | RegExp)[];
@@ -753,14 +27,11 @@ interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistab
filter?: (id: string) => boolean;
}
declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin;
declare function hoistMockAndResolve(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
interface HoistMocksResult {
code: string;
map: SourceMap;
}
interface CodeFrameGenerator {
(node: Positioned<Node>, id: string, code: string): string;
}
declare function hoistMocks(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
interface InterceptorPluginOptions {
/**
@@ -796,5 +67,5 @@ declare class ServerMockResolver {
private resolveModule;
}
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, dynamicImportPlugin, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions };
+29 -587
View File
@@ -2,6 +2,7 @@ import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
import { a as automockModule, e as esmWalker } from './chunk-automock.js';
import MagicString from 'magic-string';
import { createFilter } from 'vite';
import { h as hoistMocks } from './chunk-hoistMocks.js';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path/posix';
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
@@ -11,6 +12,8 @@ import { findMockRedirect } from './redirect.js';
import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
import 'estree-walker';
import 'node:module';
import 'node:path';
import './chunk-helpers.js';
function automockPlugin(options = {}) {
return {
@@ -50,6 +53,9 @@ function dynamicImportPlugin(options = {}) {
};
}
function injectDynamicImport(code, id, parse, options = {}) {
if (code.includes("wrapDynamicImport")) {
return;
}
const s = new MagicString(code);
let ast;
try {
@@ -81,295 +87,6 @@ function injectDynamicImport(code, id, parse, options = {}) {
};
}
// AST walker module for ESTree compatible trees
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
baseVisitor[type](node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i = 0, list = node.cases; i < list.length; i += 1) {
var cs = list[i];
c(cs, st);
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
};
base.ExportAllDeclaration = function (node, st, c) {
if (node.exported)
{ c(node.exported, st); }
c(node.source, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
if (node.value) { c(node.value, st, "Expression"); }
};
function hoistMocksPlugin(options = {}) {
const filter = options.filter || createFilter(options.include, options.exclude);
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
@@ -391,7 +108,7 @@ function hoistMocksPlugin(options = {}) {
if (!filter(id)) {
return;
}
return hoistMocks(code, id, this.parse, {
const s = hoistMocks(code, id, this.parse, {
regexpHoistable,
hoistableMockMethodNames,
hoistedMethodNames,
@@ -399,304 +116,30 @@ function hoistMocksPlugin(options = {}) {
dynamicImportMockMethodNames,
...options
});
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
};
}
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
To fix this issue you can either:
- import the mocks API directly from 'vitest'
- enable the 'globals' options`;
function API_NOT_FOUND_CHECK(names) {
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function getNodeTail(code, node) {
let end = node.end;
if (code[node.end] === ";") {
end += 1;
}
if (code[node.end] === "\n") {
return end + 1;
}
if (code[node.end + 1] === "\n") {
end += 1;
}
return end;
}
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
const hashbangRE = /^#!.*\n/;
// this is a fork of Vite SSR transform
function hoistMocks(code, id, parse, options = {}) {
var _hashbangRE$exec;
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
if (!needHoisting) {
return;
}
const s = new MagicString(code);
let ast;
try {
ast = parse(code);
} catch (err) {
console.error(`Cannot parse ${id}:\n${err.message}.`);
return;
}
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
"mock",
"unmock",
"doMock",
"doUnmock"
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
// hoist at the start of the file, after the hashbang
let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0;
let hoistedModuleImported = false;
let uid = 0;
const idToImportMap = new Map();
const imports = [];
// this will transform import statements into dynamic ones, if there are imports
// it will keep the import as is, if we don't need to mock anything
// in browser environment it will wrap the module value with "vitest_wrap_module" function
// that returns a proxy to the module so that named exports can be mocked
function defineImport(importNode) {
const source = importNode.source.value;
// always hoist vitest import to top of the file, so
// "vi" helpers can access it
if (hoistedModule === source) {
hoistedModuleImported = true;
return;
}
const importId = `__vi_import_${uid++}__`;
imports.push({
id: importId,
node: importNode
});
return importId;
}
// 1. check all import statements and record id -> importName map
for (const node of ast.body) {
// import foo from 'foo' --> foo -> __import_foo__.default
// import { baz } from 'foo' --> baz -> __import_foo__.baz
// import * as ok from 'foo' --> ok -> __import_foo__
if (node.type === "ImportDeclaration") {
const importId = defineImport(node);
if (!importId) {
continue;
}
for (const spec of node.specifiers) {
if (spec.type === "ImportSpecifier") {
if (spec.imported.type === "Identifier") {
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
} else {
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
}
} else if (spec.type === "ImportDefaultSpecifier") {
idToImportMap.set(spec.local.name, `${importId}.default`);
} else {
// namespace specifier
idToImportMap.set(spec.local.name, importId);
}
}
}
}
const declaredConst = new Set();
const hoistedNodes = [];
function createSyntaxError(node, message) {
const _error = new SyntaxError(message);
Error.captureStackTrace(_error, createSyntaxError);
const serializedError = {
name: "SyntaxError",
message: _error.message,
stack: _error.stack
// to keeb backwards compat
function hoistMockAndResolve(code, id, parse, options = {}) {
const s = hoistMocks(code, id, parse, options);
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
if (options.codeFrameGenerator) {
serializedError.frame = options.codeFrameGenerator(node, id, code);
}
return serializedError;
}
function assertNotDefaultExport(node, error) {
var _findNodeAround;
const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node;
if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) {
throw createSyntaxError(defaultExport, error);
}
}
function assertNotNamedExport(node, error) {
var _findNodeAround2;
const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node;
if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) {
throw createSyntaxError(nodeExported, error);
}
}
function getVariableDeclaration(node) {
var _findNodeAround3, _declarationNode$decl;
const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node;
const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init;
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
return declarationNode;
}
}
const usedUtilityExports = new Set();
esmWalker(ast, {
onIdentifier(id, info, parentStack) {
const binding = idToImportMap.get(id.name);
if (!binding) {
return;
}
if (info.hasBindingShortcut) {
s.appendLeft(id.end, `: ${binding}`);
} else if (info.classDeclaration) {
if (!declaredConst.has(id.name)) {
declaredConst.add(id.name);
// locate the top-most node containing the class declaration
const topNode = parentStack[parentStack.length - 2];
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
}
} else if (!info.classExpression) {
s.update(id.start, id.end, binding);
}
},
onCallExpression(node) {
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
const methodName = node.callee.property.name;
usedUtilityExports.add(node.callee.object.name);
if (hoistableMockMethodNames.includes(methodName)) {
const method = `${node.callee.object.name}.${methodName}`;
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
}
// rewrite vi.mock(import('..')) into vi.mock('..')
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
const moduleInfo = node.arguments[0];
// vi.mock(import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "ImportExpression") {
const source = moduleInfo.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
// vi.mock(await import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
const source = moduleInfo.argument.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
hoistedNodes.push(node);
} else if (dynamicImportMockMethodNames.includes(methodName)) {
const moduleInfo = node.arguments[0];
let source = null;
if (moduleInfo.type === "ImportExpression") {
source = moduleInfo.source;
}
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
source = moduleInfo.argument.source;
}
if (source) {
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
if (hoistedMethodNames.includes(methodName)) {
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
// hoist "const variable = vi.hoisted(() => {})"
hoistedNodes.push(declarationNode);
} else {
var _findNodeAround4;
const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node;
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node;
hoistedNodes.push(moveNode);
}
}
}
}
});
function getNodeName(node) {
const callee = node.callee || {};
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
return `${callee.object.name}.${callee.property.name}()`;
}
return "\"hoisted method\"";
}
function getNodeCall(node) {
if (node.type === "CallExpression") {
return node;
}
if (node.type === "VariableDeclaration") {
const { declarations } = node;
const init = declarations[0].init;
if (init) {
return getNodeCall(init);
}
}
if (node.type === "AwaitExpression") {
const { argument } = node;
if (argument.type === "CallExpression") {
return getNodeCall(argument);
}
}
return node;
}
function createError(outsideNode, insideNode) {
const outsideCall = getNodeCall(outsideNode);
const insideCall = getNodeCall(insideNode);
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
}
// validate hoistedNodes doesn't have nodes inside other nodes
for (let i = 0; i < hoistedNodes.length; i++) {
const node = hoistedNodes[i];
for (let j = i + 1; j < hoistedNodes.length; j++) {
const otherNode = hoistedNodes[j];
if (node.start >= otherNode.start && node.end <= otherNode.end) {
throw createError(otherNode, node);
}
if (otherNode.start >= node.start && otherNode.end <= node.end) {
throw createError(node, otherNode);
}
}
}
// hoist vi.mock/vi.hoisted
for (const node of hoistedNodes) {
const end = getNodeTail(code, node);
// don't hoist into itself if it's already at the top
if (hoistIndex === end || hoistIndex === node.start) {
hoistIndex = end;
} else {
s.move(node.start, end, hoistIndex);
}
}
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
for (const { node: importNode, id: importId } of imports) {
const source = importNode.source.value;
s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`);
if (importNode.start === hoistIndex) {
// no need to hoist, but update hoistIndex to keep the order
hoistIndex = importNode.end;
} else {
// There will be an error if the module is called before it is imported,
// so the module import statement is hoisted to the top
s.move(importNode.start, importNode.end, hoistIndex);
}
}
if (!hoistedModuleImported && hoistedNodes.length) {
const utilityImports = [...usedUtilityExports];
// "vi" or "vitest" is imported from a module other than "vitest"
if (utilityImports.some((name) => idToImportMap.has(name))) {
s.prepend(API_NOT_FOUND_CHECK(utilityImports));
} else if (utilityImports.length) {
s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
}
}
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: id
})
};
}
function interceptorPlugin(options = {}) {
@@ -794,9 +237,8 @@ class ServerMockResolver {
const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
if (options.mock === "factory") {
var _manifest$fsPath;
const manifest = getViteDepsManifest(this.server.config);
const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false;
const needsInterop = manifest?.[fsPath]?.needsInterop ?? false;
return {
mockType: "manual",
resolvedId: id,
@@ -865,7 +307,7 @@ class ServerMockResolver {
return this.resolveModule(rawId, resolved);
}
resolveModule(rawId, resolved) {
const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId;
const id = resolved?.id || rawId;
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
return {
id,
@@ -964,4 +406,4 @@ function mockerPlugin(options = {}) {
];
}
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
+4 -4
View File
@@ -1,5 +1,5 @@
import fs from 'node:fs';
import nodeModule from 'node:module';
import module$1 from 'node:module';
import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js';
const { existsSync, readdirSync, statSync } = fs;
@@ -42,7 +42,7 @@ function findMockRedirect(root, mockPath, external) {
return existsSync(fullPath) ? fullPath : null;
}
const builtins = new Set([
...nodeModule.builtinModules,
...module$1.builtinModules,
"assert/strict",
"diagnostics_channel",
"dns/promises",
@@ -67,8 +67,8 @@ const prefixedBuiltins = new Set([
const NODE_BUILTIN_NAMESPACE = "node:";
function isNodeBuiltin(id) {
// Added in v18.6.0
if (nodeModule.isBuiltin) {
return nodeModule.isBuiltin(id);
if (module$1.isBuiltin) {
return module$1.isBuiltin(id);
}
if (prefixedBuiltins.has(id)) {
return true;
+3 -3
View File
@@ -1,7 +1,7 @@
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js';
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-QEntlm6J.js';
import '@vitest/spy';
import './types.d-B8CCKmHt.js';
import './index.d-C-sLYZi-.js';
import './types.d-BjI5eAwu.js';
import './index.d-B41z0AuW.js';
declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints;
declare function registerNativeFactoryResolver(mocker: ModuleMocker): void;
+1
View File
@@ -1,5 +1,6 @@
import { createMockInstance } from '@vitest/spy';
import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js';
import './chunk-helpers.js';
import './index.js';
import './chunk-registry.js';
import './chunk-pathe.M-eThtNZ.js';
+8
View File
@@ -0,0 +1,8 @@
export { c as createManualModuleSource, h as hoistMocks } from './hoistMocks.d-w2ILr1dG.js';
export { automockModule } from './automock.js';
import 'magic-string';
declare function initSyntaxLexers(): Promise<void>;
declare function collectModuleExports(filename: string, code: string, format: "module" | "commonjs", exports?: string[]): string[];
export { collectModuleExports, initSyntaxLexers };
+10
View File
@@ -0,0 +1,10 @@
export { c as createManualModuleSource } from './chunk-utils.js';
export { a as automockModule, c as collectModuleExports, i as initSyntaxLexers } from './chunk-automock.js';
export { h as hoistMocks } from './chunk-hoistMocks.js';
import 'node:fs';
import 'node:url';
import 'magic-string';
import 'estree-walker';
import 'node:module';
import 'node:path';
import './chunk-helpers.js';
@@ -65,15 +65,15 @@ interface RedirectedModuleSerialized {
raw: string;
redirect: string;
}
declare class ManualMockedModule {
declare class ManualMockedModule<T = any> {
raw: string;
id: string;
url: string;
factory: () => any;
cache: Record<string | symbol, any> | undefined;
factory: () => T;
cache: T | undefined;
readonly type = "manual";
constructor(raw: string, id: string, url: string, factory: () => any);
resolve(): Promise<Record<string | symbol, any>>;
constructor(raw: string, id: string, url: string, factory: () => T);
resolve(): T;
static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule;
toJSON(): ManualMockedModuleSerialized;
}
@@ -102,6 +102,22 @@ interface ServerIdResolution {
url: string;
optimized: boolean;
}
interface ModuleMockContext {
/**
* When mocking with a factory, this refers to the module that imported the mock.
*/
callstack: null | string[];
}
interface TestModuleMocker {
queueMock(id: string, importer: string, factoryOrOptions?: ModuleMockFactory | ModuleMockOptions): void;
queueUnmock(id: string, importer: string): void;
importActual<T>(rawId: string, importer: string, callstack?: string[] | null): Promise<T>;
importMock(rawId: string, importer: string): Promise<any>;
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
getMockContext(): ModuleMockContext;
reset(): void;
}
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as f, ManualMockedModule as g };
export type { ServerMockResolution as S, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ServerIdResolution as e, AutomockedModuleSerialized as h, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as j, MockedModuleSerialized as k, RedirectedModuleSerialized as l, ModuleMockFactory as m };
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as h, ManualMockedModule as j };
export type { ServerMockResolution as S, TestModuleMocker as T, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ModuleMockContext as e, ServerIdResolution as f, AutomockedModuleSerialized as g, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as k, MockedModuleSerialized as l, ModuleMockFactory as m, RedirectedModuleSerialized as n };
+20 -9
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/mocker",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Vitest module mocker implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,11 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock"
],
"sideEffects": false,
"exports": {
".": {
@@ -44,7 +49,11 @@
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./*": "./*"
"./transforms": {
"types": "./dist/transforms.d.ts",
"default": "./dist/transforms.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
@@ -55,7 +64,7 @@
],
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0-0"
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
@@ -68,16 +77,18 @@
"dependencies": {
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21",
"@vitest/spy": "4.0.18"
"@vitest/spy": "4.1.9"
},
"devDependencies": {
"@types/estree": "^1.0.8",
"acorn-walk": "^8.3.4",
"msw": "^2.12.3",
"acorn-walk": "^8.3.5",
"cjs-module-lexer": "^2.2.0",
"es-module-lexer": "^2.0.0",
"msw": "^2.12.10",
"pathe": "^2.0.3",
"vite": "^6.3.5",
"@vitest/spy": "4.0.18",
"@vitest/utils": "4.0.18"
"@vitest/spy": "4.1.9",
"@vitest/utils": "4.1.9"
},
"scripts": {
"build": "premove dist && rollup -c",
+7
View File
@@ -0,0 +1,7 @@
# @vitest/pretty-format
[![NPM version](https://img.shields.io/npm/v/@vitest/pretty-format?color=a1b858&label=)](https://npmx.dev/package/@vitest/pretty-format)
Vitest's fork of Jest's [`pretty-format`](https://npmx.dev/package/pretty-format).
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/pretty-format/USAGE.md)
+72 -1
View File
@@ -46,18 +46,78 @@ interface Options extends Omit<RequiredOptions, "compareKeys" | "theme"> {
theme: Theme;
}
interface PrettyFormatOptions {
/**
* Call `toJSON` on objects before formatting them.
* Ignored after the formatter has already called `toJSON` once for a value.
* @default true
*/
callToJSON?: boolean;
/**
* Whether to escape special characters in regular expressions.
* @default false
*/
escapeRegex?: boolean;
/**
* Whether to escape special characters in strings.
* @default true
*/
escapeString?: boolean;
/**
* Whether to highlight syntax using terminal colors.
* @default false
*/
highlight?: boolean;
/**
* Number of spaces to use for each level of indentation.
* @default 2
*/
indent?: number;
/**
* Maximum depth to recurse into nested values.
* @default Infinity
*/
maxDepth?: number;
/**
* Maximum number of items to print in arrays, sets, maps, and similar collections.
* @default Infinity
*/
maxWidth?: number;
/**
* Approximate per-depth-level budget for output length.
* When the accumulated output at any single depth level exceeds this value,
* further nesting is collapsed. This is a heuristic safety valve, not a hard
* limit — total output can reach up to roughly `maxDepth × maxOutputLength`.
* @default 1_000_000
*/
maxOutputLength?: number;
/**
* Whether to minimize added whitespace, including indentation and line breaks.
* @default false
*/
min?: boolean;
/**
* Whether to print `Object` / `Array` prefixes for plain objects and arrays.
* @default true
*/
printBasicPrototype?: boolean;
/**
* Whether to include the function name when formatting functions.
* @default true
*/
printFunctionName?: boolean;
/**
* Whether to include shadow-root contents when formatting DOM nodes.
* @default true
*/
printShadowRoot?: boolean;
/**
* Compare function used when sorting object keys. Set to `null` to disable sorting.
*/
compareKeys?: CompareKeys;
/**
* Plugins used to serialize application-specific data types.
* @default []
*/
plugins?: Plugins;
}
type OptionsReceived = PrettyFormatOptions;
@@ -77,6 +137,7 @@ interface Config {
printShadowRoot: boolean;
spacingInner: string;
spacingOuter: string;
maxOutputLength: number;
}
type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
type Test = (arg0: any) => boolean;
@@ -103,6 +164,15 @@ type Plugins = Array<Plugin>;
* LICENSE file in the root directory of this source tree.
*/
declare function createDOMElementFilter(filterNode?: (node: any) => boolean): NewPlugin;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare const DEFAULT_OPTIONS: Options;
/**
* Returns a presentation string of your `val` object
@@ -110,6 +180,7 @@ declare const DEFAULT_OPTIONS: Options;
* @param options Custom settings
*/
declare function format(val: unknown, options?: OptionsReceived): string;
declare const plugins: {
AsymmetricMatcher: NewPlugin;
DOMCollection: NewPlugin;
@@ -120,5 +191,5 @@ declare const plugins: {
Error: NewPlugin;
};
export { DEFAULT_OPTIONS, format, plugins };
export { DEFAULT_OPTIONS, createDOMElementFilter, format, plugins };
export type { Colors, CompareKeys, Config, NewPlugin, OldPlugin, Options, OptionsReceived, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme };
+57 -10
View File
@@ -295,7 +295,25 @@ function nodeIsComment(node) {
function nodeIsFragment(node) {
return node.nodeType === FRAGMENT_NODE;
}
const serialize$3 = (node, config, indentation, depth, refs, printer) => {
function filterChildren(children, filterNode) {
// Filter out text nodes that only contain whitespace to prevent empty lines
// This is done regardless of whether a filterNode is provided
let filtered = children.filter((node) => {
// Filter out text nodes that are only whitespace
if (node.nodeType === TEXT_NODE) {
const text = node.data || "";
// Keep text nodes that have non-whitespace content
return text.trim().length > 0;
}
return true;
});
// Apply additional user-provided filter if specified
if (filterNode) {
filtered = filtered.filter(filterNode);
}
return filtered;
}
function serializeDOM(node, config, indentation, depth, refs, printer, filterNode) {
if (nodeIsText(node)) {
return printText(node.data, config);
}
@@ -306,11 +324,22 @@ const serialize$3 = (node, config, indentation, depth, refs, printer) => {
if (++depth > config.maxDepth) {
return printElementAsLeaf(type, config);
}
const children = Array.prototype.slice.call(node.childNodes || node.children);
const shadowChildren = nodeIsFragment(node) || !node.shadowRoot ? [] : Array.prototype.slice.call(node.shadowRoot.children);
const resolvedChildren = filterNode ? filterChildren(children, filterNode) : children;
const resolvedShadowChildren = filterNode ? filterChildren(shadowChildren, filterNode) : shadowChildren;
return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes, (attr) => attr.name).sort(), nodeIsFragment(node) ? {} : [...node.attributes].reduce((props, attribute) => {
props[attribute.name] = attribute.value;
return props;
}, {}), config, indentation + config.indent, depth, refs, printer), (nodeIsFragment(node) || !node.shadowRoot ? "" : printShadowRoot(Array.prototype.slice.call(node.shadowRoot.children), config, indentation + config.indent, depth, refs, printer)) + printChildren(Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer), config, indentation);
};
}, {}), config, indentation + config.indent, depth, refs, printer), (resolvedShadowChildren.length > 0 ? printShadowRoot(resolvedShadowChildren, config, indentation + config.indent, depth, refs, printer) : "") + printChildren(resolvedChildren, config, indentation + config.indent, depth, refs, printer), config, indentation);
}
const serialize$3 = (node, config, indentation, depth, refs, printer) => serializeDOM(node, config, indentation, depth, refs, printer);
function createDOMElementFilter(filterNode) {
return {
test: test$3,
serialize: (node, config, indentation, depth, refs, printer) => serializeDOM(node, config, indentation, depth, refs, printer, filterNode)
};
}
const plugin$3 = {
serialize: serialize$3,
test: test$3
@@ -892,15 +921,30 @@ function findPlugin(plugins, val) {
return null;
}
function printer(val, config, indentation, depth, refs, hasCalledToJSON) {
let result;
const plugin = findPlugin(config.plugins, val);
if (plugin !== null) {
return printPlugin(plugin, val, config, indentation, depth, refs);
result = printPlugin(plugin, val, config, indentation, depth, refs);
} else {
const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString);
if (basicResult !== null) {
result = basicResult;
} else {
result = printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON);
}
}
const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString);
if (basicResult !== null) {
return basicResult;
// Per-depth output budget (inspired by Node's util.inspect).
// Each depth level tracks output independently, so nested results
// don't inflate a single counter (which would undercount by ~Nx for
// N levels of nesting). Nodes at the same depth produce disjoint spans
// in the output string, so each bucket accurately reflects output at
// that level. Total output is bounded by maxDepth × maxOutputLength.
config._outputLengthPerDepth[depth] ??= 0;
config._outputLengthPerDepth[depth] += result.length;
if (config._outputLengthPerDepth[depth] > config.maxOutputLength) {
config.maxDepth = 0;
}
return printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON);
return result;
}
const DEFAULT_THEME = {
comment: "gray",
@@ -918,6 +962,7 @@ const DEFAULT_OPTIONS = {
highlight: false,
indent: 2,
maxDepth: Number.POSITIVE_INFINITY,
maxOutputLength: 1e6,
maxWidth: Number.POSITIVE_INFINITY,
min: false,
plugins: [],
@@ -982,7 +1027,9 @@ function getConfig(options) {
printFunctionName: getPrintFunctionName(options),
printShadowRoot: options?.printShadowRoot ?? true,
spacingInner: options?.min ? " " : "\n",
spacingOuter: options?.min ? "" : "\n"
spacingOuter: options?.min ? "" : "\n",
maxOutputLength: options?.maxOutputLength ?? DEFAULT_OPTIONS.maxOutputLength,
_outputLengthPerDepth: []
};
}
function createIndent(indent) {
@@ -1019,4 +1066,4 @@ const plugins = {
Error: ErrorPlugin
};
export { DEFAULT_OPTIONS, format, plugins };
export { DEFAULT_OPTIONS, createDOMElementFilter, format, plugins };
+10 -4
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/pretty-format",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Fork of pretty-format with support for ESM",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,12 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"pretty",
"pretty-format"
],
"sideEffects": false,
"exports": {
".": {
@@ -30,11 +36,11 @@
"dist"
],
"dependencies": {
"tinyrainbow": "^3.0.3"
"tinyrainbow": "^3.1.0"
},
"devDependencies": {
"@types/react-is": "^19.2.0",
"react-is": "^19.2.0",
"react-is": "^19.2.4",
"react-is-18": "npm:react-is@18.3.1"
},
"scripts": {
+4 -2
View File
@@ -1,5 +1,7 @@
# @vitest/runner
Vitest mechanism to collect and run tasks.
[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner)
[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/advanced/runner)
Vitest mechanism to collect and run tests.
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/runner) | [Documentation](https://vitest.dev/api/advanced/runner)
File diff suppressed because it is too large Load Diff
-340
View File
@@ -1,340 +0,0 @@
import { processError } from '@vitest/utils/error';
import { parseSingleStack } from '@vitest/utils/source-map';
import { relative } from 'pathe';
import { toArray } from '@vitest/utils/helpers';
function createChainable(keys, fn) {
function create(context) {
const chain = function(...args) {
return fn.apply(context, args);
};
Object.assign(chain, fn);
chain.withContext = () => chain.bind(context);
chain.setContext = (key, value) => {
context[key] = value;
};
chain.mergeContext = (ctx) => {
Object.assign(context, ctx);
};
for (const key of keys) {
Object.defineProperty(chain, key, { get() {
return create({
...context,
[key]: true
});
} });
}
return chain;
}
const chain = create({});
chain.fn = fn;
return chain;
}
/**
* If any tasks been marked as `only`, mark all other tasks as `skip`.
*/
function interpretTaskModes(file, namePattern, testLocations, onlyMode, parentIsOnly, allowOnly) {
const matchedLocations = [];
const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => {
const suiteIsOnly = parentIsOnly || suite.mode === "only";
// Check if any tasks in this suite have `.only` - if so, only those should run
const hasSomeTasksOnly = onlyMode && suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t));
suite.tasks.forEach((t) => {
// Check if either the parent suite or the task itself are marked as included
// If there are tasks with `.only` in this suite, only include those (not all tasks from describe.only)
const includeTask = hasSomeTasksOnly ? t.mode === "only" || t.type === "suite" && someTasksAreOnly(t) : suiteIsOnly || t.mode === "only";
if (onlyMode) {
if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) {
// Don't skip this suite
if (t.mode === "only") {
checkAllowOnly(t, allowOnly);
t.mode = "run";
}
} else if (t.mode === "run" && !includeTask) {
t.mode = "skip";
} else if (t.mode === "only") {
checkAllowOnly(t, allowOnly);
t.mode = "run";
}
}
let hasLocationMatch = parentMatchedWithLocation;
// Match test location against provided locations, only run if present
// in `testLocations`. Note: if `includeTaskLocations` is not enabled,
// all test will be skipped.
if (testLocations !== undefined && testLocations.length !== 0) {
if (t.location && (testLocations === null || testLocations === void 0 ? void 0 : testLocations.includes(t.location.line))) {
t.mode = "run";
matchedLocations.push(t.location.line);
hasLocationMatch = true;
} else if (parentMatchedWithLocation) {
t.mode = "run";
} else if (t.type === "test") {
t.mode = "skip";
}
}
if (t.type === "test") {
if (namePattern && !getTaskFullName(t).match(namePattern)) {
t.mode = "skip";
}
} else if (t.type === "suite") {
if (t.mode === "skip") {
skipAllTasks(t);
} else if (t.mode === "todo") {
todoAllTasks(t);
} else {
traverseSuite(t, includeTask, hasLocationMatch);
}
}
});
// if all subtasks are skipped, mark as skip
if (suite.mode === "run" || suite.mode === "queued") {
if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) {
suite.mode = "skip";
}
}
};
traverseSuite(file, parentIsOnly, false);
const nonMatching = testLocations === null || testLocations === void 0 ? void 0 : testLocations.filter((loc) => !matchedLocations.includes(loc));
if (nonMatching && nonMatching.length !== 0) {
const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`;
if (file.result === undefined) {
file.result = {
state: "fail",
errors: []
};
}
if (file.result.errors === undefined) {
file.result.errors = [];
}
file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`)));
}
}
function getTaskFullName(task) {
return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`;
}
function someTasksAreOnly(suite) {
return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t));
}
function skipAllTasks(suite) {
suite.tasks.forEach((t) => {
if (t.mode === "run" || t.mode === "queued") {
t.mode = "skip";
if (t.type === "suite") {
skipAllTasks(t);
}
}
});
}
function todoAllTasks(suite) {
suite.tasks.forEach((t) => {
if (t.mode === "run" || t.mode === "queued") {
t.mode = "todo";
if (t.type === "suite") {
todoAllTasks(t);
}
}
});
}
function checkAllowOnly(task, allowOnly) {
if (allowOnly) {
return;
}
const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error"));
task.result = {
state: "fail",
errors: [error]
};
}
/* @__NO_SIDE_EFFECTS__ */
function generateHash(str) {
let hash = 0;
if (str.length === 0) {
return `${hash}`;
}
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return `${hash}`;
}
function calculateSuiteHash(parent) {
parent.tasks.forEach((t, idx) => {
t.id = `${parent.id}_${idx}`;
if (t.type === "suite") {
calculateSuiteHash(t);
}
});
}
function createFileTask(filepath, root, projectName, pool, viteEnvironment) {
const path = relative(root, filepath);
const file = {
id: generateFileHash(path, projectName),
name: path,
fullName: path,
type: "suite",
mode: "queued",
filepath,
tasks: [],
meta: Object.create(null),
projectName,
file: undefined,
pool,
viteEnvironment
};
file.file = file;
return file;
}
/**
* Generate a unique ID for a file based on its path and project name
* @param file File relative to the root of the project to keep ID the same between different machines
* @param projectName The name of the test project
*/
/* @__NO_SIDE_EFFECTS__ */
function generateFileHash(file, projectName) {
return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`);
}
function findTestFileStackTrace(testFilePath, error) {
// first line is the error message
const lines = error.split("\n").slice(1);
for (const line of lines) {
const stack = parseSingleStack(line);
if (stack && stack.file === testFilePath) {
return stack;
}
}
}
/**
* Return a function for running multiple async operations with limited concurrency.
*/
function limitConcurrency(concurrency = Infinity) {
// The number of currently active + pending tasks.
let count = 0;
// The head and tail of the pending task queue, built using a singly linked list.
// Both head and tail are initially undefined, signifying an empty queue.
// They both become undefined again whenever there are no pending tasks.
let head;
let tail;
// A bookkeeping function executed whenever a task has been run to completion.
const finish = () => {
count--;
// Check if there are further pending tasks in the queue.
if (head) {
// Allow the next pending task to run and pop it from the queue.
head[0]();
head = head[1];
// The head may now be undefined if there are no further pending tasks.
// In that case, set tail to undefined as well.
tail = head && tail;
}
};
return (func, ...args) => {
// Create a promise chain that:
// 1. Waits for its turn in the task queue (if necessary).
// 2. Runs the task.
// 3. Allows the next pending task (if any) to run.
return new Promise((resolve) => {
if (count++ < concurrency) {
// No need to queue if fewer than maxConcurrency tasks are running.
resolve();
} else if (tail) {
// There are pending tasks, so append to the queue.
tail = tail[1] = [resolve];
} else {
// No other pending tasks, initialize the queue with a new tail and head.
head = tail = [resolve];
}
}).then(() => {
// Running func here ensures that even a non-thenable result or an
// immediately thrown error gets wrapped into a Promise.
return func(...args);
}).finally(finish);
};
}
/**
* Partition in tasks groups by consecutive concurrent
*/
function partitionSuiteChildren(suite) {
let tasksGroup = [];
const tasksGroups = [];
for (const c of suite.tasks) {
if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) {
tasksGroup.push(c);
} else {
tasksGroups.push(tasksGroup);
tasksGroup = [c];
}
}
if (tasksGroup.length > 0) {
tasksGroups.push(tasksGroup);
}
return tasksGroups;
}
function isTestCase(s) {
return s.type === "test";
}
function getTests(suite) {
const tests = [];
const arraySuites = toArray(suite);
for (const s of arraySuites) {
if (isTestCase(s)) {
tests.push(s);
} else {
for (const task of s.tasks) {
if (isTestCase(task)) {
tests.push(task);
} else {
const taskTests = getTests(task);
for (const test of taskTests) {
tests.push(test);
}
}
}
}
}
return tests;
}
function getTasks(tasks = []) {
return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]);
}
function getSuites(suite) {
return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []);
}
function hasTests(suite) {
return toArray(suite).some((s) => s.tasks.some((c) => isTestCase(c) || hasTests(c)));
}
function hasFailed(suite) {
return toArray(suite).some((s) => {
var _s$result;
return ((_s$result = s.result) === null || _s$result === void 0 ? void 0 : _s$result.state) === "fail" || s.type === "suite" && hasFailed(s.tasks);
});
}
function getNames(task) {
const names = [task.name];
let current = task;
while (current === null || current === void 0 ? void 0 : current.suite) {
current = current.suite;
if (current === null || current === void 0 ? void 0 : current.name) {
names.unshift(current.name);
}
}
if (current !== task.file) {
names.unshift(task.file.name);
}
return names;
}
function getFullName(task, separator = " > ") {
return getNames(task).join(separator);
}
function getTestName(task, separator = " > ") {
return getNames(task).slice(1).join(separator);
}
function createTaskName(names, separator = " > ") {
return names.filter((name) => name !== undefined).join(separator);
}
export { calculateSuiteHash as a, createFileTask as b, createChainable as c, generateHash as d, createTaskName as e, findTestFileStackTrace as f, generateFileHash as g, getFullName as h, interpretTaskModes as i, getNames as j, getSuites as k, limitConcurrency as l, getTasks as m, getTestName as n, getTests as o, partitionSuiteChildren as p, hasFailed as q, hasTests as r, someTasksAreOnly as s, isTestCase as t };
+5 -6
View File
@@ -1,8 +1,6 @@
import { b as TestArtifact, a as Test, S as Suite, d as SuiteHooks, F as File, e as TaskUpdateEvent, T as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-C7UxawJ9.js';
export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, I as ImportDuration, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, x as SequenceHooks, y as SequenceSetupFiles, z as SuiteFactory, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, Z as TestContext, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact, i as afterAll, j as afterEach, k as beforeAll, l as beforeEach, o as onTestFailed, m as onTestFinished } from './tasks.d-C7UxawJ9.js';
import { T as TestArtifact, a as Test, S as Suite, b as SuiteHooks, F as FileSpecification, V as VitestRunner, c as File, d as TaskUpdateEvent, e as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-DEYaIMIu.js';
export { A as AfterAllListener, i as AfterEachListener, j as AroundAllListener, k as AroundEachListener, B as BeforeAllListener, l as BeforeEachListener, C as CancelReason, m as FailureScreenshotArtifact, n as Fixture, o as FixtureFn, p as FixtureOptions, q as Fixtures, I as ImportDuration, r as InferFixturesTypes, O as OnTestFailedHandler, s as OnTestFinishedHandler, R as Retry, t as RunMode, u as RuntimeContext, v as SequenceHooks, w as SequenceSetupFiles, x as SerializableRetry, y as SuiteFactory, z as SuiteOptions, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, W as TestArtifactBase, X as TestArtifactLocation, Y as TestArtifactRegistry, Z as TestAttachment, _ as TestContext, $ as TestFunction, a0 as TestOptions, a1 as TestTagDefinition, a2 as TestTags, a3 as Use, a4 as VisualRegressionArtifact, a5 as VitestRunnerConfig, a6 as VitestRunnerConstructor, a7 as VitestRunnerImportSource, a8 as afterAll, a9 as afterEach, aa as aroundAll, ab as aroundEach, ac as beforeAll, ad as beforeEach, ae as onTestFailed, af as onTestFinished } from './tasks.d-DEYaIMIu.js';
import { Awaitable } from '@vitest/utils';
import { FileSpecification, VitestRunner } from './types.js';
export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js';
import '@vitest/utils/diff';
/**
@@ -15,12 +13,13 @@ import '@vitest/utils/diff';
*
* Vitest automatically injects the source location where the artifact was created and manages any attachments you include.
*
* **Note:** artifacts must be recorded before the task is reported. Any artifacts recorded after that will not be included in the task.
*
* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests
* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase}
*
* @returns A promise that resolves to the recorded artifact with location injected
*
* @throws {Error} If called after the test has finished running
* @throws {Error} If the test runner doesn't support artifacts
*
* @example
@@ -173,7 +172,7 @@ declare const describe: SuiteAPI;
*/
declare const it: TestAPI;
declare function getCurrentSuite<ExtraContext = object>(): SuiteCollector<ExtraContext>;
declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record<string, unknown>): TestAPI;
declare function createTaskCollector(fn: (...args: any[]) => any): TestAPI;
declare function getCurrentTest<T extends Test | undefined>(): T;
+5 -2112
View File
File diff suppressed because it is too large Load Diff
-834
View File
@@ -1,834 +0,0 @@
import { TestError, Awaitable } from '@vitest/utils';
interface FixtureItem extends FixtureOptions {
prop: string;
value: any;
scope: "test" | "file" | "worker";
/**
* Indicates whether the fixture is a function
*/
isFn: boolean;
/**
* The dependencies(fixtures) of current fixture function.
*/
deps?: FixtureItem[];
}
/**
* Registers a callback function to be executed once before all tests within the current suite.
* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
*
* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed before all tests.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using beforeAll to set up a database connection
* beforeAll(async () => {
* await database.connect();
* });
* ```
*/
declare function beforeAll(fn: BeforeAllListener, timeout?: number): void;
/**
* Registers a callback function to be executed once after all tests within the current suite have completed.
* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
*
* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed after all tests.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using afterAll to close a database connection
* afterAll(async () => {
* await database.disconnect();
* });
* ```
*/
declare function afterAll(fn: AfterAllListener, timeout?: number): void;
/**
* Registers a callback function to be executed before each test within the current suite.
* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
*
* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using beforeEach to reset a database state
* beforeEach(async () => {
* await database.reset();
* });
* ```
*/
declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void;
/**
* Registers a callback function to be executed after each test within the current suite has completed.
* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
*
* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using afterEach to delete temporary files created during a test
* afterEach(async () => {
* await fileSystem.deleteTempFiles();
* });
* ```
*/
declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void;
/**
* Registers a callback function to be executed when a test fails within the current suite.
* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
*
* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @throws {Error} Throws an error if the function is not called within a test.
* @returns {void}
* @example
* ```ts
* // Example of using onTestFailed to log failure details
* onTestFailed(({ errors }) => {
* console.log(`Test failed: ${test.name}`, errors);
* });
* ```
*/
declare const onTestFailed: TaskHook<OnTestFailedHandler>;
/**
* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
*
* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
*
* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
*
* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @throws {Error} Throws an error if the function is not called within a test.
* @returns {void}
* @example
* ```ts
* // Example of using onTestFinished for cleanup
* const db = await connectToDatabase();
* onTestFinished(async () => {
* await db.disconnect();
* });
* ```
*/
declare const onTestFinished: TaskHook<OnTestFinishedHandler>;
type ChainableFunction<
T extends string,
F extends (...args: any) => any,
C = object
> = F & { [x in T] : ChainableFunction<T, F, C> } & {
fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
} & C;
declare function createChainable<
T extends string,
Args extends any[],
R = any
>(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R): ChainableFunction<T, (...args: Args) => R>;
type RunMode = "run" | "skip" | "only" | "todo" | "queued";
type TaskState = RunMode | "pass" | "fail";
interface TaskBase {
/**
* Unique task identifier. Based on the file id and the position of the task.
* The id of the file task is based on the file path relative to root and project name.
* It will not change between runs.
* @example `1201091390`, `1201091390_0`, `1201091390_0_1`
*/
id: string;
/**
* Task name provided by the user. If no name was provided, it will be an empty string.
*/
name: string;
/**
* Full name including the file path, any parent suites, and this task's name.
*
* Uses ` > ` as the separator between levels.
*
* @example
* // file
* 'test/task-names.test.ts'
* @example
* // suite
* 'test/task-names.test.ts > meal planning'
* 'test/task-names.test.ts > meal planning > grocery lists'
* @example
* // test
* 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients'
*/
fullName: string;
/**
* Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks.
*
* Uses ` > ` as the separator between levels.
*
* @example
* // file
* undefined
* @example
* // suite
* 'meal planning'
* 'meal planning > grocery lists'
* @example
* // test
* 'meal planning > grocery lists > calculates ingredients'
*/
fullTestName?: string;
/**
* Task mode.
* - **skip**: task is skipped
* - **only**: only this task and other tasks with `only` mode will run
* - **todo**: task is marked as a todo, alias for `skip`
* - **run**: task will run or already ran
* - **queued**: task will start running next. It can only exist on the File
*/
mode: RunMode;
/**
* Custom metadata for the task. JSON reporter will save this data.
*/
meta: TaskMeta;
/**
* Whether the task was produced with `.each()` method.
*/
each?: boolean;
/**
* Whether the task should run concurrently with other tasks.
*/
concurrent?: boolean;
/**
* Whether the tasks of the suite run in a random order.
*/
shuffle?: boolean;
/**
* Suite that this task is part of. File task or the global suite will have no parent.
*/
suite?: Suite;
/**
* Result of the task. Suite and file tasks will only have the result if there
* was an error during collection or inside `afterAll`/`beforeAll`.
*/
result?: TaskResult;
/**
* The amount of times the task should be retried if it fails.
* @default 0
*/
retry?: number;
/**
* The amount of times the task should be repeated after the successful run.
* If the task fails, it will not be retried unless `retry` is specified.
* @default 0
*/
repeats?: number;
/**
* Location of the task in the file. This field is populated only if
* `includeTaskLocation` option is set. It is generated by calling `new Error`
* and parsing the stack trace, so the location might differ depending on the runtime.
*/
location?: {
line: number;
column: number;
};
/**
* If the test was collected by parsing the file AST, and the name
* is not a static string, this property will be set to `true`.
* @experimental
*/
dynamic?: boolean;
}
interface TaskPopulated extends TaskBase {
/**
* File task. It's the root task of the file.
*/
file: File;
/**
* Whether the task should succeed if it fails. If the task fails, it will be marked as passed.
*/
fails?: boolean;
/**
* Store promises (from async expects) to wait for them before finishing the test
*/
promises?: Promise<any>[];
}
/**
* Custom metadata that can be used in reporters.
*/
interface TaskMeta {}
/**
* The result of calling a task.
*/
interface TaskResult {
/**
* State of the task. Inherits the `task.mode` during collection.
* When the task has finished, it will be changed to `pass` or `fail`.
* - **pass**: task ran successfully
* - **fail**: task failed
*/
state: TaskState;
/**
* Errors that occurred during the task execution. It is possible to have several errors
* if `expect.soft()` failed multiple times or `retry` was triggered.
*/
errors?: TestError[];
/**
* How long in milliseconds the task took to run.
*/
duration?: number;
/**
* Time in milliseconds when the task started running.
*/
startTime?: number;
/**
* Heap size in bytes after the task finished.
* Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined.
*/
heap?: number;
/**
* State of related to this task hooks. Useful during reporting.
*/
hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
/**
* The amount of times the task was retried. The task is retried only if it
* failed and `retry` option is set.
*/
retryCount?: number;
/**
* The amount of times the task was repeated. The task is repeated only if
* `repeats` option is set. This number also contains `retryCount`.
*/
repeatCount?: number;
}
/** The time spent importing & executing a non-externalized file. */
interface ImportDuration {
/** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */
selfTime: number;
/** The time spent importing & executing the file and all its imports. */
totalTime: number;
/** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */
external?: boolean;
/** Which module imported this module first. All subsequent imports are cached. */
importer?: string;
}
/**
* The tuple representing a single task update.
* Usually reported after the task finishes.
*/
type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta];
interface TaskEventData {
annotation?: TestAnnotation | undefined;
artifact?: TestArtifact | undefined;
}
type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined];
type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact";
interface Suite extends TaskBase {
type: "suite";
/**
* File task. It's the root task of the file.
*/
file: File;
/**
* An array of tasks that are part of the suite.
*/
tasks: Task[];
}
interface File extends Suite {
/**
* The name of the pool that the file belongs to.
* @default 'forks'
*/
pool?: string;
/**
* The environment that processes the file on the server.
*/
viteEnvironment?: string;
/**
* The path to the file in UNIX format.
*/
filepath: string;
/**
* The name of the workspace project the file belongs to.
*/
projectName: string | undefined;
/**
* The time it took to collect all tests in the file.
* This time also includes importing all the file dependencies.
*/
collectDuration?: number;
/**
* The time it took to import the setup file.
*/
setupDuration?: number;
/** The time spent importing every non-externalized dependency that Vitest has processed. */
importDurations?: Record<string, ImportDuration>;
}
interface Test<ExtraContext = object> extends TaskPopulated {
type: "test";
/**
* Test context that will be passed to the test function.
*/
context: TestContext & ExtraContext;
/**
* The test timeout in milliseconds.
*/
timeout: number;
/**
* An array of custom annotations.
*/
annotations: TestAnnotation[];
/**
* An array of artifacts produced by the test.
*
* @experimental
*/
artifacts: TestArtifact[];
fullTestName: string;
}
type Task = Test | Suite | File;
type TestFunction<ExtraContext = object> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
1: [T[0]];
2: [T[0], T[1]];
3: [T[0], T[1], T[2]];
4: [T[0], T[1], T[2], T[3]];
5: [T[0], T[1], T[2], T[3], T[4]];
6: [T[0], T[1], T[2], T[3], T[4], T[5]];
7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : "fallback"];
interface EachFunctionReturn<T extends any[]> {
(name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number): void;
(name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable<void>): void;
}
interface TestEachFunction {
<T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>;
<T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>;
<T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>;
(...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
}
interface TestForFunctionReturn<
Arg,
Context
> {
(name: string | Function, fn: (arg: Arg, context: Context) => Awaitable<void>): void;
(name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable<void>): void;
}
interface TestForFunction<ExtraContext> {
<T>(cases: ReadonlyArray<T>): TestForFunctionReturn<T, TestContext & ExtraContext>;
(strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn<any, TestContext & ExtraContext>;
}
interface SuiteForFunction {
<T>(cases: ReadonlyArray<T>): EachFunctionReturn<[T]>;
(...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
}
interface TestCollectorCallable<C = object> {
<ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number): void;
<ExtraContext extends C>(name: string | Function, options?: TestCollectorOptions, fn?: TestFunction<ExtraContext>): void;
}
type ChainableTestAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "fails", TestCollectorCallable<ExtraContext>, {
each: TestEachFunction;
for: TestForFunction<ExtraContext>;
}>;
type TestCollectorOptions = Omit<TestOptions, "shuffle">;
interface TestOptions {
/**
* Test timeout.
*/
timeout?: number;
/**
* Times to retry the test if fails. Useful for making flaky tests more stable.
* When retries is up, the last test error will be thrown.
*
* @default 0
*/
retry?: number;
/**
* How many times the test will run again.
* Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default.
*
* @default 0
*/
repeats?: number;
/**
* Whether suites and tests run concurrently.
* Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`.
*/
concurrent?: boolean;
/**
* Whether tests run sequentially.
* Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`.
*/
sequential?: boolean;
/**
* Whether the tasks of the suite run in a random order.
*/
shuffle?: boolean;
/**
* Whether the test should be skipped.
*/
skip?: boolean;
/**
* Should this test be the only one running in a suite.
*/
only?: boolean;
/**
* Whether the test should be skipped and marked as a todo.
*/
todo?: boolean;
/**
* Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail.
*/
fails?: boolean;
}
interface ExtendedAPI<ExtraContext> {
skipIf: (condition: any) => ChainableTestAPI<ExtraContext>;
runIf: (condition: any) => ChainableTestAPI<ExtraContext>;
}
interface Hooks<ExtraContext> {
beforeAll: typeof beforeAll;
afterAll: typeof afterAll;
beforeEach: typeof beforeEach<ExtraContext>;
afterEach: typeof afterEach<ExtraContext>;
}
type TestAPI<ExtraContext = object> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & Hooks<ExtraContext> & {
extend: <T extends Record<string, any> = object>(fixtures: Fixtures<T, ExtraContext>) => TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>;
scoped: (fixtures: Partial<Fixtures<ExtraContext>>) => void;
};
interface FixtureOptions {
/**
* Whether to automatically set up current fixture, even though it's not being used in tests.
* @default false
*/
auto?: boolean;
/**
* Indicated if the injected value from the config should be preferred over the fixture value
*/
injected?: boolean;
/**
* When should the fixture be set up.
* - **test**: fixture will be set up before every test
* - **worker**: fixture will be set up once per worker
* - **file**: fixture will be set up once per file
*
* **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file.
* @default 'test'
*/
scope?: "test" | "worker" | "file";
}
type Use<T> = (value: T) => Promise<void>;
type FixtureFn<
T,
K extends keyof T,
ExtraContext
> = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>;
type Fixture<
T,
K extends keyof T,
ExtraContext = object
> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never);
type Fixtures<
T,
ExtraContext = object
> = { [K in keyof T] : Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?] };
type InferFixturesTypes<T> = T extends TestAPI<infer C> ? C : T;
interface SuiteCollectorCallable<ExtraContext = object> {
<OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, fn?: SuiteFactory<OverrideExtraContext>, options?: number): SuiteCollector<OverrideExtraContext>;
<OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, options: TestOptions, fn?: SuiteFactory<OverrideExtraContext>): SuiteCollector<OverrideExtraContext>;
}
type ChainableSuiteAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "shuffle", SuiteCollectorCallable<ExtraContext>, {
each: TestEachFunction;
for: SuiteForFunction;
}>;
type SuiteAPI<ExtraContext = object> = ChainableSuiteAPI<ExtraContext> & {
skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
};
interface BeforeAllListener {
(suite: Readonly<Suite | File>): Awaitable<unknown>;
}
interface AfterAllListener {
(suite: Readonly<Suite | File>): Awaitable<unknown>;
}
interface BeforeEachListener<ExtraContext = object> {
(context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
}
interface AfterEachListener<ExtraContext = object> {
(context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
}
interface SuiteHooks<ExtraContext = object> {
beforeAll: BeforeAllListener[];
afterAll: AfterAllListener[];
beforeEach: BeforeEachListener<ExtraContext>[];
afterEach: AfterEachListener<ExtraContext>[];
}
interface TaskCustomOptions extends TestOptions {
/**
* Whether the task was produced with `.each()` method.
*/
each?: boolean;
/**
* Custom metadata for the task that will be assigned to `task.meta`.
*/
meta?: Record<string, unknown>;
/**
* Task fixtures.
*/
fixtures?: FixtureItem[];
/**
* Function that will be called when the task is executed.
* If nothing is provided, the runner will try to get the function using `getFn(task)`.
* If the runner cannot find the function, the task will be marked as failed.
*/
handler?: (context: TestContext) => Awaitable<void>;
}
interface SuiteCollector<ExtraContext = object> {
readonly name: string;
readonly mode: RunMode;
options?: TestOptions;
type: "collector";
test: TestAPI<ExtraContext>;
tasks: (Suite | Test<ExtraContext> | SuiteCollector<ExtraContext>)[];
scoped: (fixtures: Fixtures<any, ExtraContext>) => void;
fixtures: () => FixtureItem[] | undefined;
file?: File;
suite?: Suite;
task: (name: string, options?: TaskCustomOptions) => Test<ExtraContext>;
collect: (file: File) => Promise<Suite>;
clear: () => void;
on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
}
type SuiteFactory<ExtraContext = object> = (test: TestAPI<ExtraContext>) => Awaitable<void>;
interface RuntimeContext {
tasks: (SuiteCollector | Test)[];
currentSuite: SuiteCollector | null;
}
/**
* User's custom test context.
*/
interface TestContext {
/**
* Metadata of the current test
*/
readonly task: Readonly<Test>;
/**
* An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or
* the test run was cancelled.
* @see {@link https://vitest.dev/guide/test-context#signal}
*/
readonly signal: AbortSignal;
/**
* Register a callback to run when this specific test fails.
* Useful when tests run concurrently.
* @see {@link https://vitest.dev/guide/test-context#ontestfailed}
*/
readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void;
/**
* Register a callback to run when this specific test finishes.
* Useful when tests run concurrently.
* @see {@link https://vitest.dev/guide/test-context#ontestfinished}
*/
readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void;
/**
* Mark tests as skipped. All execution after this call will be skipped.
* This function throws an error, so make sure you are not catching it accidentally.
* @see {@link https://vitest.dev/guide/test-context#skip}
*/
readonly skip: {
(note?: string): never;
(condition: boolean, note?: string): void;
};
/**
* Add a test annotation that will be displayed by your reporter.
* @see {@link https://vitest.dev/guide/test-context#annotate}
*/
readonly annotate: {
(message: string, type?: string, attachment?: TestAttachment): Promise<TestAnnotation>;
(message: string, attachment?: TestAttachment): Promise<TestAnnotation>;
};
}
type OnTestFailedHandler = (context: TestContext) => Awaitable<void>;
type OnTestFinishedHandler = (context: TestContext) => Awaitable<void>;
interface TaskHook<HookListener> {
(fn: HookListener, timeout?: number): void;
}
type SequenceHooks = "stack" | "list" | "parallel";
type SequenceSetupFiles = "list" | "parallel";
/**
* Represents a file or data attachment associated with a test artifact.
*
* Attachments can be either file-based (via `path`) or inline content (via `body`).
* The `contentType` helps consumers understand how to interpret the attachment data.
*/
interface TestAttachment {
/** MIME type of the attachment (e.g., 'image/png', 'text/plain') */
contentType?: string;
/** File system path to the attachment */
path?: string;
/** Inline attachment content as a string or raw binary data */
body?: string | Uint8Array;
}
/**
* Source code location information for a test artifact.
*
* Indicates where in the source code the artifact originated from.
*/
interface TestArtifactLocation {
/** Line number in the source file (1-indexed) */
line: number;
/** Column number in the line (1-indexed) */
column: number;
/** Path to the source file */
file: string;
}
/**
* @experimental
*
* Base interface for all test artifacts.
*
* Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code.
*/
interface TestArtifactBase {
/** File or data attachments associated with this artifact */
attachments?: TestAttachment[];
/** Source location where this artifact was created */
location?: TestArtifactLocation;
}
/**
* @deprecated Use {@linkcode TestArtifactLocation} instead.
*
* Kept for backwards compatibility.
*/
type TestAnnotationLocation = TestArtifactLocation;
interface TestAnnotation {
message: string;
type: string;
location?: TestArtifactLocation;
attachment?: TestAttachment;
}
/**
* @experimental
*
* Artifact type for test annotations.
*/
interface TestAnnotationArtifact extends TestArtifactBase {
type: "internal:annotation";
annotation: TestAnnotation;
}
interface VisualRegressionArtifactAttachment extends TestAttachment {
name: "reference" | "actual" | "diff";
width: number;
height: number;
}
/**
* @experimental
*
* Artifact type for visual regressions.
*/
interface VisualRegressionArtifact extends TestArtifactBase {
type: "internal:toMatchScreenshot";
kind: "visual-regression";
message: string;
attachments: VisualRegressionArtifactAttachment[];
}
/**
* @experimental
* @advanced
*
* Registry for custom test artifact types.
*
* Augment this interface to register custom artifact types that your tests can produce.
*
* Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property.
*
* @remarks
* - Use a `Symbol` as the **registry key** to guarantee uniqueness
* - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix
* - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata
* - `location` property is automatically injected to indicate where the artifact was created
*
* @example
* ```ts
* // Define custom attachment type for generated PDF
* interface PDFAttachment extends TestAttachment {
* contentType: 'application/pdf'
* body: Uint8Array
* pageCount: number
* fileSize: number
* }
*
* interface PDFGenerationArtifact extends TestArtifactBase {
* type: 'my-plugin:pdf-generation'
* templateName: string
* isValid: boolean
* attachments: [PDFAttachment]
* }
*
* // Use a symbol to guarantee key uniqueness
* const pdfKey = Symbol('pdf-generation')
*
* declare module 'vitest' {
* interface TestArtifactRegistry {
* [pdfKey]: PDFGenerationArtifact
* }
* }
*
* // Custom assertion for PDF generation
* async function toGenerateValidPDF(
* this: MatcherState,
* actual: PDFTemplate,
* data: Record<string, unknown>
* ): AsyncExpectationResult {
* const pdfBuffer = await actual.render(data)
* const validation = await validatePDF(pdfBuffer)
*
* await recordArtifact(this.task, {
* type: 'my-plugin:pdf-generation',
* templateName: actual.name,
* isValid: validation.success,
* attachments: [{
* contentType: 'application/pdf',
* body: pdfBuffer,
* pageCount: validation.pageCount,
* fileSize: pdfBuffer.byteLength
* }]
* })
*
* return {
* pass: validation.success,
* message: () => validation.success
* ? `Generated valid PDF with ${validation.pageCount} pages`
* : `Invalid PDF: ${validation.error}`
* }
* }
* ```
*/
interface TestArtifactRegistry {}
/**
* @experimental
*
* Union type of all test artifacts, including built-in and custom registered artifacts.
*
* This type automatically includes all artifacts registered via {@link TestArtifactRegistry}.
*/
type TestArtifact = TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry];
export { createChainable as c, afterAll as i, afterEach as j, beforeAll as k, beforeEach as l, onTestFinished as m, onTestFailed as o };
export type { TestOptions as $, AfterAllListener as A, BeforeAllListener as B, ChainableFunction as C, TaskBase as D, TaskCustomOptions as E, File as F, TaskEventPack as G, TaskHook as H, ImportDuration as I, TaskMeta as J, TaskPopulated as K, TaskResult as L, TaskResultPack as M, TaskState as N, OnTestFailedHandler as O, TestAnnotation as P, TestAnnotationArtifact as Q, RunMode as R, Suite as S, Task as T, TestAnnotationLocation as U, TestArtifactBase as V, TestArtifactLocation as W, TestArtifactRegistry as X, TestAttachment as Y, TestContext as Z, TestFunction as _, Test as a, Use as a0, VisualRegressionArtifact as a1, TestArtifact as b, SuiteHooks as d, TaskUpdateEvent as e, TestAPI as f, SuiteAPI as g, SuiteCollector as h, AfterEachListener as n, BeforeEachListener as p, Fixture as q, FixtureFn as r, FixtureOptions as s, Fixtures as t, InferFixturesTypes as u, OnTestFinishedHandler as v, RuntimeContext as w, SequenceHooks as x, SequenceSetupFiles as y, SuiteFactory as z };
File diff suppressed because it is too large Load Diff
+2 -182
View File
@@ -1,183 +1,3 @@
import { DiffOptions } from '@vitest/utils/diff';
import { F as File, a as Test, S as Suite, M as TaskResultPack, G as TaskEventPack, P as TestAnnotation, b as TestArtifact, Z as TestContext, I as ImportDuration, x as SequenceHooks, y as SequenceSetupFiles } from './tasks.d-C7UxawJ9.js';
export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, g as SuiteAPI, h as SuiteCollector, z as SuiteFactory, d as SuiteHooks, T as Task, D as TaskBase, E as TaskCustomOptions, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, N as TaskState, e as TaskUpdateEvent, f as TestAPI, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact } from './tasks.d-C7UxawJ9.js';
export { A as AfterAllListener, i as AfterEachListener, j as AroundAllListener, k as AroundEachListener, B as BeforeAllListener, l as BeforeEachListener, C as CancelReason, m as FailureScreenshotArtifact, c as File, F as FileSpecification, n as Fixture, o as FixtureFn, p as FixtureOptions, q as Fixtures, I as ImportDuration, r as InferFixturesTypes, O as OnTestFailedHandler, s as OnTestFinishedHandler, R as Retry, t as RunMode, u as RuntimeContext, v as SequenceHooks, w as SequenceSetupFiles, x as SerializableRetry, S as Suite, g as SuiteAPI, h as SuiteCollector, y as SuiteFactory, b as SuiteHooks, z as SuiteOptions, e as Task, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, d as TaskUpdateEvent, a as Test, f as TestAPI, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, T as TestArtifact, W as TestArtifactBase, X as TestArtifactLocation, Y as TestArtifactRegistry, Z as TestAttachment, _ as TestContext, $ as TestFunction, a0 as TestOptions, a1 as TestTagDefinition, a2 as TestTags, a3 as Use, a4 as VisualRegressionArtifact, V as VitestRunner, a5 as VitestRunnerConfig, a6 as VitestRunnerConstructor, a7 as VitestRunnerImportSource } from './tasks.d-DEYaIMIu.js';
import '@vitest/utils';
/**
* This is a subset of Vitest config that's required for the runner to work.
*/
interface VitestRunnerConfig {
root: string;
setupFiles: string[];
name?: string;
passWithNoTests: boolean;
testNamePattern?: RegExp;
allowOnly?: boolean;
sequence: {
shuffle?: boolean;
concurrent?: boolean;
seed: number;
hooks: SequenceHooks;
setupFiles: SequenceSetupFiles;
};
chaiConfig?: {
truncateThreshold?: number;
};
maxConcurrency: number;
testTimeout: number;
hookTimeout: number;
retry: number;
includeTaskLocation?: boolean;
diffOptions?: DiffOptions;
}
/**
* Possible options to run a single file in a test.
*/
interface FileSpecification {
filepath: string;
testLocations: number[] | undefined;
}
type VitestRunnerImportSource = "collect" | "setup";
interface VitestRunnerConstructor {
new (config: VitestRunnerConfig): VitestRunner;
}
type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>);
interface VitestRunner {
/**
* First thing that's getting called before actually collecting and running tests.
*/
onBeforeCollect?: (paths: string[]) => unknown;
/**
* Called after the file task was created but not collected yet.
*/
onCollectStart?: (file: File) => unknown;
/**
* Called after collecting tests and before "onBeforeRun".
*/
onCollected?: (files: File[]) => unknown;
/**
* Called when test runner should cancel next test runs.
* Runner should listen for this method and mark tests and suites as skipped in
* "onBeforeRunSuite" and "onBeforeRunTask" when called.
*/
cancel?: (reason: CancelReason) => unknown;
/**
* Called before running a single test. Doesn't have "result" yet.
*/
onBeforeRunTask?: (test: Test) => unknown;
/**
* Called before actually running the test function. Already has "result" with "state" and "startTime".
*/
onBeforeTryTask?: (test: Test, options: {
retry: number;
repeats: number;
}) => unknown;
/**
* When the task has finished running, but before cleanup hooks are called
*/
onTaskFinished?: (test: Test) => unknown;
/**
* Called after result and state are set.
*/
onAfterRunTask?: (test: Test) => unknown;
/**
* Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
*/
onAfterTryTask?: (test: Test, options: {
retry: number;
repeats: number;
}) => unknown;
/**
* Called after the retry resolution happend. Unlike `onAfterTryTask`, the test now has a new state.
* All `after` hooks were also called by this point.
*/
onAfterRetryTask?: (test: Test, options: {
retry: number;
repeats: number;
}) => unknown;
/**
* Called before running a single suite. Doesn't have "result" yet.
*/
onBeforeRunSuite?: (suite: Suite) => unknown;
/**
* Called after running a single suite. Has state and result.
*/
onAfterRunSuite?: (suite: Suite) => unknown;
/**
* If defined, will be called instead of usual Vitest suite partition and handling.
* "before" and "after" hooks will not be ignored.
*/
runSuite?: (suite: Suite) => Promise<void>;
/**
* If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
* "before" and "after" hooks will not be ignored.
*/
runTask?: (test: Test) => Promise<void>;
/**
* Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
*/
onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
/**
* Called when annotation is added via the `context.annotate` method.
*/
onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise<TestAnnotation>;
/**
* @experimental
*
* Called when artifacts are recorded on tests via the `recordArtifact` utility.
*/
onTestArtifactRecord?: <Artifact extends TestArtifact>(test: Test, artifact: Artifact) => Promise<Artifact>;
/**
* Called before running all tests in collected paths.
*/
onBeforeRunFiles?: (files: File[]) => unknown;
/**
* Called right after running all tests in collected paths.
*/
onAfterRunFiles?: (files: File[]) => unknown;
/**
* Called when new context for a test is defined. Useful if you want to add custom properties to the context.
* If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
*
* @see https://vitest.dev/advanced/runner#your-task-function
*/
extendTaskContext?: (context: TestContext) => TestContext;
/**
* Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files.
*/
importFile: (filepath: string, source: VitestRunnerImportSource) => unknown;
/**
* Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }`
*/
injectValue?: (key: string) => unknown;
/**
* Gets the time spent importing each individual non-externalized file that Vitest collected.
*/
getImportDurations?: () => Record<string, ImportDuration>;
/**
* Publicly available configuration.
*/
config: VitestRunnerConfig;
/**
* The name of the current pool. Can affect how stack trace is inferred on the server side.
*/
pool?: string;
/**
* The current Vite environment that processes the files on the server.
*/
viteEnvironment?: string;
/**
* Return the worker context for fixtures specified with `scope: 'worker'`
*/
getWorkerContext?: () => Record<string, unknown>;
onCleanupWorkerContext?: (cleanup: () => unknown) => void;
trace?<T>(name: string, cb: () => T): T;
trace?<T>(name: string, attributes: Record<string, any>, cb: () => T): T;
/** @private */
_currentTaskStartTime?: number;
/** @private */
_currentTaskTimeout?: number;
}
export { File, ImportDuration, SequenceHooks, SequenceSetupFiles, Suite, TaskEventPack, TaskResultPack, Test, TestAnnotation, TestArtifact, TestContext };
export type { CancelReason, FileSpecification, VitestRunner, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource };
import '@vitest/utils/diff';
+20 -8
View File
@@ -1,11 +1,12 @@
import { S as Suite, F as File, T as Task, a as Test } from './tasks.d-C7UxawJ9.js';
export { C as ChainableFunction, c as createChainable } from './tasks.d-C7UxawJ9.js';
import { S as Suite, c as File, e as Task, a1 as TestTagDefinition, a5 as VitestRunnerConfig, a as Test } from './tasks.d-DEYaIMIu.js';
export { ag as ChainableFunction, ah as createChainable } from './tasks.d-DEYaIMIu.js';
import { ParsedStack, Arrayable } from '@vitest/utils';
import '@vitest/utils/diff';
/**
* If any tasks been marked as `only`, mark all other tasks as `skip`.
*/
declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void;
declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, testIds?: string[] | undefined, testTagsFilter?: ((testTags: string[]) => boolean) | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void;
declare function someTasksAreOnly(suite: Suite): boolean;
declare function generateHash(str: string): string;
declare function calculateSuiteHash(parent: Suite): void;
@@ -18,19 +19,30 @@ declare function createFileTask(filepath: string, root: string, projectName: str
declare function generateFileHash(file: string, projectName: string | undefined): string;
declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined;
/**
* Return a function for running multiple async operations with limited concurrency.
*/
declare function limitConcurrency(concurrency?: number): <
interface ConcurrencyLimiter extends ConcurrencyLimiterFn {
acquire: () => (() => void) | Promise<() => void>;
}
type ConcurrencyLimiterFn = <
Args extends unknown[],
T
>(func: (...args: Args) => PromiseLike<T> | T, ...args: Args) => Promise<T>;
/**
* Return a function for running multiple async operations with limited concurrency.
*/
declare function limitConcurrency(concurrency?: number): ConcurrencyLimiter;
/**
* Partition in tasks groups by consecutive concurrent
*/
declare function partitionSuiteChildren(suite: Suite): Task[][];
/**
* @experimental
*/
declare function matchesTags(testTags: string[]): boolean;
declare function validateTags(config: VitestRunnerConfig, tags: string[]): void;
declare function createTagsFilter(tagsExpr: string[], availableTags: TestTagDefinition[]): (testTags: string[]) => boolean;
declare function isTestCase(s: Task): s is Test;
declare function getTests(suite: Arrayable<Task>): Test[];
declare function getTasks(tasks?: Arrayable<Task>): Task[];
@@ -42,4 +54,4 @@ declare function getFullName(task: Task, separator?: string): string;
declare function getTestName(task: Task, separator?: string): string;
declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string;
export { calculateSuiteHash, createFileTask, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, partitionSuiteChildren, someTasksAreOnly };
export { calculateSuiteHash, createFileTask, createTagsFilter, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, matchesTags, partitionSuiteChildren, someTasksAreOnly, validateTags };
+4 -2
View File
@@ -1,5 +1,7 @@
export { a as calculateSuiteHash, c as createChainable, b as createFileTask, e as createTaskName, f as findTestFileStackTrace, g as generateFileHash, d as generateHash, h as getFullName, j as getNames, k as getSuites, m as getTasks, n as getTestName, o as getTests, q as hasFailed, r as hasTests, i as interpretTaskModes, t as isTestCase, l as limitConcurrency, p as partitionSuiteChildren, s as someTasksAreOnly } from './chunk-tasks.js';
export { x as calculateSuiteHash, y as createChainable, z as createFileTask, A as createTagsFilter, B as createTaskName, C as findTestFileStackTrace, D as generateFileHash, E as generateHash, F as getFullName, G as getNames, H as getSuites, I as getTasks, J as getTestName, K as getTests, L as hasFailed, M as hasTests, N as interpretTaskModes, O as isTestCase, P as limitConcurrency, Q as matchesTags, R as partitionSuiteChildren, S as someTasksAreOnly, T as validateTags } from './chunk-artifact.js';
import '@vitest/utils/error';
import '@vitest/utils/helpers';
import '@vitest/utils/timers';
import '@vitest/utils/display';
import '@vitest/utils/source-map';
import 'pathe';
import '@vitest/utils/helpers';
+8 -3
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/runner",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Vitest test runner",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/runner#readme",
"homepage": "https://vitest.dev/api/advanced/runner",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,11 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"test-runner"
],
"sideEffects": true,
"exports": {
".": {
@@ -39,7 +44,7 @@
],
"dependencies": {
"pathe": "^2.0.3",
"@vitest/utils": "4.0.18"
"@vitest/utils": "4.1.9"
},
"scripts": {
"build": "premove dist && rollup -c",
+4
View File
@@ -1,5 +1,7 @@
# @vitest/snapshot
[![NPM version](https://img.shields.io/npm/v/@vitest/snapshot?color=a1b858&label=)](https://npmx.dev/package/@vitest/snapshot)
Lightweight implementation of Jest's snapshots.
## Usage
@@ -82,3 +84,5 @@ manager.add(result)
console.log(manager.summary)
```
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/snapshot) | [Documentation](https://vitest.dev/guide/snapshot)
@@ -1,9 +1,4 @@
interface ParsedStack {
method: string;
file: string;
line: number;
column: number;
}
import { ParsedStack } from '@vitest/utils';
interface SnapshotEnvironment {
getVersion: () => string;
@@ -19,4 +14,4 @@ interface SnapshotEnvironmentOptions {
snapshotsDirName?: string;
}
export type { ParsedStack as P, SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };
export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };
+2 -1
View File
@@ -1,4 +1,5 @@
import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DHdQ1Csl.js';
import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DOJxxZV9.js';
import '@vitest/utils';
declare class NodeSnapshotEnvironment implements SnapshotEnvironment {
private options;
+1 -1
View File
@@ -1,5 +1,5 @@
import { promises, existsSync } from 'node:fs';
import { resolve, isAbsolute, dirname, join, basename } from 'pathe';
import { isAbsolute, resolve, dirname, join, basename } from 'pathe';
class NodeSnapshotEnvironment {
constructor(options = {}) {
+26 -82
View File
@@ -1,85 +1,8 @@
import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-lFsMJFUd.js';
export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-lFsMJFUd.js';
import { S as SnapshotEnvironment, P as ParsedStack } from './environment.d-DHdQ1Csl.js';
import { S as SnapshotState, a as SnapshotStateOptions, b as SnapshotResult, R as RawSnapshotInfo, D as DomainSnapshotAdapter } from './rawSnapshot.d-D_X3-62x.js';
export { c as DomainMatchResult, d as SnapshotData, e as SnapshotMatchOptions, f as SnapshotSerializer, g as SnapshotSummary, h as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-D_X3-62x.js';
import { Plugin, Plugins } from '@vitest/pretty-format';
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare class DefaultMap<
K,
V
> extends Map<K, V> {
private defaultFn;
constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>);
get(key: K): V;
}
declare class CounterMap<K> extends DefaultMap<K, number> {
constructor();
_total: number | undefined;
valueOf(): number;
increment(key: K): void;
total(): number;
}
interface SnapshotReturnOptions {
actual: string;
count: number;
expected?: string;
key: string;
pass: boolean;
}
interface SaveStatus {
deleted: boolean;
saved: boolean;
}
declare class SnapshotState {
testFilePath: string;
snapshotPath: string;
private _counters;
private _dirty;
private _updateSnapshot;
private _snapshotData;
private _initialData;
private _inlineSnapshots;
private _inlineSnapshotStacks;
private _testIdToKeys;
private _rawSnapshots;
private _uncheckedKeys;
private _snapshotFormat;
private _environment;
private _fileExists;
expand: boolean;
private _added;
private _matched;
private _unmatched;
private _updated;
get added(): CounterMap<string>;
set added(value: number);
get matched(): CounterMap<string>;
set matched(value: number);
get unmatched(): CounterMap<string>;
set unmatched(value: number);
get updated(): CounterMap<string>;
set updated(value: number);
private constructor();
static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
get environment(): SnapshotEnvironment;
markSnapshotsAsCheckedForTest(testName: string): void;
clearTest(testId: string): void;
protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
private _addSnapshot;
save(): Promise<SaveStatus>;
getUncheckedCount(): number;
getUncheckedKeys(): Array<string>;
removeUncheckedKeys(): void;
match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }: SnapshotMatchOptions): SnapshotReturnOptions;
pack(): Promise<SnapshotResult>;
}
export { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js';
import '@vitest/utils';
interface AssertOptions {
received: unknown;
@@ -97,6 +20,23 @@ interface AssertOptions {
error?: Error;
errorMessage?: string;
rawSnapshot?: RawSnapshotInfo;
assertionName?: string;
}
interface AssertDomainOptions extends Omit<AssertOptions, "received"> {
received: unknown;
adapter: DomainSnapshotAdapter<any, any>;
}
interface AssertDomainPollOptions extends Omit<AssertDomainOptions, "received"> {
poll: () => Promise<unknown> | unknown;
timeout?: number;
interval?: number;
}
/** Same shape as expect.extend custom matcher result (SyncExpectationResult from @vitest/expect) */
interface MatchResult {
pass: boolean;
message: () => string;
actual?: unknown;
expected?: unknown;
}
interface SnapshotClientOptions {
isEqual?: (received: unknown, expected: unknown) => boolean;
@@ -110,7 +50,10 @@ declare class SnapshotClient {
skipTest(filepath: string, testName: string): void;
clearTest(filepath: string, testId: string): void;
getSnapshotState(filepath: string): SnapshotState;
match(options: AssertOptions): MatchResult;
assert(options: AssertOptions): void;
matchDomain(options: AssertDomainOptions): MatchResult;
pollMatchDomain(options: AssertDomainPollOptions): Promise<MatchResult>;
assertRaw(options: AssertOptions): Promise<void>;
clear(): void;
}
@@ -127,4 +70,5 @@ declare function stripSnapshotIndentation(inlineSnapshot: string): string;
declare function addSerializer(plugin: Plugin): void;
declare function getSerializers(): Plugins;
export { SnapshotClient, SnapshotEnvironment, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation };
export { DomainSnapshotAdapter, SnapshotClient, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation };
export type { MatchResult };
+576 -825
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,6 +1,7 @@
import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-lFsMJFUd.js';
import { a as SnapshotStateOptions, g as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-D_X3-62x.js';
import '@vitest/pretty-format';
import './environment.d-DHdQ1Csl.js';
import '@vitest/utils';
import './environment.d-DOJxxZV9.js';
declare class SnapshotManager {
options: Omit<SnapshotStateOptions, "snapshotEnvironment">;
+1 -1
View File
@@ -1,4 +1,4 @@
import { join, dirname, basename, resolve, isAbsolute } from 'pathe';
import { join, dirname, basename, isAbsolute, resolve } from 'pathe';
class SnapshotManager {
summary;
+205
View File
@@ -0,0 +1,205 @@
import { OptionsReceived, Plugin } from '@vitest/pretty-format';
import { ParsedStack } from '@vitest/utils';
import { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js';
interface DomainMatchResult {
pass: boolean;
message?: string;
/**
* The captured value viewed through the template's lens.
*
* Where the template uses patterns (e.g. regexes) or omits details,
* the resolved string adopts those patterns. Where the template doesn't
* match, the resolved string uses literal captured values instead.
*
* Used for two purposes:
* - **Diff display** (actual side): compared against `expected`
* so the diff highlights only genuine mismatches, not pattern-vs-literal noise.
* - **Snapshot update** (`--update`): written as the new snapshot content,
* preserving user-edited patterns from matched regions while incorporating
* actual values for mismatched regions.
*
* When omitted, falls back to `render(capture(received))` (the raw rendered value).
*/
resolved?: string;
/**
* The stored template re-rendered as a string, representing what the user
* originally wrote or last saved.
*
* Used as the expected side in diff display.
*
* When omitted, falls back to the raw snapshot string from the snap file
* or inline snapshot.
*/
expected?: string;
}
interface DomainSnapshotAdapter<
Captured = unknown,
Expected = unknown
> {
name: string;
capture: (received: unknown) => Captured;
render: (captured: Captured) => string;
parseExpected: (input: string) => Expected;
match: (captured: Captured, expected: Expected) => DomainMatchResult;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare class DefaultMap<
K,
V
> extends Map<K, V> {
private defaultFn;
constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>);
get(key: K): V;
}
declare class CounterMap<K> extends DefaultMap<K, number> {
constructor();
_total: number | undefined;
valueOf(): number;
increment(key: K): void;
total(): number;
}
interface SnapshotReturnOptions {
actual: string;
count: number;
expected?: string;
key: string;
pass: boolean;
}
interface SaveStatus {
deleted: boolean;
saved: boolean;
}
interface ExpectedSnapshot {
key: string;
count: number;
data?: string;
markAsChecked: () => void;
}
declare class SnapshotState {
testFilePath: string;
snapshotPath: string;
private _counters;
private _dirty;
private _updateSnapshot;
private _snapshotData;
private _initialData;
private _inlineSnapshots;
private _inlineSnapshotStacks;
private _testIdToKeys;
private _rawSnapshots;
private _uncheckedKeys;
private _snapshotFormat;
private _environment;
private _fileExists;
expand: boolean;
private _added;
private _matched;
private _unmatched;
private _updated;
get added(): CounterMap<string>;
set added(value: number);
get matched(): CounterMap<string>;
set matched(value: number);
get unmatched(): CounterMap<string>;
set unmatched(value: number);
get updated(): CounterMap<string>;
set updated(value: number);
private constructor();
static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
get snapshotUpdateState(): SnapshotUpdateState;
get environment(): SnapshotEnvironment;
markSnapshotsAsCheckedForTest(testName: string): void;
clearTest(testId: string): void;
protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
private _addSnapshot;
private _resolveKey;
private _resolveInlineStack;
private _reconcile;
save(): Promise<SaveStatus>;
getUncheckedCount(): number;
getUncheckedKeys(): Array<string>;
removeUncheckedKeys(): void;
probeExpectedSnapshot(options: Pick<SnapshotMatchOptions, "testName" | "testId" | "isInline" | "inlineSnapshot">): ExpectedSnapshot;
match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }: SnapshotMatchOptions): SnapshotReturnOptions;
processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }: ProcessDomainSnapshotOptions): SnapshotReturnOptions;
pack(): Promise<SnapshotResult>;
}
type SnapshotData = Record<string, string>;
type SnapshotUpdateState = "all" | "new" | "none";
type SnapshotSerializer = Plugin;
interface SnapshotStateOptions {
updateSnapshot: SnapshotUpdateState;
snapshotEnvironment: SnapshotEnvironment;
expand?: boolean;
snapshotFormat?: OptionsReceived;
resolveSnapshotPath?: (path: string, extension: string, context?: any) => string;
}
interface SnapshotMatchOptions {
testId: string;
testName: string;
received: unknown;
key?: string;
inlineSnapshot?: string;
isInline: boolean;
error?: Error;
rawSnapshot?: RawSnapshotInfo;
assertionName?: string;
}
interface ProcessDomainSnapshotOptions {
testId: string;
received: string;
expectedSnapshot: ExpectedSnapshot;
matchResult?: DomainMatchResult;
isInline?: boolean;
assertionName?: string;
error?: Error;
}
interface SnapshotResult {
filepath: string;
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
}
interface UncheckedSnapshot {
filePath: string;
keys: Array<string>;
}
interface SnapshotSummary {
added: number;
didUpdate: boolean;
failure: boolean;
filesAdded: number;
filesRemoved: number;
filesRemovedList: Array<string>;
filesUnmatched: number;
filesUpdated: number;
matched: number;
total: number;
unchecked: number;
uncheckedKeysByFile: Array<UncheckedSnapshot>;
unmatched: number;
updated: number;
}
interface RawSnapshotInfo {
file: string;
readonly?: boolean;
content?: string;
}
export { SnapshotState as S };
export type { DomainSnapshotAdapter as D, RawSnapshotInfo as R, UncheckedSnapshot as U, SnapshotStateOptions as a, SnapshotResult as b, DomainMatchResult as c, SnapshotData as d, SnapshotMatchOptions as e, SnapshotSerializer as f, SnapshotSummary as g, SnapshotUpdateState as h };
-61
View File
@@ -1,61 +0,0 @@
import { OptionsReceived, Plugin } from '@vitest/pretty-format';
import { S as SnapshotEnvironment } from './environment.d-DHdQ1Csl.js';
type SnapshotData = Record<string, string>;
type SnapshotUpdateState = "all" | "new" | "none";
type SnapshotSerializer = Plugin;
interface SnapshotStateOptions {
updateSnapshot: SnapshotUpdateState;
snapshotEnvironment: SnapshotEnvironment;
expand?: boolean;
snapshotFormat?: OptionsReceived;
resolveSnapshotPath?: (path: string, extension: string, context?: any) => string;
}
interface SnapshotMatchOptions {
testId: string;
testName: string;
received: unknown;
key?: string;
inlineSnapshot?: string;
isInline: boolean;
error?: Error;
rawSnapshot?: RawSnapshotInfo;
}
interface SnapshotResult {
filepath: string;
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
}
interface UncheckedSnapshot {
filePath: string;
keys: Array<string>;
}
interface SnapshotSummary {
added: number;
didUpdate: boolean;
failure: boolean;
filesAdded: number;
filesRemoved: number;
filesRemovedList: Array<string>;
filesUnmatched: number;
filesUpdated: number;
matched: number;
total: number;
unchecked: number;
uncheckedKeysByFile: Array<UncheckedSnapshot>;
unmatched: number;
updated: number;
}
interface RawSnapshotInfo {
file: string;
readonly?: boolean;
content?: string;
}
export type { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotSerializer as d, SnapshotSummary as e, SnapshotUpdateState as f };
+10 -5
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/snapshot",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Vitest snapshot manager",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/snapshot#readme",
"homepage": "https://vitest.dev/guide/snapshot",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,11 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"snapshot"
],
"sideEffects": false,
"exports": {
".": {
@@ -40,12 +45,12 @@
"dependencies": {
"magic-string": "^0.30.21",
"pathe": "^2.0.3",
"@vitest/pretty-format": "4.0.18"
"@vitest/pretty-format": "4.1.9",
"@vitest/utils": "4.1.9"
},
"devDependencies": {
"@types/natural-compare": "^1.4.3",
"natural-compare": "^1.4.0",
"@vitest/utils": "4.0.18"
"natural-compare": "^1.4.0"
},
"scripts": {
"build": "premove dist && rollup -c",
+5 -1
View File
@@ -1,3 +1,7 @@
# @vitest/spy
Lightweight Jest compatible spy implementation.
[![NPM version](https://img.shields.io/npm/v/@vitest/spy?color=a1b858&label=)](https://npmx.dev/package/@vitest/spy)
Lightweight Jest-compatible mocking implementation.
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/spy) | [Documentation](https://vitest.dev/api/mock)
+38 -6
View File
@@ -1,3 +1,5 @@
import { Disposable } from '@vitest/spy/optional-types.js';
interface MockResultReturn<T> {
type: "return";
/**
@@ -31,7 +33,7 @@ interface MockSettledResultRejected {
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected | MockSettledResultIncomplete;
type MockParameters<T extends Procedure | Constructable> = T extends Constructable ? ConstructorParameters<T> : T extends Procedure ? Parameters<T> : never;
type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? void : T extends Procedure ? ReturnType<T> : never;
type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : T extends Procedure ? ReturnType<T> : never;
type MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>;
interface MockContext<T extends Procedure | Constructable = Procedure> {
/**
@@ -173,7 +175,7 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
/**
* Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
*
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration.
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/clearmocks) setting in the configuration.
* @see https://vitest.dev/api/mock#mockclear
*/
mockClear(): this;
@@ -183,7 +185,7 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
* Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`.
* Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state.
*
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration.
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/mockreset) setting in the configuration.
* @see https://vitest.dev/api/mock#mockreset
*/
mockReset(): this;
@@ -267,6 +269,28 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
*/
mockReturnValueOnce(value: MockReturnType<T>): this;
/**
* Accepts a value that will be thrown whenever the mock function is called.
* @see https://vitest.dev/api/mock#mockthrow
* @example
* const myMockFn = vi.fn().mockThrow(new Error('error'))
* myMockFn() // throws 'error'
*/
mockThrow(value: unknown): this;
/**
* Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value.
* @example
* const myMockFn = vi
* .fn()
* .mockReturnValue('default')
* .mockThrowOnce(new Error('first call error'))
* .mockThrowOnce('second call error')
*
* expect(() => myMockFn()).toThrowError('first call error')
* expect(() => myMockFn()).toThrowError('second call error')
* expect(myMockFn()).toEqual('default')
*/
mockThrowOnce(value: unknown): this;
/**
* Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
* @example
* const asyncMock = vi.fn().mockResolvedValue(42)
@@ -322,11 +346,19 @@ type PartialResultFunction<T> = T extends Constructable ? ({
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
}) : T extends Procedure ? (...args: Parameters<T>) => PartialMaybePromise<ReturnType<T>> : T;
type PartialMock<T extends Procedure | Constructable = Procedure> = Mock<PartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
type DeepPartial<T> = T extends Procedure ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends object ? { [K in keyof T]? : DeepPartial<T[K]> } : T;
type DeepPartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<DeepPartial<Awaited<T>>> : DeepPartial<T>;
type DeepPartialResultFunction<T> = T extends Constructable ? ({
new (...args: ConstructorParameters<T>): InstanceType<T>;
}) | ({
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
}) : T extends Procedure ? (...args: Parameters<T>) => DeepPartialMaybePromise<ReturnType<T>> : T;
type DeepPartialMock<T extends Procedure | Constructable = Procedure> = Mock<DeepPartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
type MaybeMockedConstructor<T> = T extends Constructable ? Mock<T> : T;
type MockedFunction<T extends Procedure | Constructable> = Mock<T> & { [K in keyof T] : T[K] };
type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & { [K in keyof T] : T[K] };
type MockedFunction<T extends Procedure | Constructable> = Mock<T> & MockedObject<T>;
type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & MockedObject<T>;
type MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>;
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartialMock<T> & MockedObjectDeep<T>;
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = DeepPartialMock<T> & MockedObjectDeep<T>;
type MockedObject<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunction<T[K]> : T[K] } & { [K in Properties<T>] : T[K] };
type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K] } & { [K in Properties<T>] : MaybeMockedDeep<T[K]> };
type MaybeMockedDeep<T> = T extends Procedure | Constructable ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
+72 -22
View File
@@ -8,7 +8,6 @@ const MOCK_RESTORE = new Set();
const REGISTERED_MOCKS = new Set();
const MOCK_CONFIGS = new WeakMap();
function createMockInstance(options = {}) {
var _ref;
const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options;
if (restore) {
MOCK_RESTORE.add(restore);
@@ -20,7 +19,7 @@ function createMockInstance(options = {}) {
state,
...options
});
const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0;
const mockLength = (mockImplementation || originalImplementation)?.length ?? 0;
Object.defineProperty(mock, "length", {
writable: true,
enumerable: false,
@@ -65,7 +64,7 @@ function createMockInstance(options = {}) {
config.mockImplementation = implementation;
config.onceMockImplementations = [];
const returnValue = callback();
if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") {
if (typeof returnValue === "object" && typeof returnValue?.then === "function") {
return returnValue.then(() => {
reset();
return mock;
@@ -81,22 +80,64 @@ function createMockInstance(options = {}) {
});
};
mock.mockReturnValue = function mockReturnValue(value) {
return mock.mockImplementation(() => value);
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockReturnValue");
}
return value;
});
};
mock.mockReturnValueOnce = function mockReturnValueOnce(value) {
return mock.mockImplementationOnce(() => value);
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockReturnValueOnce");
}
return value;
});
};
mock.mockThrow = function mockThrow(value) {
// eslint-disable-next-line prefer-arrow-callback
return mock.mockImplementation(function() {
throw value;
});
};
mock.mockThrowOnce = function mockThrowOnce(value) {
// eslint-disable-next-line prefer-arrow-callback
return mock.mockImplementationOnce(function() {
throw value;
});
};
mock.mockResolvedValue = function mockResolvedValue(value) {
return mock.mockImplementation(() => Promise.resolve(value));
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockResolvedValue");
}
return Promise.resolve(value);
});
};
mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.resolve(value));
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockResolvedValueOnce");
}
return Promise.resolve(value);
});
};
mock.mockRejectedValue = function mockRejectedValue(value) {
return mock.mockImplementation(() => Promise.reject(value));
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockRejectedValue");
}
return Promise.reject(value);
});
};
mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.reject(value));
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockRejectedValueOnce");
}
return Promise.reject(value);
});
};
mock.mockClear = function mockClear() {
state.calls = [];
@@ -116,7 +157,7 @@ function createMockInstance(options = {}) {
};
mock.mockRestore = function mockRestore() {
mock.mockReset();
return restore === null || restore === void 0 ? void 0 : restore();
return restore?.();
};
mock.mockName = function mockName(name) {
if (typeof name === "string") {
@@ -137,7 +178,7 @@ function createMockInstance(options = {}) {
}
function fn(originalImplementation) {
// if the function is already a mock, just return the same function,
// simillarly to how vi.spyOn() works
// similarly to how vi.spyOn() works
if (originalImplementation != null && isMockFunction(originalImplementation)) {
return originalImplementation;
}
@@ -161,6 +202,12 @@ function spyOn(object, key, accessor) {
let original;
if (originalDescriptor) {
original = originalDescriptor[accessType];
// weird Proxy edge case where descriptor's value is undefined,
// but there's still a value on the object when called
// https://github.com/vitest-dev/vitest/issues/9439
if (original == null && accessType === "value") {
original = object[key];
}
} else if (accessType !== "value") {
original = () => object[key];
} else {
@@ -236,7 +283,7 @@ let invocationCallCounter = 1;
function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) {
const original = config.mockOriginal;
const pseudoOriginal = mockImplementation;
const name = mockName || (original === null || original === void 0 ? void 0 : original.name) || "Mock";
const name = mockName || original?.name || "Mock";
const namedObject = { [name]: (function(...args) {
registerCalls(args, state, prototypeState);
registerInvocationOrder(invocationCallCounter++, state, prototypeState);
@@ -253,7 +300,7 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
const context = new.target ? undefined : this;
const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState);
const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState);
const implementation = config.onceMockImplementations.shift() || config.mockImplementation || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.onceMockImplementations.shift()) || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockImplementation) || original || function() {};
const implementation = config.onceMockImplementations.shift() || config.mockImplementation || prototypeConfig?.onceMockImplementations.shift() || prototypeConfig?.mockImplementation || original || function() {};
let returnValue;
let thrownValue;
let didThrow = false;
@@ -262,11 +309,11 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
returnValue = Reflect.construct(implementation, args, new.target);
// jest calls this before the implementation, but we have to resolve this _after_
// because we cannot do it before the `Reflect.construct` called the custom implementation.
// fortunetly, the constructor is always an empty functon because `prototypeMethods`
// fortunately, the constructor is always an empty function because `prototypeMethods`
// are only used by the automocker, so this doesn't matter
for (const prop of prototypeMembers) {
const prototypeMock = returnValue[prop];
// the method was overidden because of inheritence, ignore it
// the method was overridden because of inheritance, ignore it
// eslint-disable-next-line ts/no-use-before-define
if (prototypeMock !== mock.prototype[prop]) {
continue;
@@ -275,7 +322,7 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
const prototypeState = isMock ? prototypeMock.mock : undefined;
const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined;
returnValue[prop] = createMockInstance({
originalImplementation: keepMembersImplementation ? prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockOriginal : undefined,
originalImplementation: keepMembersImplementation ? prototypeConfig?.mockOriginal : undefined,
prototypeState,
prototypeConfig,
keepMembersImplementation
@@ -335,28 +382,28 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
}
function registerCalls(args, state, prototypeState) {
state.calls.push(args);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args);
prototypeState?.calls.push(args);
}
function registerInvocationOrder(order, state, prototypeState) {
state.invocationCallOrder.push(order);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order);
prototypeState?.invocationCallOrder.push(order);
}
function registerResult(result, state, prototypeState) {
state.results.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result);
prototypeState?.results.push(result);
}
function registerSettledResult(result, state, prototypeState) {
state.settledResults.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.settledResults.push(result);
prototypeState?.settledResults.push(result);
}
function registerInstance(instance, state, prototypeState) {
const instanceIndex = state.instances.push(instance);
const instancePrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.instances.push(instance);
const instancePrototypeIndex = prototypeState?.instances.push(instance);
return [instanceIndex, instancePrototypeIndex];
}
function registerContext(context, state, prototypeState) {
const contextIndex = state.contexts.push(context);
const contextPrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.contexts.push(context);
const contextPrototypeIndex = prototypeState?.contexts.push(context);
return [contextIndex, contextPrototypeIndex];
}
function copyOriginalStaticProperties(mock, original) {
@@ -429,5 +476,8 @@ function clearAllMocks() {
function resetAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockReset());
}
function throwConstructorError(shorthand) {
throw new TypeError(`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`);
}
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };
+6
View File
@@ -0,0 +1,6 @@
/* eslint-disable ts/ban-ts-comment */
export interface Disposable {
// @ts-ignore -- Symbol.dispose might not be in user types
[Symbol.dispose]: () => void
}
+14 -3
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/spy",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Lightweight Jest compatible spy implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme",
"homepage": "https://vitest.dev/api/mock",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,19 +14,30 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock",
"spy",
"intercept"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./optional-types.js": {
"types": "./optional-types.d.ts"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
"dist",
"optional-types.d.ts"
],
"scripts": {
"build": "premove dist && rollup -c",
+7
View File
@@ -0,0 +1,7 @@
# @vitest/utils
[![NPM version](https://img.shields.io/npm/v/@vitest/utils?color=a1b858&label=)](https://npmx.dev/package/@vitest/utils)
Internal shared utilities used by other Vitest packages.
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/utils) | [Documentation](https://vitest.dev/)
-5
View File
@@ -1,5 +0,0 @@
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
export { getDefaultExportFromCjs as g };
+20 -4
View File
@@ -1,6 +1,6 @@
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { D as DiffOptions } from './types.d-BCElaP-c.js';
export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js';
import '@vitest/pretty-format';
/**
* Diff Match and Patch
@@ -75,14 +75,29 @@ declare function diffLinesRaw(aLines: Array<string>, bLines: Array<string>, opti
declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string;
declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array<Diff>, boolean];
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
interface StringifiedMemory {
expected?: string;
actual?: string;
}
interface Memorize {
(pointer: "expected" | "actual", stringifiedValue: string): string;
}
/**
* @param a Expected value
* @param b Received value
* @param options Diff options
* @returns {string | null} a string diff
*/
declare function diff(a: any, b: any, options?: DiffOptions): string | undefined;
declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions): string | undefined;
declare function diff(a: any, b: any, options?: DiffOptions, memorize?: Memorize): string | undefined;
declare function getDefaultFormatOptions(options?: DiffOptions): PrettyFormatOptions;
declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions, memory?: StringifiedMemory): string | undefined;
declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet<WeakKey>, expectedReplaced?: WeakSet<WeakKey>): {
replacedActual: any;
replacedExpected: any;
@@ -90,4 +105,5 @@ declare function replaceAsymmetricMatcher(actual: any, expected: any, actualRepl
type PrintLabel = (string: string) => string;
declare function getLabelPrinter(...strings: Array<string>): PrintLabel;
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getDefaultFormatOptions, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export type { StringifiedMemory };
+41 -28
View File
@@ -2,7 +2,6 @@ import { plugins, format } from '@vitest/pretty-format';
import c from 'tinyrainbow';
import { stringify } from './display.js';
import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js';
import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
import './constants.js';
/**
@@ -333,7 +332,6 @@ function diff_cleanupSemanticLossless(diffs) {
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
function diff_cleanupMerge(diffs) {
var _diffs$at;
// Add a dummy entry at the end.
diffs.push(new Diff(DIFF_EQUAL, ""));
let pointer = 0;
@@ -404,7 +402,7 @@ function diff_cleanupMerge(diffs) {
break;
}
}
if (((_diffs$at = diffs.at(-1)) === null || _diffs$at === void 0 ? void 0 : _diffs$at[1]) === "") {
if (diffs.at(-1)?.[1] === "") {
diffs.pop();
}
// Second pass: look for single edits surrounded on both sides by equalities
@@ -495,6 +493,10 @@ function diff_cleanupSemanticScore_(one, two) {
const NO_DIFF_MESSAGE = "Compared values have no visual difference.";
const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead.";
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var build = {};
var hasRequiredBuild;
@@ -1623,8 +1625,8 @@ function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCo
}
// Compare two arrays of strings line-by-line.
function diffLinesRaw(aLines, bLines, options) {
const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
const truncate = options?.truncateThreshold ?? false;
const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length;
const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length;
const truncated = aLength !== aLines.length || bLength !== bLines.length;
@@ -1697,8 +1699,8 @@ function getNewLineSymbol(string) {
return string.includes("\r\n") ? "\r\n" : "\n";
}
function diffStrings(a, b, options) {
const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
const truncate = options?.truncateThreshold ?? false;
const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
let aLength = a.length;
let bLength = b.length;
if (truncate) {
@@ -1966,6 +1968,7 @@ const FALLBACK_FORMAT_OPTIONS = {
maxDepth: 8,
plugins: PLUGINS
};
const DEFAULT_MEMORIZE = (_, v) => v;
// Generate a string that will highlight the difference between two values
// with green and red. (similar to how github does code diffing)
/**
@@ -1974,7 +1977,7 @@ const FALLBACK_FORMAT_OPTIONS = {
* @param options Diff options
* @returns {string | null} a string diff
*/
function diff(a, b, options) {
function diff(a, b, options, memorize = DEFAULT_MEMORIZE) {
if (Object.is(a, b)) {
return "";
}
@@ -2008,10 +2011,10 @@ function diff(a, b, options) {
function truncate(s) {
return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`;
}
aDisplay = truncate(aDisplay);
bDisplay = truncate(bDisplay);
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`;
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`;
aDisplay = memorize("expected", truncate(aDisplay));
bDisplay = memorize("actual", truncate(bDisplay));
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)}\n${aDisplay}`;
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)}\n${bDisplay}`;
return `${aDiff}\n\n${bDiff}`;
}
if (omitDifference) {
@@ -2020,15 +2023,21 @@ function diff(a, b, options) {
switch (aType) {
case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options);
case "boolean":
case "number": return comparePrimitive(a, b, options);
case "map": return compareObjects(sortMap(a), sortMap(b), options);
case "set": return compareObjects(sortSet(a), sortSet(b), options);
default: return compareObjects(a, b, options);
case "number": return comparePrimitive(a, b, options, memorize);
case "map": return compareObjects(sortMap(a), sortMap(b), options, memorize);
case "set": return compareObjects(sortSet(a), sortSet(b), options, memorize);
default: return compareObjects(a, b, options, memorize);
}
}
function comparePrimitive(a, b, options) {
const aFormat = format(a, FORMAT_OPTIONS);
const bFormat = format(b, FORMAT_OPTIONS);
function createMemorize(memory) {
return (pointer, stringifiedValue) => {
memory[pointer] = stringifiedValue;
return stringifiedValue;
};
}
function comparePrimitive(a, b, options, memorize = DEFAULT_MEMORIZE) {
const aFormat = memorize("expected", format(a, FORMAT_OPTIONS));
const bFormat = memorize("actual", format(b, FORMAT_OPTIONS));
return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options);
}
function sortMap(map) {
@@ -2037,12 +2046,12 @@ function sortMap(map) {
function sortSet(set) {
return new Set(Array.from(set.values()).sort());
}
function compareObjects(a, b, options) {
function compareObjects(a, b, options, memorize = DEFAULT_MEMORIZE) {
let difference;
let hasThrown = false;
try {
const formatOptions = getFormatOptions(FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b, formatOptions, options);
difference = getObjectsDifference(a, b, formatOptions, options, memorize);
} catch {
hasThrown = true;
}
@@ -2051,13 +2060,16 @@ function compareObjects(a, b, options) {
// without calling `toJSON`. It's also possible that toJSON might throw.
if (difference === undefined || difference === noDiffMessage) {
const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b, formatOptions, options);
difference = getObjectsDifference(a, b, formatOptions, options, memorize);
if (difference !== noDiffMessage && !hasThrown) {
difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`;
}
}
return difference;
}
function getDefaultFormatOptions(options) {
return getFormatOptions(FORMAT_OPTIONS, options);
}
function getFormatOptions(formatOptions, options) {
const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options);
return {
@@ -2067,7 +2079,7 @@ function getFormatOptions(formatOptions, options) {
maxDepth: maxDepth ?? formatOptions.maxDepth
};
}
function getObjectsDifference(a, b, formatOptions, options) {
function getObjectsDifference(a, b, formatOptions, options, memorize = DEFAULT_MEMORIZE) {
const formatOptionsZeroIndent = {
...formatOptions,
indent: 0
@@ -2077,8 +2089,8 @@ function getObjectsDifference(a, b, formatOptions, options) {
if (aCompare === bCompare) {
return getCommonMessage(NO_DIFF_MESSAGE, options);
} else {
const aDisplay = format(a, formatOptions);
const bDisplay = format(b, formatOptions);
const aDisplay = memorize("expected", format(a, formatOptions));
const bDisplay = memorize("actual", format(b, formatOptions));
return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options);
}
}
@@ -2092,7 +2104,7 @@ function isReplaceable(obj1, obj2) {
const obj2Type = getType$1(obj2);
return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array");
}
function printDiffOrStringify(received, expected, options) {
function printDiffOrStringify(received, expected, options, memory) {
const { aAnnotation, bAnnotation } = normalizeDiffOptions(options);
if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) {
if (expected.includes("\n") || received.includes("\n")) {
@@ -2109,7 +2121,8 @@ function printDiffOrStringify(received, expected, options) {
const clonedExpected = deepClone(expected, { forceWritable: true });
const clonedReceived = deepClone(received, { forceWritable: true });
const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected);
const difference = diff(replacedExpected, replacedActual, options);
const memorize = memory ? createMemorize(memory) : DEFAULT_MEMORIZE;
const difference = diff(replacedExpected, replacedActual, options, memorize);
return difference;
// }
// const printLabel = getLabelPrinter(aAnnotation, bAnnotation)
@@ -2196,4 +2209,4 @@ function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) {
return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), "");
}
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getDefaultFormatOptions, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
+2 -1
View File
@@ -17,8 +17,9 @@ interface Options {
type LoupeOptions = Partial<Options>;
interface StringifyOptions extends PrettyFormatOptions {
maxLength?: number;
filterNode?: string | ((node: any) => boolean);
}
declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: StringifyOptions): string;
declare function stringify(object: unknown, maxDepth?: number, { maxLength, filterNode, ...options }?: StringifyOptions): string;
declare const formatRegExp: RegExp;
declare function format(...args: unknown[]): string;
declare function browserFormat(...args: unknown[]): string;
+38 -5
View File
@@ -1,4 +1,4 @@
import { plugins, format as format$1 } from '@vitest/pretty-format';
import { plugins, createDOMElementFilter, format as format$1 } from '@vitest/pretty-format';
const ansiColors = {
bold: ['1', '22'],
@@ -583,14 +583,24 @@ const PLUGINS = [
Immutable,
AsymmetricMatcher
];
function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) {
function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
const MAX_LENGTH = maxLength ?? 1e4;
let result;
// Convert string selector to filter function
const filterFn = typeof filterNode === "string" ? createNodeFilterFromSelector(filterNode) : filterNode;
const plugins = filterFn ? [
ReactTestComponent,
ReactElement,
createDOMElementFilter(filterFn),
DOMCollection,
Immutable,
AsymmetricMatcher
] : PLUGINS;
try {
result = format$1(object, {
maxDepth,
escapeString: false,
plugins: PLUGINS,
plugins,
...options
});
} catch {
@@ -598,16 +608,36 @@ function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) {
callToJSON: false,
maxDepth,
escapeString: false,
plugins: PLUGINS,
plugins,
...options
});
}
// Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249
return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
maxLength,
filterNode,
...options
}) : result;
}
function createNodeFilterFromSelector(selector) {
const ELEMENT_NODE = 1;
const COMMENT_NODE = 8;
return (node) => {
// Filter out comments
if (node.nodeType === COMMENT_NODE) {
return false;
}
// Filter out elements matching the selector
if (node.nodeType === ELEMENT_NODE && node.matches) {
try {
return !node.matches(selector);
} catch {
return true;
}
}
return true;
};
}
const formatRegExp = /%[sdjifoOc%]/g;
function baseFormat(args, options = {}) {
const formatArg = (item, inspecOptions) => {
@@ -664,6 +694,9 @@ function baseFormat(args, options = {}) {
if (typeof value === "bigint") {
return `${value.toString()}n`;
}
if (typeof value === "symbol") {
return "NaN";
}
return Number(value).toString();
}
case "%i": {
@@ -697,7 +730,7 @@ function baseFormat(args, options = {}) {
});
for (let x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== "object") {
str += ` ${x}`;
str += ` ${typeof x === "symbol" ? x.toString() : x}`;
} else {
str += ` ${formatArg(x)}`;
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { D as DiffOptions } from './types.d-BCElaP-c.js';
import { TestError } from './types.js';
export { serializeValue as serializeError } from './serialize.js';
import '@vitest/pretty-format';
declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): TestError;
export { processError };
+15 -13
View File
@@ -1,11 +1,10 @@
import { printDiffOrStringify } from './diff.js';
import { stringify } from './display.js';
import { format } from '@vitest/pretty-format';
import { printDiffOrStringify, getDefaultFormatOptions } from './diff.js';
import { serializeValue } from './serialize.js';
import '@vitest/pretty-format';
import 'tinyrainbow';
import './display.js';
import './helpers.js';
import './constants.js';
import './chunk-_commonjsHelpers.js';
function processError(_err, diffOptions, seen = new WeakSet()) {
if (!_err || typeof _err !== "object") {
@@ -13,16 +12,13 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
}
const err = _err;
if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) {
err.diff = printDiffOrStringify(err.actual, err.expected, {
const options = {
...diffOptions,
...err.diffOptions
});
}
if ("expected" in err && typeof err.expected !== "string") {
err.expected = stringify(err.expected, 10);
}
if ("actual" in err && typeof err.actual !== "string") {
err.actual = stringify(err.actual, 10);
};
err.diff = printDiffOrStringify(err.actual, err.expected, options, err);
err.expected = prettifyValue(err.expected, options);
err.actual = prettifyValue(err.actual, options);
}
// some Error implementations may not allow rewriting cause
// in most cases, the assignment will lead to "err.cause = err.cause"
@@ -35,8 +31,14 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
try {
return serializeValue(err);
} catch (e) {
return serializeValue(new Error(`Failed to fully serialize error: ${e === null || e === void 0 ? void 0 : e.message}\nInner error message: ${err === null || err === void 0 ? void 0 : err.message}`));
return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`));
}
}
function prettifyValue(value, options) {
if (typeof value !== "string") {
return format(value, getDefaultFormatOptions(options));
}
return value;
}
export { processError, serializeValue as serializeError };
+8 -1
View File
@@ -23,6 +23,10 @@ declare function assertTypes(value: unknown, name: string, types: string[]): voi
declare function isPrimitive(value: unknown): boolean;
declare function slash(path: string): string;
declare function cleanUrl(url: string): string;
declare function splitFileAndPostfix(path: string): {
file: string;
postfix: string;
};
declare const isExternalUrl: (url: string) => boolean;
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
@@ -35,6 +39,7 @@ declare function wrapId(id: string): string;
*/
declare function unwrapId(id: string): string;
declare function withTrailingSlash(path: string): string;
declare function filterOutComments(s: string): string;
declare function isBareImport(id: string): boolean;
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
declare function isObject(item: unknown): boolean;
@@ -60,6 +65,7 @@ declare function createDefer<T>(): DeferPromise<T>;
*/
declare function getCallLastIndex(code: string): number | null;
declare function isNegativeNaN(val: number): boolean;
declare function ordinal(i: number): string;
/**
* Deep merge :P
*
@@ -68,6 +74,7 @@ declare function isNegativeNaN(val: number): boolean;
* Do not merge types - it is very expensive and usually it's better to case a type here
*/
declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T;
declare function unique<T>(array: T[]): T[];
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId };
export type { DeferPromise };
+50 -1
View File
@@ -66,6 +66,13 @@ const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path) {
const file = cleanUrl(path);
return {
file,
postfix: path.slice(file.length)
};
}
const externalRE = /^(?:[a-z]+:)?\/\//;
const isExternalUrl = (url) => externalRE.test(url);
/**
@@ -88,6 +95,31 @@ function withTrailingSlash(path) {
}
return path;
}
function filterOutComments(s) {
const result = [];
let commentState = "none";
for (let i = 0; i < s.length; ++i) {
if (commentState === "singleline") {
if (s[i] === "\n") {
commentState = "none";
}
} else if (commentState === "multiline") {
if (s[i - 1] === "*" && s[i] === "/") {
commentState = "none";
}
} else if (commentState === "none") {
if (s[i] === "/" && s[i + 1] === "/") {
commentState = "singleline";
} else if (s[i] === "/" && s[i + 1] === "*") {
commentState = "multiline";
i += 2;
} else {
result.push(s[i]);
}
}
}
return result.join("");
}
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
function isBareImport(id) {
return bareImportRE.test(id);
@@ -261,6 +293,20 @@ function isPlainObject(val) {
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
function ordinal(i) {
const j = i % 10;
const k = i % 100;
if (j === 1 && k !== 11) {
return `${i}st`;
}
if (j === 2 && k !== 12) {
return `${i}nd`;
}
if (j === 3 && k !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
/**
* Deep merge :P
*
@@ -291,5 +337,8 @@ function deepMerge(target, ...sources) {
}
return deepMerge(target, ...sources);
}
function unique(array) {
return Array.from(new Set(array));
}
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId };
-9
View File
@@ -1,9 +0,0 @@
import { Colors } from 'tinyrainbow';
interface HighlightOptions {
jsx?: boolean;
colors?: Colors;
}
declare function highlight(code: string, options?: HighlightOptions): string;
export { highlight };
-538
View File
@@ -1,538 +0,0 @@
import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
import c from 'tinyrainbow';
var jsTokens_1;
var hasRequiredJsTokens;
function requireJsTokens () {
if (hasRequiredJsTokens) return jsTokens_1;
hasRequiredJsTokens = 1;
// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
// License: MIT.
var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
jsTokens_1 = function*(input, {jsx = false} = {}) {
var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
({length} = input);
lastIndex = 0;
lastSignificantToken = "";
stack = [
{tag: "JS"}
];
braces = [];
parenNesting = 0;
postfixIncDec = false;
while (lastIndex < length) {
mode = stack[stack.length - 1];
switch (mode.tag) {
case "JS":
case "JSNonExpressionParen":
case "InterpolationInTemplate":
case "InterpolationInJSX":
if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
RegularExpressionLiteral.lastIndex = lastIndex;
if (match = RegularExpressionLiteral.exec(input)) {
lastIndex = RegularExpressionLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "RegularExpressionLiteral",
value: match[0],
closed: match[1] !== void 0 && match[1] !== "\\"
});
continue;
}
}
Punctuator.lastIndex = lastIndex;
if (match = Punctuator.exec(input)) {
punctuator = match[0];
nextLastIndex = Punctuator.lastIndex;
nextLastSignificantToken = punctuator;
switch (punctuator) {
case "(":
if (lastSignificantToken === "?NonExpressionParenKeyword") {
stack.push({
tag: "JSNonExpressionParen",
nesting: parenNesting
});
}
parenNesting++;
postfixIncDec = false;
break;
case ")":
parenNesting--;
postfixIncDec = true;
if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
stack.pop();
nextLastSignificantToken = "?NonExpressionParenEnd";
postfixIncDec = false;
}
break;
case "{":
Punctuator.lastIndex = 0;
isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
braces.push(isExpression);
postfixIncDec = false;
break;
case "}":
switch (mode.tag) {
case "InterpolationInTemplate":
if (braces.length === mode.nesting) {
Template.lastIndex = lastIndex;
match = Template.exec(input);
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
postfixIncDec = false;
yield ({
type: "TemplateMiddle",
value: match[0]
});
} else {
stack.pop();
postfixIncDec = true;
yield ({
type: "TemplateTail",
value: match[0],
closed: match[1] === "`"
});
}
continue;
}
break;
case "InterpolationInJSX":
if (braces.length === mode.nesting) {
stack.pop();
lastIndex += 1;
lastSignificantToken = "}";
yield ({
type: "JSXPunctuator",
value: "}"
});
continue;
}
}
postfixIncDec = braces.pop();
nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
break;
case "]":
postfixIncDec = true;
break;
case "++":
case "--":
nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
break;
case "<":
if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
stack.push({tag: "JSXTag"});
lastIndex += 1;
lastSignificantToken = "<";
yield ({
type: "JSXPunctuator",
value: punctuator
});
continue;
}
postfixIncDec = false;
break;
default:
postfixIncDec = false;
}
lastIndex = nextLastIndex;
lastSignificantToken = nextLastSignificantToken;
yield ({
type: "Punctuator",
value: punctuator
});
continue;
}
Identifier.lastIndex = lastIndex;
if (match = Identifier.exec(input)) {
lastIndex = Identifier.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "for":
case "if":
case "while":
case "with":
if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
nextLastSignificantToken = "?NonExpressionParenKeyword";
}
}
lastSignificantToken = nextLastSignificantToken;
postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
yield ({
type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
value: match[0]
});
continue;
}
StringLiteral.lastIndex = lastIndex;
if (match = StringLiteral.exec(input)) {
lastIndex = StringLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "StringLiteral",
value: match[0],
closed: match[2] !== void 0
});
continue;
}
NumericLiteral.lastIndex = lastIndex;
if (match = NumericLiteral.exec(input)) {
lastIndex = NumericLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "NumericLiteral",
value: match[0]
});
continue;
}
Template.lastIndex = lastIndex;
if (match = Template.exec(input)) {
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
stack.push({
tag: "InterpolationInTemplate",
nesting: braces.length
});
postfixIncDec = false;
yield ({
type: "TemplateHead",
value: match[0]
});
} else {
postfixIncDec = true;
yield ({
type: "NoSubstitutionTemplate",
value: match[0],
closed: match[1] === "`"
});
}
continue;
}
break;
case "JSXTag":
case "JSXTagEnd":
JSXPunctuator.lastIndex = lastIndex;
if (match = JSXPunctuator.exec(input)) {
lastIndex = JSXPunctuator.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "<":
stack.push({tag: "JSXTag"});
break;
case ">":
stack.pop();
if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
nextLastSignificantToken = "?JSX";
postfixIncDec = true;
} else {
stack.push({tag: "JSXChildren"});
}
break;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
nextLastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
break;
case "/":
if (lastSignificantToken === "<") {
stack.pop();
if (stack[stack.length - 1].tag === "JSXChildren") {
stack.pop();
}
stack.push({tag: "JSXTagEnd"});
}
}
lastSignificantToken = nextLastSignificantToken;
yield ({
type: "JSXPunctuator",
value: match[0]
});
continue;
}
JSXIdentifier.lastIndex = lastIndex;
if (match = JSXIdentifier.exec(input)) {
lastIndex = JSXIdentifier.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXIdentifier",
value: match[0]
});
continue;
}
JSXString.lastIndex = lastIndex;
if (match = JSXString.exec(input)) {
lastIndex = JSXString.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXString",
value: match[0],
closed: match[2] !== void 0
});
continue;
}
break;
case "JSXChildren":
JSXText.lastIndex = lastIndex;
if (match = JSXText.exec(input)) {
lastIndex = JSXText.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXText",
value: match[0]
});
continue;
}
switch (input[lastIndex]) {
case "<":
stack.push({tag: "JSXTag"});
lastIndex++;
lastSignificantToken = "<";
yield ({
type: "JSXPunctuator",
value: "<"
});
continue;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
lastIndex++;
lastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
yield ({
type: "JSXPunctuator",
value: "{"
});
continue;
}
}
WhiteSpace.lastIndex = lastIndex;
if (match = WhiteSpace.exec(input)) {
lastIndex = WhiteSpace.lastIndex;
yield ({
type: "WhiteSpace",
value: match[0]
});
continue;
}
LineTerminatorSequence.lastIndex = lastIndex;
if (match = LineTerminatorSequence.exec(input)) {
lastIndex = LineTerminatorSequence.lastIndex;
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
yield ({
type: "LineTerminatorSequence",
value: match[0]
});
continue;
}
MultiLineComment.lastIndex = lastIndex;
if (match = MultiLineComment.exec(input)) {
lastIndex = MultiLineComment.lastIndex;
if (Newline.test(match[0])) {
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
}
yield ({
type: "MultiLineComment",
value: match[0],
closed: match[1] !== void 0
});
continue;
}
SingleLineComment.lastIndex = lastIndex;
if (match = SingleLineComment.exec(input)) {
lastIndex = SingleLineComment.lastIndex;
postfixIncDec = false;
yield ({
type: "SingleLineComment",
value: match[0]
});
continue;
}
firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
lastIndex += firstCodePoint.length;
lastSignificantToken = firstCodePoint;
postfixIncDec = false;
yield ({
type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
value: firstCodePoint
});
}
return void 0;
};
return jsTokens_1;
}
var jsTokensExports = /*@__PURE__*/ requireJsTokens();
var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokensExports);
// src/index.ts
var reservedWords = {
keyword: [
"break",
"case",
"catch",
"continue",
"debugger",
"default",
"do",
"else",
"finally",
"for",
"function",
"if",
"return",
"switch",
"throw",
"try",
"var",
"const",
"while",
"with",
"new",
"this",
"super",
"class",
"extends",
"export",
"import",
"null",
"true",
"false",
"in",
"instanceof",
"typeof",
"void",
"delete"
],
strict: [
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
"yield"
]
}, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
function isReservedWord(word) {
return word === "await" || word === "enum";
}
function isStrictReservedWord(word) {
return isReservedWord(word) || reservedWordsStrictSet.has(word);
}
function isKeyword(word) {
return keywords.has(word);
}
var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) {
if (token.type === "IdentifierName") {
if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value))
return "Keyword";
if (token.value[0] && token.value[0] !== token.value[0].toLowerCase())
return "IdentifierCapitalized";
}
return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type;
};
function getCallableType(token) {
if (token.type === "IdentifierName")
return "IdentifierCallable";
if (token.type === "PrivateIdentifier")
return "PrivateIdentifierCallable";
throw new Error("Not a callable token");
}
var colorize = (defs, type, value) => {
let colorize2 = defs[type];
return colorize2 ? colorize2(value) : value;
}, highlightTokens = (defs, text, jsx) => {
let highlighted = "", lastPotentialCallable = null, stackedHighlight = "";
for (let token of jsTokens(text, { jsx })) {
let type = getTokenType(token);
if (type === "IdentifierName" || type === "PrivateIdentifier") {
lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token;
continue;
}
if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) {
stackedHighlight += colorize(defs, type, token.value);
continue;
}
if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) {
let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable);
highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null;
}
highlighted += colorize(defs, type, token.value);
}
return highlighted;
};
function highlight$1(code, options = { jsx: false, colors: {} }) {
return code && highlightTokens(options.colors || {}, code, options.jsx);
}
function getDefs(c) {
const Invalid = (text) => c.white(c.bgRed(c.bold(text)));
return {
Keyword: c.magenta,
IdentifierCapitalized: c.yellow,
Punctuator: c.yellow,
StringLiteral: c.green,
NoSubstitutionTemplate: c.green,
MultiLineComment: c.gray,
SingleLineComment: c.gray,
RegularExpressionLiteral: c.cyan,
NumericLiteral: c.blue,
TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)),
TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)),
TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)),
IdentifierCallable: c.blue,
PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`,
Invalid,
JSXString: c.green,
JSXIdentifier: c.yellow,
JSXInvalid: Invalid,
JSXPunctuator: c.yellow
};
}
function highlight(code, options = { jsx: false }) {
return highlight$1(code, {
jsx: options.jsx,
colors: getDefs(options.colors || c)
});
}
export { highlight };
+1 -2
View File
@@ -5,13 +5,12 @@ const packageCache = new Map();
function findNearestPackageData(basedir) {
const originalBasedir = basedir;
while (basedir) {
var _tryStatSync;
const cached = getCachedData(packageCache, basedir, originalBasedir);
if (cached) {
return cached;
}
const pkgPath = join(basedir, "package.json");
if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) {
if (tryStatSync(pkgPath)?.isFile()) {
const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
if (packageCache) {
setCacheData(packageCache, pkgData, basedir, originalBasedir);
+6 -6
View File
@@ -22,16 +22,16 @@ function serializeValue(val, seen = new WeakMap()) {
const jsonValue = val.toJSON();
if (jsonValue && jsonValue !== val && typeof jsonValue === "object") {
if (typeof val.message === "string") {
safe(() => jsonValue.message ?? (jsonValue.message = normalizeErrorMessage(val.message)));
safe(() => jsonValue.message ??= normalizeErrorMessage(val.message));
}
if (typeof val.stack === "string") {
safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack));
safe(() => jsonValue.stack ??= val.stack);
}
if (typeof val.name === "string") {
safe(() => jsonValue.name ?? (jsonValue.name = val.name));
safe(() => jsonValue.name ??= val.name);
}
if (val.cause != null) {
safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen)));
safe(() => jsonValue.cause ??= serializeValue(val.cause, seen));
}
}
return serializeValue(jsonValue, seen);
@@ -101,7 +101,7 @@ function serializeValue(val, seen = new WeakMap()) {
obj = Object.getPrototypeOf(obj);
}
if (val instanceof Error) {
safe(() => val.message = normalizeErrorMessage(val.message));
safe(() => clone.message = normalizeErrorMessage(val.message));
}
return clone;
}
@@ -112,7 +112,7 @@ function safe(fn) {
} catch {}
}
function normalizeErrorMessage(message) {
return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
return message.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/getByTestId('__vitest_\d+__')/g, "page");
}
export { serializeValue };
+15 -5
View File
@@ -233,8 +233,11 @@ const stackIgnorePatterns = [
/node:\w+/,
/__vitest_test__/,
/__vitest_browser__/,
"/@id/__x00__vitest/browser",
/\/deps\/vitest_/
];
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (!urlLike.includes(":")) {
@@ -259,6 +262,9 @@ function extractLocation(urlLike) {
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows ? 5 : 4);
}
if (url.includes("vitest=")) {
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
}
return [
url,
parts[2] || undefined,
@@ -352,7 +358,7 @@ function parseSingleV8Stack(raw) {
// normalize Windows path (\ -> /)
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
if (method) {
method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
}
return {
method,
@@ -372,13 +378,17 @@ function createStackString(stacks) {
}
function parseStacktrace(stack, options = {}) {
const { ignoreStackEntries = stackIgnorePatterns } = options;
const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
// remove vi.defineHelper's internal stacks
const helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__"));
if (helperIndex >= 0) {
stacks = stacks.slice(helperIndex + 1);
}
return stacks.map((stack) => {
var _options$getSourceMap;
if (options.getUrlId) {
stack.file = options.getUrlId(stack.file);
}
const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file);
const map = options.getSourceMap?.(stack.file);
if (!map || typeof map !== "object" || !map.version) {
return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
}
@@ -457,7 +467,7 @@ class DecodedMap {
this._encoded = mappings || "";
this._decodedMemo = memoizedState();
this.url = from;
this.resolvedSources = (sources || []).map((s) => resolve(s || "", from));
this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || ""));
}
}
function memoizedState() {
+6
View File
@@ -0,0 +1,6 @@
interface ExtractedSourceMap {
map: any;
}
declare function extractSourcemapFromFile(code: string, filePath: string): ExtractedSourceMap | undefined;
export { extractSourcemapFromFile };
+23
View File
@@ -0,0 +1,23 @@
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import convertSourceMap from 'convert-source-map';
// based on vite
// https://github.com/vitejs/vite/blob/84079a84ad94de4c1ef4f1bdb2ab448ff2c01196/packages/vite/src/node/server/sourcemap.ts#L149
function extractSourcemapFromFile(code, filePath) {
const map = (convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
return map ? { map } : undefined;
}
function createConvertSourceMapReadMap(originalFileName) {
return (filename) => {
// convertSourceMap can detect invalid filename from comments.
// fallback to empty source map to avoid errors.
const targetPath = path.resolve(path.dirname(originalFileName), filename);
if (existsSync(targetPath)) {
return readFileSync(targetPath, "utf-8");
}
return "{}";
};
}
export { extractSourcemapFromFile };
+23
View File
@@ -0,0 +1,23 @@
Copyright 2013 Thorsten Lorenz.
All rights reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
+206
View File
@@ -0,0 +1,206 @@
# convert-source-map [![Build Status][ci-image]][ci-url]
Converts a source-map from/to different formats and allows adding/changing properties.
```js
var convert = require('convert-source-map');
var json = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', [ 'SRC/FOO.JS' ])
.toJSON();
console.log(json);
console.log(modified);
```
```json
{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
{"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
```
## Upgrading
Prior to v2.0.0, the `fromMapFileComment` and `fromMapFileSource` functions took a String directory path and used that to resolve & read the source map file from the filesystem. However, this made the library limited to nodejs environments and broke on sources with querystrings.
In v2.0.0, you now need to pass a function that does the file reading. It will receive the source filename as a String that you can resolve to a filesystem path, URL, or anything else.
If you are using `convert-source-map` in nodejs and want the previous behavior, you'll use a function like such:
```diff
+ var fs = require('fs'); // Import the fs module to read a file
+ var path = require('path'); // Import the path module to resolve a path against your directory
- var conv = convert.fromMapFileSource(css, '../my-dir');
+ var conv = convert.fromMapFileSource(css, function (filename) {
+ return fs.readFileSync(path.resolve('../my-dir', filename), 'utf-8');
+ });
```
## API
### fromObject(obj)
Returns source map converter from given object.
### fromJSON(json)
Returns source map converter from given json string.
### fromURI(uri)
Returns source map converter from given uri encoded json string.
### fromBase64(base64)
Returns source map converter from given base64 encoded json string.
### fromComment(comment)
Returns source map converter from given base64 or uri encoded json string prefixed with `//# sourceMappingURL=...`.
### fromMapFileComment(comment, readMap)
Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`.
`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously).
If `readMap` doesn't return a `Promise`, `fromMapFileComment` will return a source map converter synchronously.
If `readMap` returns a `Promise`, `fromMapFileComment` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error.
#### Examples
**Synchronous read in Node.js:**
```js
var convert = require('convert-source-map');
var fs = require('fs');
function readMap(filename) {
return fs.readFileSync(filename, 'utf8');
}
var json = convert
.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
.toJSON();
console.log(json);
```
**Asynchronous read in Node.js:**
```js
var convert = require('convert-source-map');
var { promises: fs } = require('fs'); // Notice the `promises` import
function readMap(filename) {
return fs.readFile(filename, 'utf8');
}
var converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
var json = converter.toJSON();
console.log(json);
```
**Asynchronous read in the browser:**
```js
var convert = require('convert-source-map');
async function readMap(url) {
const res = await fetch(url);
return res.text();
}
const converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
var json = converter.toJSON();
console.log(json);
```
### fromSource(source)
Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found.
### fromMapFileSource(source, readMap)
Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found.
`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously).
If `readMap` doesn't return a `Promise`, `fromMapFileSource` will return a source map converter synchronously.
If `readMap` returns a `Promise`, `fromMapFileSource` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error.
### toObject()
Returns a copy of the underlying source map.
### toJSON([space])
Converts source map to json string. If `space` is given (optional), this will be passed to
[JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the
JSON string is generated.
### toURI()
Converts source map to uri encoded json string.
### toBase64()
Converts source map to base64 encoded json string.
### toComment([options])
Converts source map to an inline comment that can be appended to the source-file.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would
normally see in a JS source file.
When `options.encoding == 'uri'`, the data will be uri encoded, otherwise they will be base64 encoded.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
### addProperty(key, value)
Adds given property to the source map. Throws an error if property already exists.
### setProperty(key, value)
Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated.
### getProperty(key)
Gets given property of the source map.
### removeComments(src)
Returns `src` with all source map comments removed
### removeMapFileComments(src)
Returns `src` with all source map comments pointing to map files removed.
### commentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments.
Breaks down a source map comment into groups: Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
### mapFileCommentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files.
### generateMapFileComment(file, [options])
Returns a comment that links to an external source map via `file`.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
[ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci
[ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square
+233
View File
@@ -0,0 +1,233 @@
'use strict';
Object.defineProperty(exports, 'commentRegex', {
get: function getCommentRegex () {
// Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
}
});
Object.defineProperty(exports, 'mapFileCommentRegex', {
get: function getMapFileCommentRegex () {
// Matches sourceMappingURL in either // or /* comment styles.
return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, 'base64').toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === 'number') {
throw new TypeError('The value to decode must not be of type number.');
}
return new Buffer(base64, 'base64').toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(',').pop();
}
function readFromFileMap(sm, read) {
var r = exports.mapFileCommentRegex.exec(sm);
// for some odd reason //# .. captures in 1 and /* .. */ in 2
var filename = r[1] || r[2];
try {
var sm = read(filename);
if (sm != null && typeof sm.catch === 'function') {
return sm.catch(throwError);
} else {
return sm;
}
} catch (e) {
throwError(e);
}
function throwError(e) {
throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
}
}
function Converter (sm, opts) {
opts = opts || {};
if (opts.hasComment) {
sm = stripComment(sm);
}
if (opts.encoding === 'base64') {
sm = decodeBase64(sm);
} else if (opts.encoding === 'uri') {
sm = decodeURIComponent(sm);
}
if (opts.isJSON || opts.encoding) {
sm = JSON.parse(sm);
}
this.sourcemap = sm;
}
Converter.prototype.toJSON = function (space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json = this.toJSON();
return Buffer.from(json, 'utf8').toString('base64');
}
function encodeBase64WithNewBuffer() {
var json = this.toJSON();
if (typeof json === 'number') {
throw new TypeError('The json to encode must not be of type number.');
}
return new Buffer(json, 'utf8').toString('base64');
}
function encodeBase64WithBtoa() {
var json = this.toJSON();
return btoa(unescape(encodeURIComponent(json)));
}
Converter.prototype.toURI = function () {
var json = this.toJSON();
return encodeURIComponent(json);
};
Converter.prototype.toComment = function (options) {
var encoding, content, data;
if (options != null && options.encoding === 'uri') {
encoding = '';
content = this.toURI();
} else {
encoding = ';base64';
content = this.toBase64();
}
data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};
// returns copy instead of original
Converter.prototype.toObject = function () {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function (key, value) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value);
};
Converter.prototype.setProperty = function (key, value) {
this.sourcemap[key] = value;
return this;
};
Converter.prototype.getProperty = function (key) {
return this.sourcemap[key];
};
exports.fromObject = function (obj) {
return new Converter(obj);
};
exports.fromJSON = function (json) {
return new Converter(json, { isJSON: true });
};
exports.fromURI = function (uri) {
return new Converter(uri, { encoding: 'uri' });
};
exports.fromBase64 = function (base64) {
return new Converter(base64, { encoding: 'base64' });
};
exports.fromComment = function (comment) {
var m, encoding;
comment = comment
.replace(/^\/\*/g, '//')
.replace(/\*\/$/g, '');
m = exports.commentRegex.exec(comment);
encoding = m && m[4] || 'uri';
return new Converter(comment, { encoding: encoding, hasComment: true });
};
function makeConverter(sm) {
return new Converter(sm, { isJSON: true });
}
exports.fromMapFileComment = function (comment, read) {
if (typeof read === 'string') {
throw new Error(
'String directory paths are no longer supported with `fromMapFileComment`\n' +
'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
)
}
var sm = readFromFileMap(comment, read);
if (sm != null && typeof sm.then === 'function') {
return sm.then(makeConverter);
} else {
return makeConverter(sm);
}
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromSource = function (content) {
var m = content.match(exports.commentRegex);
return m ? exports.fromComment(m.pop()) : null;
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromMapFileSource = function (content, read) {
if (typeof read === 'string') {
throw new Error(
'String directory paths are no longer supported with `fromMapFileSource`\n' +
'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
)
}
var m = content.match(exports.mapFileCommentRegex);
return m ? exports.fromMapFileComment(m.pop(), read) : null;
};
exports.removeComments = function (src) {
return src.replace(exports.commentRegex, '');
};
exports.removeMapFileComments = function (src) {
return src.replace(exports.mapFileCommentRegex, '');
};
exports.generateMapFileComment = function (file, options) {
var data = 'sourceMappingURL=' + file;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};
@@ -0,0 +1,38 @@
{
"name": "convert-source-map",
"version": "2.0.0",
"description": "Converts a source-map from/to different formats and allows adding/changing properties.",
"main": "index.js",
"scripts": {
"test": "tap test/*.js --color"
},
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/convert-source-map.git"
},
"homepage": "https://github.com/thlorenz/convert-source-map",
"devDependencies": {
"inline-source-map": "~0.6.2",
"tap": "~9.0.0"
},
"keywords": [
"convert",
"sourcemap",
"source",
"map",
"browser",
"debug"
],
"author": {
"name": "Thorsten Lorenz",
"email": "thlorenz@gmx.de",
"url": "http://thlorenz.com"
},
"license": "MIT",
"engine": {
"node": ">=4"
},
"files": [
"index.js"
]
}
+14 -10
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/utils",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Shared Vitest utility functions",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -52,14 +52,14 @@
"types": "./dist/display.d.ts",
"default": "./dist/display.js"
},
"./highlight": {
"types": "./dist/highlight.d.ts",
"default": "./dist/highlight.js"
},
"./source-map": {
"types": "./dist/source-map.d.ts",
"default": "./dist/source-map.js"
},
"./source-map/node": {
"types": "./dist/source-map/node.d.ts",
"default": "./dist/source-map/node.js"
},
"./serialize": {
"types": "./dist/serialize.d.ts",
"default": "./dist/serialize.js"
@@ -73,6 +73,9 @@
"*": {
"source-map": [
"dist/source-map.d.ts"
],
"source-map/node": [
"dist/source-map/node.d.ts"
]
}
},
@@ -81,15 +84,16 @@
"dist"
],
"dependencies": {
"tinyrainbow": "^3.0.3",
"@vitest/pretty-format": "4.0.18"
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0",
"@vitest/pretty-format": "4.1.9"
},
"devDependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@types/convert-source-map": "^2.0.3",
"@types/estree": "^1.0.8",
"diff-sequences": "^29.6.3",
"loupe": "^3.2.1",
"tinyhighlight": "^0.3.2"
"loupe": "^3.2.1"
},
"scripts": {
"build": "premove dist && rollup -c",