first commit

This commit is contained in:
2025-12-08 10:52:05 -05:00
commit 50737919fd
935 changed files with 782679 additions and 0 deletions

21
node_modules/@vitest/spy/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
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.

3
node_modules/@vitest/spy/README.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# @vitest/spy
Lightweight Jest compatible spy implementation.

384
node_modules/@vitest/spy/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,384 @@
interface MockResultReturn<T> {
type: "return";
/**
* The value that was returned from the function. If function returned a Promise, then this will be a resolved value.
*/
value: T;
}
interface MockResultIncomplete {
type: "incomplete";
value: undefined;
}
interface MockResultThrow {
type: "throw";
/**
* An error that was thrown during function execution.
*/
value: any;
}
interface MockSettledResultIncomplete {
type: "incomplete";
value: undefined;
}
interface MockSettledResultFulfilled<T> {
type: "fulfilled";
value: T;
}
interface MockSettledResultRejected {
type: "rejected";
value: any;
}
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 MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>;
interface MockContext<T extends Procedure | Constructable = Procedure> {
/**
* This is an array containing all arguments for each call. One item of the array is the arguments of that call.
*
* @see https://vitest.dev/api/mock#mock-calls
* @example
* const fn = vi.fn()
*
* fn('arg1', 'arg2')
* fn('arg3')
*
* fn.mock.calls === [
* ['arg1', 'arg2'], // first call
* ['arg3'], // second call
* ]
*/
calls: MockParameters<T>[];
/**
* This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value.
* @see https://vitest.dev/api/mock#mock-instances
*/
instances: MockProcedureContext<T>[];
/**
* An array of `this` values that were used during each call to the mock function.
* @see https://vitest.dev/api/mock#mock-contexts
*/
contexts: MockProcedureContext<T>[];
/**
* The order of mock's execution. This returns an array of numbers which are shared between all defined mocks.
*
* @see https://vitest.dev/api/mock#mock-invocationcallorder
* @example
* const fn1 = vi.fn()
* const fn2 = vi.fn()
*
* fn1()
* fn2()
* fn1()
*
* fn1.mock.invocationCallOrder === [1, 3]
* fn2.mock.invocationCallOrder === [2]
*/
invocationCallOrder: number[];
/**
* This is an array containing all values that were `returned` from the function.
*
* The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected.
*
* @see https://vitest.dev/api/mock#mock-results
* @example
* const fn = vi.fn()
* .mockReturnValueOnce('result')
* .mockImplementationOnce(() => { throw new Error('thrown error') })
*
* const result = fn()
*
* try {
* fn()
* }
* catch {}
*
* fn.mock.results === [
* {
* type: 'return',
* value: 'result',
* },
* {
* type: 'throw',
* value: Error,
* },
* ]
*/
results: MockResult<MockReturnType<T>>[];
/**
* An array containing all values that were `resolved` or `rejected` from the function.
*
* This array will be empty if the function was never resolved or rejected.
*
* @see https://vitest.dev/api/mock#mock-settledresults
* @example
* const fn = vi.fn().mockResolvedValueOnce('result')
*
* const result = fn()
*
* fn.mock.settledResults === [
* {
* type: 'incomplete',
* value: undefined,
* }
* ]
* fn.mock.results === [
* {
* type: 'return',
* value: Promise<'result'>,
* },
* ]
*
* await result
*
* fn.mock.settledResults === [
* {
* type: 'fulfilled',
* value: 'result',
* },
* ]
*/
settledResults: MockSettledResult<Awaited<MockReturnType<T>>>[];
/**
* This contains the arguments of the last call. If spy wasn't called, will return `undefined`.
* @see https://vitest.dev/api/mock#mock-lastcall
*/
lastCall: MockParameters<T> | undefined;
}
type Procedure = (...args: any[]) => any;
type NormalizedProcedure<T extends Procedure | Constructable> = T extends Constructable ? ({
new (...args: ConstructorParameters<T>): InstanceType<T>;
}) | ({
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
}) : T extends Procedure ? (...args: Parameters<T>) => ReturnType<T> : never;
type Methods<T> = keyof { [K in keyof T as T[K] extends Procedure ? K : never] : T[K] };
type Properties<T> = { [K in keyof T] : T[K] extends Procedure ? never : K }[keyof T] & (string | symbol);
type Classes<T> = { [K in keyof T] : T[K] extends new (...args: any[]) => any ? K : never }[keyof T] & (string | symbol);
interface MockInstance<T extends Procedure | Constructable = Procedure> extends Disposable {
/**
* Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.
* @see https://vitest.dev/api/mock#getmockname
*/
getMockName(): string;
/**
* Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
* @see https://vitest.dev/api/mock#mockname
*/
mockName(name: string): this;
/**
* Current context of the mock. It stores information about all invocation calls, instances, and results.
*/
mock: MockContext<T>;
/**
* 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.
* @see https://vitest.dev/api/mock#mockclear
*/
mockClear(): this;
/**
* Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations.
*
* 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.
* @see https://vitest.dev/api/mock#mockreset
*/
mockReset(): this;
/**
* Does what `mockReset` does and restores original descriptors of spied-on objects.
* @see https://vitest.dev/api/mock#mockrestore
*/
mockRestore(): void;
/**
* Returns current permanent mock implementation if there is one.
*
* If mock was created with `vi.fn`, it will consider passed down method as a mock implementation.
*
* If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided.
*/
getMockImplementation(): NormalizedProcedure<T> | undefined;
/**
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
* @see https://vitest.dev/api/mock#mockimplementation
* @example
* const increment = vi.fn().mockImplementation(count => count + 1);
* expect(increment(3)).toBe(4);
*/
mockImplementation(fn: NormalizedProcedure<T>): this;
/**
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.
*
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
* @see https://vitest.dev/api/mock#mockimplementationonce
* @example
* const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1);
* expect(fn(3)).toBe(4);
* expect(fn(3)).toBe(3);
*/
mockImplementationOnce(fn: NormalizedProcedure<T>): this;
/**
* Overrides the original mock implementation temporarily while the callback is being executed.
*
* Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce).
* @see https://vitest.dev/api/mock#withimplementation
* @example
* const myMockFn = vi.fn(() => 'original')
*
* myMockFn.withImplementation(() => 'temp', () => {
* myMockFn() // 'temp'
* })
*
* myMockFn() // 'original'
*/
withImplementation(fn: NormalizedProcedure<T>, cb: () => Promise<unknown>): Promise<this>;
withImplementation(fn: NormalizedProcedure<T>, cb: () => unknown): this;
/**
* Use this if you need to return the `this` context from the method without invoking the actual implementation.
* @see https://vitest.dev/api/mock#mockreturnthis
*/
mockReturnThis(): this;
/**
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
* @see https://vitest.dev/api/mock#mockreturnvalue
* @example
* const mock = vi.fn()
* mock.mockReturnValue(42)
* mock() // 42
* mock.mockReturnValue(43)
* mock() // 43
*/
mockReturnValue(value: MockReturnType<T>): this;
/**
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
*
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
* @example
* const myMockFn = vi
* .fn()
* .mockReturnValue('default')
* .mockReturnValueOnce('first call')
* .mockReturnValueOnce('second call')
*
* // 'first call', 'second call', 'default'
* console.log(myMockFn(), myMockFn(), myMockFn())
*/
mockReturnValueOnce(value: MockReturnType<T>): 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)
* asyncMock() // Promise<42>
*/
mockResolvedValue(value: Awaited<MockReturnType<T>>): this;
/**
* Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.
* @example
* const myMockFn = vi
* .fn()
* .mockResolvedValue('default')
* .mockResolvedValueOnce('first call')
* .mockResolvedValueOnce('second call')
*
* // Promise<'first call'>, Promise<'second call'>, Promise<'default'>
* console.log(myMockFn(), myMockFn(), myMockFn())
*/
mockResolvedValueOnce(value: Awaited<MockReturnType<T>>): this;
/**
* Accepts an error that will be rejected when async function is called.
* @example
* const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
* await asyncMock() // throws Error<'Async error'>
*/
mockRejectedValue(error: unknown): this;
/**
* Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
* @example
* const asyncMock = vi
* .fn()
* .mockResolvedValueOnce('first call')
* .mockRejectedValueOnce(new Error('Async error'))
*
* await asyncMock() // first call
* await asyncMock() // throws Error<'Async error'>
*/
mockRejectedValueOnce(error: unknown): this;
}
type Mock<T extends Procedure | Constructable = Procedure> = MockInstance<T> & (T extends Constructable ? (T extends Procedure ? {
new (...args: ConstructorParameters<T>): InstanceType<T>;
(...args: Parameters<T>): ReturnType<T>;
} : {
new (...args: ConstructorParameters<T>): InstanceType<T>;
}) : {
new (...args: MockParameters<T>): MockReturnType<T>;
(...args: MockParameters<T>): MockReturnType<T>;
}) & { [P in keyof T] : T[P] };
type PartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<Partial<Awaited<T>>> : Partial<T>;
type PartialResultFunction<T> = T extends Constructable ? ({
new (...args: ConstructorParameters<T>): InstanceType<T>;
}) | ({
(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 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 MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>;
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartialMock<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;
type MaybePartiallyMockedDeep<T> = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
type MaybeMocked<T> = T extends Procedure | Constructable ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
type MaybePartiallyMocked<T> = T extends Procedure | Constructable ? PartiallyMockedFunction<T> : T extends object ? MockedObject<T> : T;
interface Constructable {
new (...args: any[]): any;
}
type MockedClass<T extends Constructable> = MockInstance<T> & {
prototype: T extends {
prototype: any;
} ? Mocked<T["prototype"]> : never;
} & T;
type Mocked<T> = { [P in keyof T] : T[P] extends Procedure ? MockInstance<T[P]> : T[P] extends Constructable ? MockedClass<T[P]> : T[P] } & T;
interface MockConfig {
mockImplementation: Procedure | Constructable | undefined;
mockOriginal: Procedure | Constructable | undefined;
mockName: string;
onceMockImplementations: Array<Procedure | Constructable>;
}
interface MockInstanceOption {
originalImplementation?: Procedure | Constructable;
mockImplementation?: Procedure | Constructable;
resetToMockImplementation?: boolean;
restore?: () => void;
prototypeMembers?: (string | symbol)[];
keepMembersImplementation?: boolean;
prototypeState?: MockContext;
prototypeConfig?: MockConfig;
resetToMockName?: boolean;
name?: string | symbol;
}
declare function isMockFunction(fn: any): fn is Mock;
declare function createMockInstance(options?: MockInstanceOption): Mock<Procedure | Constructable>;
declare function fn<T extends Procedure | Constructable = Procedure>(originalImplementation?: T): Mock<T>;
declare function spyOn<
T extends object,
S extends Properties<Required<T>>
>(object: T, key: S, accessor: "get"): Mock<() => T[S]>;
declare function spyOn<
T extends object,
G extends Properties<Required<T>>
>(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>;
declare function spyOn<
T extends object,
M extends Classes<Required<T>> | Methods<Required<T>>
>(object: T, key: M): Required<T>[M] extends Constructable | Procedure ? Mock<Required<T>[M]> : never;
declare function restoreAllMocks(): void;
declare function clearAllMocks(): void;
declare function resetAllMocks(): void;
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };
export type { Constructable, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep, Mock, MockContext, MockInstance, MockInstanceOption, MockParameters, MockProcedureContext, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockReturnType, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, PartialMock, PartiallyMockedFunction, PartiallyMockedFunctionDeep, Procedure };

433
node_modules/@vitest/spy/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,433 @@
function isMockFunction(fn) {
return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true;
}
const MOCK_RESTORE = new Set();
// Jest keeps the state in a separate WeakMap which is good for memory,
// but it makes the state slower to access and return different values
// if you stored it before calling `mockClear` where it will be recreated
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);
}
const config = getDefaultConfig(originalImplementation);
const state = getDefaultState();
const mock = createMock({
config,
state,
...options
});
const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0;
Object.defineProperty(mock, "length", {
writable: true,
enumerable: false,
value: mockLength,
configurable: true
});
// inherit the default name so it appears in snapshots and logs
// this is used by `vi.spyOn()` for better debugging.
// when `vi.fn()` is called, we just use the default string
if (resetToMockName) {
config.mockName = mock.name || "vi.fn()";
}
MOCK_CONFIGS.set(mock, config);
REGISTERED_MOCKS.add(mock);
mock._isMockFunction = true;
mock.getMockImplementation = () => {
// Jest only returns `config.mockImplementation` here,
// but we think it makes sense to return what the next function will be called
return config.onceMockImplementations[0] || config.mockImplementation;
};
Object.defineProperty(mock, "mock", {
configurable: false,
enumerable: true,
writable: false,
value: state
});
mock.mockImplementation = function mockImplementation(implementation) {
config.mockImplementation = implementation;
return mock;
};
mock.mockImplementationOnce = function mockImplementationOnce(implementation) {
config.onceMockImplementations.push(implementation);
return mock;
};
mock.withImplementation = function withImplementation(implementation, callback) {
const previousImplementation = config.mockImplementation;
const previousOnceImplementations = config.onceMockImplementations;
const reset = () => {
config.mockImplementation = previousImplementation;
config.onceMockImplementations = previousOnceImplementations;
};
config.mockImplementation = implementation;
config.onceMockImplementations = [];
const returnValue = callback();
if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") {
return returnValue.then(() => {
reset();
return mock;
});
} else {
reset();
}
return mock;
};
mock.mockReturnThis = function mockReturnThis() {
return mock.mockImplementation(function() {
return this;
});
};
mock.mockReturnValue = function mockReturnValue(value) {
return mock.mockImplementation(() => value);
};
mock.mockReturnValueOnce = function mockReturnValueOnce(value) {
return mock.mockImplementationOnce(() => value);
};
mock.mockResolvedValue = function mockResolvedValue(value) {
return mock.mockImplementation(() => Promise.resolve(value));
};
mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.resolve(value));
};
mock.mockRejectedValue = function mockRejectedValue(value) {
return mock.mockImplementation(() => Promise.reject(value));
};
mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.reject(value));
};
mock.mockClear = function mockClear() {
state.calls = [];
state.contexts = [];
state.instances = [];
state.invocationCallOrder = [];
state.results = [];
state.settledResults = [];
return mock;
};
mock.mockReset = function mockReset() {
mock.mockClear();
config.mockImplementation = resetToMockImplementation ? mockImplementation : undefined;
config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()";
config.onceMockImplementations = [];
return mock;
};
mock.mockRestore = function mockRestore() {
mock.mockReset();
return restore === null || restore === void 0 ? void 0 : restore();
};
mock.mockName = function mockName(name) {
if (typeof name === "string") {
config.mockName = name;
}
return mock;
};
mock.getMockName = function getMockName() {
return config.mockName || "vi.fn()";
};
if (Symbol.dispose) {
mock[Symbol.dispose] = () => mock.mockRestore();
}
if (mockImplementation) {
mock.mockImplementation(mockImplementation);
}
return mock;
}
function fn(originalImplementation) {
// if the function is already a mock, just return the same function,
// simillarly to how vi.spyOn() works
if (originalImplementation != null && isMockFunction(originalImplementation)) {
return originalImplementation;
}
return createMockInstance({
mockImplementation: originalImplementation,
resetToMockImplementation: true
});
}
function spyOn(object, key, accessor) {
assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined.");
assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value.");
const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || [];
assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`);
let accessType = accessor || "value";
let ssr = false;
// vite ssr support - actual function is stored inside a getter
if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) {
accessType = "get";
ssr = true;
}
let original;
if (originalDescriptor) {
original = originalDescriptor[accessType];
} else if (accessType !== "value") {
original = () => object[key];
} else {
original = object[key];
}
const originalImplementation = ssr && original ? original() : original;
const originalType = typeof originalImplementation;
assert(
// allow only functions
originalType === "function" || accessType !== "value" && original == null,
`vi.spyOn() can only spy on a function. Received ${originalType}.`
);
if (isMockFunction(originalImplementation)) {
return originalImplementation;
}
const reassign = (cb) => {
const { value, ...desc } = originalDescriptor || {
configurable: true,
writable: true
};
if (accessType !== "value") {
delete desc.writable;
}
desc[accessType] = cb;
Object.defineProperty(object, key, desc);
};
const restore = () => {
// if method is defined on the prototype, we can just remove it from
// the current object instead of redefining a copy of it
if (originalDescriptorObject !== object) {
Reflect.deleteProperty(object, key);
} else if (originalDescriptor && !original) {
Object.defineProperty(object, key, originalDescriptor);
} else {
reassign(original);
}
};
const mock = createMockInstance({
restore,
originalImplementation,
resetToMockName: true
});
try {
reassign(ssr ? () => mock : mock);
} catch (error) {
if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) {
throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error });
}
throw error;
}
return mock;
}
function getDescriptor(obj, method) {
const objDescriptor = Object.getOwnPropertyDescriptor(obj, method);
if (objDescriptor) {
return [obj, objDescriptor];
}
let currentProto = Object.getPrototypeOf(obj);
while (currentProto !== null) {
const descriptor = Object.getOwnPropertyDescriptor(currentProto, method);
if (descriptor) {
return [currentProto, descriptor];
}
currentProto = Object.getPrototypeOf(currentProto);
}
}
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
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 namedObject = { [name]: (function(...args) {
registerCalls(args, state, prototypeState);
registerInvocationOrder(invocationCallCounter++, state, prototypeState);
const result = {
type: "incomplete",
value: undefined
};
const settledResult = {
type: "incomplete",
value: undefined
};
registerResult(result, state, prototypeState);
registerSettledResult(settledResult, state, prototypeState);
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() {};
let returnValue;
let thrownValue;
let didThrow = false;
try {
if (new.target) {
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`
// 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
// eslint-disable-next-line ts/no-use-before-define
if (prototypeMock !== mock.prototype[prop]) {
continue;
}
const isMock = isMockFunction(prototypeMock);
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,
prototypeState,
prototypeConfig,
keepMembersImplementation
});
}
} else {
returnValue = implementation.apply(this, args);
}
} catch (error) {
thrownValue = error;
didThrow = true;
if (error instanceof TypeError && error.message.includes("is not a constructor")) {
console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`);
}
throw error;
} finally {
if (didThrow) {
result.type = "throw";
result.value = thrownValue;
settledResult.type = "rejected";
settledResult.value = thrownValue;
} else {
result.type = "return";
result.value = returnValue;
if (new.target) {
state.contexts[contextIndex - 1] = returnValue;
state.instances[instanceIndex - 1] = returnValue;
if (contextPrototypeIndex != null && prototypeState) {
prototypeState.contexts[contextPrototypeIndex - 1] = returnValue;
}
if (instancePrototypeIndex != null && prototypeState) {
prototypeState.instances[instancePrototypeIndex - 1] = returnValue;
}
}
if (returnValue instanceof Promise) {
returnValue.then((settledValue) => {
settledResult.type = "fulfilled";
settledResult.value = settledValue;
}, (rejectedValue) => {
settledResult.type = "rejected";
settledResult.value = rejectedValue;
});
} else {
settledResult.type = "fulfilled";
settledResult.value = returnValue;
}
}
}
return returnValue;
}) };
const mock = namedObject[name];
const copyPropertiesFrom = original || pseudoOriginal;
if (copyPropertiesFrom) {
copyOriginalStaticProperties(mock, copyPropertiesFrom);
}
return mock;
}
function registerCalls(args, state, prototypeState) {
state.calls.push(args);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args);
}
function registerInvocationOrder(order, state, prototypeState) {
state.invocationCallOrder.push(order);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order);
}
function registerResult(result, state, prototypeState) {
state.results.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result);
}
function registerSettledResult(result, state, prototypeState) {
state.settledResults.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : 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);
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);
return [contextIndex, contextPrototypeIndex];
}
function copyOriginalStaticProperties(mock, original) {
const { properties, descriptors } = getAllProperties(original);
for (const key of properties) {
const descriptor = descriptors[key];
const mockDescriptor = getDescriptor(mock, key);
if (mockDescriptor) {
continue;
}
Object.defineProperty(mock, key, descriptor);
}
}
const ignoreProperties = new Set([
"length",
"name",
"prototype",
Symbol.for("nodejs.util.promisify.custom")
]);
function getAllProperties(original) {
const properties = new Set();
const descriptors = {};
while (original && original !== Object.prototype && original !== Function.prototype) {
const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)];
for (const prop of ownProperties) {
if (descriptors[prop] || ignoreProperties.has(prop)) {
continue;
}
properties.add(prop);
descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop);
}
original = Object.getPrototypeOf(original);
}
return {
properties,
descriptors
};
}
function getDefaultConfig(original) {
return {
mockImplementation: undefined,
mockOriginal: original,
mockName: "vi.fn()",
onceMockImplementations: []
};
}
function getDefaultState() {
const state = {
calls: [],
contexts: [],
instances: [],
invocationCallOrder: [],
settledResults: [],
results: [],
get lastCall() {
return state.calls.at(-1);
}
};
return state;
}
function restoreAllMocks() {
for (const restore of MOCK_RESTORE) {
restore();
}
MOCK_RESTORE.clear();
}
function clearAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockClear());
}
function resetAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockReset());
}
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };

35
node_modules/@vitest/spy/package.json generated vendored Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "@vitest/spy",
"type": "module",
"version": "4.0.15",
"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",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/spy"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}