mirror of
https://github.com/soconnor0919/beenpad.git
synced 2026-02-05 00:06:40 -05:00
first commit
This commit is contained in:
21
node_modules/@vitest/mocker/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/mocker/LICENSE
generated
vendored
Normal 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.
|
||||
5
node_modules/@vitest/mocker/README.md
generated
vendored
Normal file
5
node_modules/@vitest/mocker/README.md
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# @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)
|
||||
2
node_modules/@vitest/mocker/dist/auto-register.d.ts
generated
vendored
Normal file
2
node_modules/@vitest/mocker/dist/auto-register.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
export { };
|
||||
9
node_modules/@vitest/mocker/dist/auto-register.js
generated
vendored
Normal file
9
node_modules/@vitest/mocker/dist/auto-register.js
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
|
||||
import { registerModuleMocker } from './register.js';
|
||||
import './chunk-mocker.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
import '@vitest/spy';
|
||||
|
||||
registerModuleMocker(() => new ModuleMockerServerInterceptor());
|
||||
12
node_modules/@vitest/mocker/dist/automock.d.ts
generated
vendored
Normal file
12
node_modules/@vitest/mocker/dist/automock.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
interface AutomockOptions {
|
||||
/**
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
}
|
||||
declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString;
|
||||
|
||||
export { automockModule };
|
||||
export type { AutomockOptions };
|
||||
3
node_modules/@vitest/mocker/dist/automock.js
generated
vendored
Normal file
3
node_modules/@vitest/mocker/dist/automock.js
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import 'magic-string';
|
||||
export { a as automockModule } from './chunk-automock.js';
|
||||
import 'estree-walker';
|
||||
53
node_modules/@vitest/mocker/dist/browser.d.ts
generated
vendored
Normal file
53
node_modules/@vitest/mocker/dist/browser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
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 { StartOptions, SetupWorker } from 'msw/browser';
|
||||
import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js';
|
||||
import '@vitest/spy';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
|
||||
interface ModuleMockerMSWInterceptorOptions {
|
||||
/**
|
||||
* The identifier to access the globalThis object in the worker.
|
||||
* This will be injected into the script as is, so make sure it's a valid JS expression.
|
||||
* @example
|
||||
* ```js
|
||||
* // globalThisAccessor: '__my_variable__' produces:
|
||||
* globalThis[__my_variable__]
|
||||
* // globalThisAccessor: 'Symbol.for('secret:mocks')' produces:
|
||||
* globalThis[Symbol.for('secret:mocks')]
|
||||
* // globalThisAccessor: '"__vitest_mocker__"' (notice quotes) produces:
|
||||
* globalThis["__vitest_mocker__"]
|
||||
* ```
|
||||
* @default `"__vitest_mocker__"`
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
/**
|
||||
* Options passed down to `msw.setupWorker().start(options)`
|
||||
*/
|
||||
mswOptions?: StartOptions;
|
||||
/**
|
||||
* A pre-configured `msw.setupWorker` instance.
|
||||
*/
|
||||
mswWorker?: SetupWorker;
|
||||
}
|
||||
declare class ModuleMockerMSWInterceptor implements ModuleMockerInterceptor {
|
||||
private readonly options;
|
||||
protected readonly mocks: MockerRegistry;
|
||||
private startPromise;
|
||||
private worker;
|
||||
constructor(options?: ModuleMockerMSWInterceptorOptions);
|
||||
register(module: MockedModule): Promise<void>;
|
||||
delete(url: string): Promise<void>;
|
||||
invalidate(): Promise<void>;
|
||||
private resolveManualMock;
|
||||
protected init(): Promise<SetupWorker>;
|
||||
}
|
||||
|
||||
declare class ModuleMockerServerInterceptor implements ModuleMockerInterceptor {
|
||||
register(module: MockedModule): Promise<void>;
|
||||
delete(id: string): Promise<void>;
|
||||
invalidate(): Promise<void>;
|
||||
}
|
||||
|
||||
export { ModuleMockerInterceptor, ModuleMockerMSWInterceptor, ModuleMockerServerInterceptor };
|
||||
export type { ModuleMockerMSWInterceptorOptions };
|
||||
91
node_modules/@vitest/mocker/dist/browser.js
generated
vendored
Normal file
91
node_modules/@vitest/mocker/dist/browser.js
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
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 './index.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
class ModuleMockerMSWInterceptor {
|
||||
mocks = new MockerRegistry();
|
||||
startPromise;
|
||||
worker;
|
||||
constructor(options = {}) {
|
||||
this.options = options;
|
||||
if (!options.globalThisAccessor) {
|
||||
options.globalThisAccessor = "\"__vitest_mocker__\"";
|
||||
}
|
||||
}
|
||||
async register(module) {
|
||||
await this.init();
|
||||
this.mocks.add(module);
|
||||
}
|
||||
async delete(url) {
|
||||
await this.init();
|
||||
this.mocks.delete(url);
|
||||
}
|
||||
async invalidate() {
|
||||
this.mocks.clear();
|
||||
}
|
||||
async resolveManualMock(mock) {
|
||||
const exports$1 = Object.keys(await mock.resolve());
|
||||
const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor);
|
||||
return new Response(text, { headers: { "Content-Type": "application/javascript" } });
|
||||
}
|
||||
async init() {
|
||||
if (this.worker) {
|
||||
return this.worker;
|
||||
}
|
||||
if (this.startPromise) {
|
||||
return this.startPromise;
|
||||
}
|
||||
const worker = this.options.mswWorker;
|
||||
this.startPromise = Promise.all([worker ? { setupWorker(handler) {
|
||||
worker.use(handler);
|
||||
return worker;
|
||||
} } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => {
|
||||
const worker = setupWorker(http.get(/.+/, async ({ request }) => {
|
||||
const path = cleanQuery(request.url.slice(location.origin.length));
|
||||
if (!this.mocks.has(path)) {
|
||||
return passthrough();
|
||||
}
|
||||
const mock = this.mocks.get(path);
|
||||
switch (mock.type) {
|
||||
case "manual": return this.resolveManualMock(mock);
|
||||
case "automock":
|
||||
case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`));
|
||||
case "redirect": return Response.redirect(mock.redirect);
|
||||
default: throw new Error(`Unknown mock type: ${mock.type}`);
|
||||
}
|
||||
}));
|
||||
return worker.start(this.options.mswOptions).then(() => worker);
|
||||
}).finally(() => {
|
||||
this.worker = worker;
|
||||
this.startPromise = undefined;
|
||||
});
|
||||
return await this.startPromise;
|
||||
}
|
||||
}
|
||||
const trailingSeparatorRE = /[?&]$/;
|
||||
const timestampRE = /\bt=\d{13}&?\b/;
|
||||
const versionRE = /\bv=\w{8}&?\b/;
|
||||
function cleanQuery(url) {
|
||||
return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, "");
|
||||
}
|
||||
function passthrough() {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
statusText: "Passthrough",
|
||||
headers: { "x-msw-intention": "passthrough" }
|
||||
});
|
||||
}
|
||||
const replacePercentageRE = /%/g;
|
||||
function injectQuery(url, queryToInject) {
|
||||
// encode percents for consistent behavior with pathToFileURL
|
||||
// see #2614 for details
|
||||
const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href);
|
||||
const { search, hash } = resolvedUrl;
|
||||
const pathname = cleanUrl(url);
|
||||
return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
|
||||
}
|
||||
|
||||
export { ModuleMockerMSWInterceptor };
|
||||
345
node_modules/@vitest/mocker/dist/chunk-automock.js
generated
vendored
Normal file
345
node_modules/@vitest/mocker/dist/chunk-automock.js
generated
vendored
Normal file
@@ -0,0 +1,345 @@
|
||||
import MagicString from 'magic-string';
|
||||
import { walk } from 'estree-walker';
|
||||
|
||||
const isNodeInPatternWeakSet = new WeakSet();
|
||||
function setIsNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.add(node);
|
||||
}
|
||||
function isNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.has(node);
|
||||
}
|
||||
/**
|
||||
* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
|
||||
* Except this is using acorn AST
|
||||
*/
|
||||
function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) {
|
||||
const parentStack = [];
|
||||
const varKindStack = [];
|
||||
const scopeMap = new WeakMap();
|
||||
const identifiers = [];
|
||||
const setScope = (node, name) => {
|
||||
let scopeIds = scopeMap.get(node);
|
||||
if (scopeIds && scopeIds.has(name)) {
|
||||
return;
|
||||
}
|
||||
if (!scopeIds) {
|
||||
scopeIds = new Set();
|
||||
scopeMap.set(node, scopeIds);
|
||||
}
|
||||
scopeIds.add(name);
|
||||
};
|
||||
function isInScope(name, parents) {
|
||||
return parents.some((node) => {
|
||||
var _scopeMap$get;
|
||||
return node && ((_scopeMap$get = scopeMap.get(node)) === null || _scopeMap$get === void 0 ? void 0 : _scopeMap$get.has(name));
|
||||
});
|
||||
}
|
||||
function handlePattern(p, parentScope) {
|
||||
if (p.type === "Identifier") {
|
||||
setScope(parentScope, p.name);
|
||||
} else if (p.type === "RestElement") {
|
||||
handlePattern(p.argument, parentScope);
|
||||
} else if (p.type === "ObjectPattern") {
|
||||
p.properties.forEach((property) => {
|
||||
if (property.type === "RestElement") {
|
||||
setScope(parentScope, property.argument.name);
|
||||
} else {
|
||||
handlePattern(property.value, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "ArrayPattern") {
|
||||
p.elements.forEach((element) => {
|
||||
if (element) {
|
||||
handlePattern(element, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "AssignmentPattern") {
|
||||
handlePattern(p.left, parentScope);
|
||||
} else {
|
||||
setScope(parentScope, p.name);
|
||||
}
|
||||
}
|
||||
walk(root, {
|
||||
enter(node, parent) {
|
||||
if (node.type === "ImportDeclaration") {
|
||||
return this.skip();
|
||||
}
|
||||
// track parent stack, skip for "else-if"/"else" branches as acorn nests
|
||||
// the ast within "if" nodes instead of flattening them
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.unshift(parent);
|
||||
}
|
||||
// track variable declaration kind stack used by VariableDeclarator
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.unshift(node.kind);
|
||||
}
|
||||
if (node.type === "CallExpression") {
|
||||
onCallExpression === null || onCallExpression === void 0 ? void 0 : onCallExpression(node);
|
||||
}
|
||||
if (node.type === "MetaProperty" && node.meta.name === "import") {
|
||||
onImportMeta === null || onImportMeta === void 0 ? void 0 : onImportMeta(node);
|
||||
} else if (node.type === "ImportExpression") {
|
||||
onDynamicImport === null || onDynamicImport === void 0 ? void 0 : onDynamicImport(node);
|
||||
}
|
||||
if (node.type === "Identifier") {
|
||||
if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) {
|
||||
// record the identifier, for DFS -> BFS
|
||||
identifiers.push([node, parentStack.slice(0)]);
|
||||
}
|
||||
} else if (isFunctionNode(node)) {
|
||||
// If it is a function declaration, it could be shadowing an import
|
||||
// Add its name to the scope so it won't get replaced
|
||||
if (node.type === "FunctionDeclaration") {
|
||||
const parentScope = findParentScope(parentStack);
|
||||
if (parentScope) {
|
||||
setScope(parentScope, node.id.name);
|
||||
}
|
||||
}
|
||||
// walk function expressions and add its arguments to known identifiers
|
||||
// so that we don't prefix them
|
||||
node.params.forEach((p) => {
|
||||
if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
|
||||
handlePattern(p, node);
|
||||
return;
|
||||
}
|
||||
walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
|
||||
// skip params default value of destructure
|
||||
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "AssignmentPattern" && (parent === null || parent === void 0 ? void 0 : parent.right) === child) {
|
||||
return this.skip();
|
||||
}
|
||||
if (child.type !== "Identifier") {
|
||||
return;
|
||||
}
|
||||
// do not record as scope variable if is a destructuring keyword
|
||||
if (isStaticPropertyKey(child, parent)) {
|
||||
return;
|
||||
}
|
||||
// do not record if this is a default value
|
||||
// assignment of a destructuring variable
|
||||
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "TemplateLiteral" && (parent === null || parent === void 0 ? void 0 : parent.expressions.includes(child)) || (parent === null || parent === void 0 ? void 0 : parent.type) === "CallExpression" && (parent === null || parent === void 0 ? void 0 : parent.callee) === child) {
|
||||
return;
|
||||
}
|
||||
setScope(node, child.name);
|
||||
} });
|
||||
});
|
||||
} else if (node.type === "Property" && parent.type === "ObjectPattern") {
|
||||
// mark property in destructuring pattern
|
||||
setIsNodeInPattern(node);
|
||||
} else if (node.type === "VariableDeclarator") {
|
||||
const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
|
||||
if (parentFunction) {
|
||||
handlePattern(node.id, parentFunction);
|
||||
}
|
||||
} else if (node.type === "CatchClause" && node.param) {
|
||||
handlePattern(node.param, node);
|
||||
}
|
||||
},
|
||||
leave(node, parent) {
|
||||
// untrack parent stack from above
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.shift();
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.shift();
|
||||
}
|
||||
}
|
||||
});
|
||||
// emit the identifier events in BFS so the hoisted declarations
|
||||
// can be captured correctly
|
||||
identifiers.forEach(([node, stack]) => {
|
||||
if (!isInScope(node.name, stack)) {
|
||||
const parent = stack[0];
|
||||
const grandparent = stack[1];
|
||||
const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack));
|
||||
const classDeclaration = parent.type === "PropertyDefinition" && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && node === parent.superClass;
|
||||
const classExpression = parent.type === "ClassExpression" && node === parent.id;
|
||||
onIdentifier === null || onIdentifier === void 0 ? void 0 : onIdentifier(node, {
|
||||
hasBindingShortcut,
|
||||
classDeclaration,
|
||||
classExpression
|
||||
}, stack);
|
||||
}
|
||||
});
|
||||
}
|
||||
function isRefIdentifier(id, parent, parentStack) {
|
||||
// declaration id
|
||||
if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
if (isFunctionNode(parent)) {
|
||||
// function declaration/expression id
|
||||
if (parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
// params list
|
||||
if (parent.params.includes(id)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// class method name
|
||||
if (parent.type === "MethodDefinition" && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
// property key
|
||||
if (isStaticPropertyKey(id, parent)) {
|
||||
return false;
|
||||
}
|
||||
// object destructuring pattern
|
||||
if (isNodeInPattern(parent) && parent.value === id) {
|
||||
return false;
|
||||
}
|
||||
// non-assignment array destructuring pattern
|
||||
if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) {
|
||||
return false;
|
||||
}
|
||||
// member expression property
|
||||
if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
if (parent.type === "ExportSpecifier") {
|
||||
return false;
|
||||
}
|
||||
// is a special keyword but parsed as identifier
|
||||
if (id.name === "arguments") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isStaticProperty(node) {
|
||||
return node && node.type === "Property" && !node.computed;
|
||||
}
|
||||
function isStaticPropertyKey(node, parent) {
|
||||
return isStaticProperty(parent) && parent.key === node;
|
||||
}
|
||||
const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
|
||||
function isFunctionNode(node) {
|
||||
return functionNodeTypeRE.test(node.type);
|
||||
}
|
||||
const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
|
||||
function isBlock(node) {
|
||||
return blockNodeTypeRE.test(node.type);
|
||||
}
|
||||
function findParentScope(parentStack, isVar = false) {
|
||||
return parentStack.find(isVar ? isFunctionNode : isBlock);
|
||||
}
|
||||
function isInDestructuringAssignment(parent, parentStack) {
|
||||
if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) {
|
||||
return parentStack.some((i) => i.type === "AssignmentExpression");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getArbitraryModuleIdentifier(node) {
|
||||
return node.type === "Identifier" ? node.name : node.raw;
|
||||
}
|
||||
|
||||
// TODO: better source map replacement
|
||||
function automockModule(code, mockType, parse, options = {}) {
|
||||
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
const ast = parse(code);
|
||||
const m = new MagicString(code);
|
||||
const allSpecifiers = [];
|
||||
let importIndex = 0;
|
||||
for (const _node of ast.body) {
|
||||
if (_node.type === "ExportAllDeclaration") {
|
||||
throw new Error(`automocking files with \`export *\` is not supported in browser mode because it cannot be statically analysed`);
|
||||
}
|
||||
if (_node.type === "ExportNamedDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
function traversePattern(expression) {
|
||||
// export const test = '1'
|
||||
if (expression.type === "Identifier") {
|
||||
allSpecifiers.push({ name: expression.name });
|
||||
} else if (expression.type === "ArrayPattern") {
|
||||
expression.elements.forEach((element) => {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
traversePattern(element);
|
||||
});
|
||||
} else if (expression.type === "ObjectPattern") {
|
||||
expression.properties.forEach((property) => {
|
||||
// export const { ...rest } = {}
|
||||
if (property.type === "RestElement") {
|
||||
traversePattern(property);
|
||||
} else if (property.type === "Property") {
|
||||
traversePattern(property.value);
|
||||
} else ;
|
||||
});
|
||||
} else if (expression.type === "RestElement") {
|
||||
traversePattern(expression.argument);
|
||||
} else if (expression.type === "AssignmentPattern") {
|
||||
throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`);
|
||||
} else if (expression.type === "MemberExpression") {
|
||||
throw new Error(`MemberExpression is not supported. Please open a new bug report.`);
|
||||
} else ;
|
||||
}
|
||||
if (declaration) {
|
||||
if (declaration.type === "FunctionDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else if (declaration.type === "VariableDeclaration") {
|
||||
declaration.declarations.forEach((declaration) => {
|
||||
traversePattern(declaration.id);
|
||||
});
|
||||
} else if (declaration.type === "ClassDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else ;
|
||||
m.remove(node.start, declaration.start);
|
||||
}
|
||||
const specifiers = node.specifiers || [];
|
||||
const source = node.source;
|
||||
if (!source && specifiers.length) {
|
||||
specifiers.forEach((specifier) => {
|
||||
allSpecifiers.push({
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported),
|
||||
name: getArbitraryModuleIdentifier(specifier.local)
|
||||
});
|
||||
});
|
||||
m.remove(node.start, node.end);
|
||||
} else if (source && specifiers.length) {
|
||||
const importNames = [];
|
||||
specifiers.forEach((specifier) => {
|
||||
const importedName = `__vitest_imported_${importIndex++}__`;
|
||||
importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]);
|
||||
allSpecifiers.push({
|
||||
name: importedName,
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported)
|
||||
});
|
||||
});
|
||||
const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`;
|
||||
m.overwrite(node.start, node.end, importString);
|
||||
}
|
||||
}
|
||||
if (_node.type === "ExportDefaultDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
allSpecifiers.push({
|
||||
name: "__vitest_default",
|
||||
alias: "default"
|
||||
});
|
||||
m.overwrite(node.start, declaration.start, `const __vitest_default = `);
|
||||
}
|
||||
}
|
||||
const moduleObject = `
|
||||
const __vitest_current_es_module__ = {
|
||||
__esModule: true,
|
||||
${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")}
|
||||
}
|
||||
const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}")
|
||||
`;
|
||||
const assigning = allSpecifiers.map(({ name }, index) => {
|
||||
return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`;
|
||||
}).join("\n");
|
||||
const redeclarations = allSpecifiers.map(({ name, alias }, index) => {
|
||||
return ` __vitest_mocked_${index}__ as ${alias || name},`;
|
||||
}).join("\n");
|
||||
const specifiersExports = `
|
||||
export {
|
||||
${redeclarations}
|
||||
}
|
||||
`;
|
||||
m.append(moduleObject + assigning + specifiersExports);
|
||||
return m;
|
||||
}
|
||||
|
||||
export { automockModule as a, esmWalker as e };
|
||||
15
node_modules/@vitest/mocker/dist/chunk-interceptor-native.js
generated
vendored
Normal file
15
node_modules/@vitest/mocker/dist/chunk-interceptor-native.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { r as rpc } from './chunk-mocker.js';
|
||||
|
||||
class ModuleMockerServerInterceptor {
|
||||
async register(module) {
|
||||
await rpc("vitest:interceptor:register", module.toJSON());
|
||||
}
|
||||
async delete(id) {
|
||||
await rpc("vitest:interceptor:delete", id);
|
||||
}
|
||||
async invalidate() {
|
||||
await rpc("vitest:interceptor:invalidate");
|
||||
}
|
||||
}
|
||||
|
||||
export { ModuleMockerServerInterceptor as M };
|
||||
521
node_modules/@vitest/mocker/dist/chunk-mocker.js
generated
vendored
Normal file
521
node_modules/@vitest/mocker/dist/chunk-mocker.js
generated
vendored
Normal file
@@ -0,0 +1,521 @@
|
||||
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) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
||||
}
|
||||
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
||||
function cwd() {
|
||||
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
||||
return process.cwd().replace(/\\/g, "/");
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
const resolve = function(...arguments_) {
|
||||
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
||||
const path = index >= 0 ? arguments_[index] : cwd();
|
||||
if (!path || path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let index = 0; index <= path.length; ++index) {
|
||||
if (index < path.length) {
|
||||
char = path[index];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === index - 1 || dots === 1);
|
||||
else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length > 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path.slice(lastSlash + 1, index)}`;
|
||||
} else {
|
||||
res = path.slice(lastSlash + 1, index);
|
||||
}
|
||||
lastSegmentLength = index - lastSlash - 1;
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
|
||||
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
|
||||
function extractLocation(urlLike) {
|
||||
// Fail-fast but return locations like "(native)"
|
||||
if (!urlLike.includes(":")) {
|
||||
return [urlLike];
|
||||
}
|
||||
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
|
||||
const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
|
||||
if (!parts) {
|
||||
return [urlLike];
|
||||
}
|
||||
let url = parts[1];
|
||||
if (url.startsWith("async ")) {
|
||||
url = url.slice(6);
|
||||
}
|
||||
if (url.startsWith("http:") || url.startsWith("https:")) {
|
||||
const urlObj = new URL(url);
|
||||
urlObj.searchParams.delete("import");
|
||||
urlObj.searchParams.delete("browserv");
|
||||
url = urlObj.pathname + urlObj.hash + urlObj.search;
|
||||
}
|
||||
if (url.startsWith("/@fs/")) {
|
||||
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
|
||||
url = url.slice(isWindows ? 5 : 4);
|
||||
}
|
||||
return [
|
||||
url,
|
||||
parts[2] || undefined,
|
||||
parts[3] || undefined
|
||||
];
|
||||
}
|
||||
function parseSingleFFOrSafariStack(raw) {
|
||||
let line = raw.trim();
|
||||
if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
|
||||
return null;
|
||||
}
|
||||
if (line.includes(" > eval")) {
|
||||
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
|
||||
}
|
||||
// Early return for lines that don't look like Firefox/Safari stack traces
|
||||
// Firefox/Safari stack traces must contain '@' and should have location info after it
|
||||
if (!line.includes("@")) {
|
||||
return null;
|
||||
}
|
||||
// Find the correct @ that separates function name from location
|
||||
// For cases like '@https://@fs/path' or 'functionName@https://@fs/path'
|
||||
// we need to find the first @ that precedes a valid location (containing :)
|
||||
let atIndex = -1;
|
||||
let locationPart = "";
|
||||
let functionName;
|
||||
// Try each @ from left to right to find the one that gives us a valid location
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
if (line[i] === "@") {
|
||||
const candidateLocation = line.slice(i + 1);
|
||||
// Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1")
|
||||
if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
|
||||
atIndex = i;
|
||||
locationPart = candidateLocation;
|
||||
functionName = i > 0 ? line.slice(0, i) : undefined;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Validate we found a valid location with minimum length (filename:line format)
|
||||
if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
|
||||
return null;
|
||||
}
|
||||
const [url, lineNumber, columnNumber] = extractLocation(locationPart);
|
||||
if (!url || !lineNumber || !columnNumber) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
file: url,
|
||||
method: functionName || "",
|
||||
line: Number.parseInt(lineNumber),
|
||||
column: Number.parseInt(columnNumber)
|
||||
};
|
||||
}
|
||||
function parseSingleStack(raw) {
|
||||
const line = raw.trim();
|
||||
if (!CHROME_IE_STACK_REGEXP.test(line)) {
|
||||
return parseSingleFFOrSafariStack(line);
|
||||
}
|
||||
return parseSingleV8Stack(line);
|
||||
}
|
||||
// Based on https://github.com/stacktracejs/error-stack-parser
|
||||
// Credit to stacktracejs
|
||||
function parseSingleV8Stack(raw) {
|
||||
let line = raw.trim();
|
||||
if (!CHROME_IE_STACK_REGEXP.test(line)) {
|
||||
return null;
|
||||
}
|
||||
if (line.includes("(eval ")) {
|
||||
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
|
||||
}
|
||||
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
|
||||
// capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in
|
||||
// case it has spaces in it, as the string is split on \s+ later on
|
||||
const location = sanitizedLine.match(/ (\(.+\)$)/);
|
||||
// remove the parenthesized location from the line, if it was matched
|
||||
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
|
||||
// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
|
||||
// because this line doesn't have function name
|
||||
const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
|
||||
let method = location && sanitizedLine || "";
|
||||
let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url;
|
||||
if (!file || !lineNumber || !columnNumber) {
|
||||
return null;
|
||||
}
|
||||
if (method.startsWith("async ")) {
|
||||
method = method.slice(6);
|
||||
}
|
||||
if (file.startsWith("file://")) {
|
||||
file = file.slice(7);
|
||||
}
|
||||
// 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, "");
|
||||
}
|
||||
return {
|
||||
method,
|
||||
file,
|
||||
line: Number.parseInt(lineNumber),
|
||||
column: Number.parseInt(columnNumber)
|
||||
};
|
||||
}
|
||||
|
||||
function createCompilerHints(options) {
|
||||
const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__";
|
||||
function _mocker() {
|
||||
// @ts-expect-error injected by the plugin
|
||||
return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) {
|
||||
throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`);
|
||||
} });
|
||||
}
|
||||
return {
|
||||
hoisted(factory) {
|
||||
if (typeof factory !== "function") {
|
||||
throw new TypeError(`vi.hoisted() expects a function, but received a ${typeof factory}`);
|
||||
}
|
||||
return factory();
|
||||
},
|
||||
mock(path, factory) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
const importer = getImporter("mock");
|
||||
_mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory);
|
||||
},
|
||||
unmock(path) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
_mocker().queueUnmock(path, getImporter("unmock"));
|
||||
},
|
||||
doMock(path, factory) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
const importer = getImporter("doMock");
|
||||
_mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory);
|
||||
},
|
||||
doUnmock(path) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
_mocker().queueUnmock(path, getImporter("doUnmock"));
|
||||
},
|
||||
async importActual(path) {
|
||||
return _mocker().importActual(path, getImporter("importActual"));
|
||||
},
|
||||
async importMock(path) {
|
||||
return _mocker().importMock(path, getImporter("importMock"));
|
||||
}
|
||||
};
|
||||
}
|
||||
function getImporter(name) {
|
||||
const stackTrace = /* @__PURE__ */ createSimpleStackTrace({ stackTraceLimit: 5 });
|
||||
const stackArray = stackTrace.split("\n");
|
||||
// if there is no message in a stack trace, use the item - 1
|
||||
const importerStackIndex = stackArray.findIndex((stack) => {
|
||||
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) || "";
|
||||
}
|
||||
|
||||
const hot = import.meta.hot || {
|
||||
on: warn,
|
||||
off: warn,
|
||||
send: warn
|
||||
};
|
||||
function warn() {
|
||||
console.warn("Vitest mocker cannot work if Vite didn't establish WS connection.");
|
||||
}
|
||||
function rpc(event, data) {
|
||||
hot.send(event, data);
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error(`Failed to resolve ${event} in time`));
|
||||
}, 5e3);
|
||||
hot.on(`${event}:result`, function r(data) {
|
||||
resolve(data);
|
||||
clearTimeout(timeout);
|
||||
hot.off(`${event}:result`, r);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const { now } = Date;
|
||||
class ModuleMocker {
|
||||
registry = new MockerRegistry();
|
||||
queue = new Set();
|
||||
mockedIds = new Set();
|
||||
constructor(interceptor, rpc, createMockInstance, config) {
|
||||
this.interceptor = interceptor;
|
||||
this.rpc = rpc;
|
||||
this.createMockInstance = createMockInstance;
|
||||
this.config = config;
|
||||
}
|
||||
async prepare() {
|
||||
if (!this.queue.size) {
|
||||
return;
|
||||
}
|
||||
await Promise.all([...this.queue.values()]);
|
||||
}
|
||||
async resolveFactoryModule(id) {
|
||||
const mock = this.registry.get(id);
|
||||
if (!mock || mock.type !== "manual") {
|
||||
throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
const result = await mock.resolve();
|
||||
return result;
|
||||
}
|
||||
getFactoryModule(id) {
|
||||
const mock = this.registry.get(id);
|
||||
if (!mock || mock.type !== "manual") {
|
||||
throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
if (!mock.cache) {
|
||||
throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
return mock.cache;
|
||||
}
|
||||
async invalidate() {
|
||||
const ids = Array.from(this.mockedIds);
|
||||
if (!ids.length) {
|
||||
return;
|
||||
}
|
||||
await this.rpc.invalidate(ids);
|
||||
await this.interceptor.invalidate();
|
||||
this.registry.clear();
|
||||
}
|
||||
async importActual(id, importer) {
|
||||
const resolved = await this.rpc.resolveId(id, importer);
|
||||
if (resolved == null) {
|
||||
throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
|
||||
}
|
||||
const ext = extname(resolved.id);
|
||||
const url = new URL(resolved.url, location.href);
|
||||
const query = `_vitest_original&ext${ext}`;
|
||||
const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`;
|
||||
return this.wrapDynamicImport(() => import(
|
||||
/* @vite-ignore */
|
||||
actualUrl
|
||||
)).then((mod) => {
|
||||
if (!resolved.optimized || typeof mod.default === "undefined") {
|
||||
return mod;
|
||||
}
|
||||
// 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 : {
|
||||
...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
|
||||
default: m
|
||||
};
|
||||
});
|
||||
}
|
||||
async importMock(rawId, importer) {
|
||||
await this.prepare();
|
||||
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
|
||||
let mock = this.registry.get(mockUrl);
|
||||
if (!mock) {
|
||||
if (redirectUrl) {
|
||||
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
|
||||
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
|
||||
} else {
|
||||
mock = new AutomockedModule(rawId, resolvedId, mockUrl);
|
||||
}
|
||||
}
|
||||
if (mock.type === "manual") {
|
||||
return await mock.resolve();
|
||||
}
|
||||
if (mock.type === "automock" || mock.type === "autospy") {
|
||||
const url = new URL(`/@id/${resolvedId}`, location.href);
|
||||
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`;
|
||||
const moduleObject = await import(
|
||||
/* @vite-ignore */
|
||||
`${url.pathname}${query}&mock=${mock.type}${url.hash}`
|
||||
);
|
||||
return this.mockObject(moduleObject, mock.type);
|
||||
}
|
||||
return import(
|
||||
/* @vite-ignore */
|
||||
mock.redirect
|
||||
);
|
||||
}
|
||||
mockObject(object, moduleType = "automock") {
|
||||
return mockObject({
|
||||
globalConstructors: {
|
||||
Object,
|
||||
Function,
|
||||
Array,
|
||||
Map,
|
||||
RegExp
|
||||
},
|
||||
createMockInstance: this.createMockInstance,
|
||||
type: moduleType
|
||||
}, object);
|
||||
}
|
||||
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 mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
|
||||
this.mockedIds.add(resolvedId);
|
||||
const factory = typeof factoryOrOptions === "function" ? async () => {
|
||||
const data = await factoryOrOptions();
|
||||
// vite wraps all external modules that have "needsInterop" in a function that
|
||||
// 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;
|
||||
let module;
|
||||
if (mockType === "manual") {
|
||||
module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
|
||||
} else if (mockType === "autospy") {
|
||||
module = this.registry.register("autospy", rawId, resolvedId, mockUrl);
|
||||
} else if (mockType === "redirect") {
|
||||
module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect);
|
||||
} else {
|
||||
module = this.registry.register("automock", rawId, resolvedId, mockUrl);
|
||||
}
|
||||
await this.interceptor.register(module);
|
||||
}).finally(() => {
|
||||
this.queue.delete(promise);
|
||||
});
|
||||
this.queue.add(promise);
|
||||
}
|
||||
queueUnmock(id, importer) {
|
||||
const promise = this.rpc.resolveId(id, importer).then(async (resolved) => {
|
||||
if (!resolved) {
|
||||
return;
|
||||
}
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolved.url));
|
||||
this.mockedIds.add(resolved.id);
|
||||
this.registry.delete(mockUrl);
|
||||
await this.interceptor.delete(mockUrl);
|
||||
}).finally(() => {
|
||||
this.queue.delete(promise);
|
||||
});
|
||||
this.queue.add(promise);
|
||||
}
|
||||
// We need to await mock registration before importing the actual module
|
||||
// In case there is a mocked module in the import chain
|
||||
wrapDynamicImport(moduleFactory) {
|
||||
if (typeof moduleFactory === "function") {
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
this.prepare().finally(() => {
|
||||
moduleFactory().then(resolve, reject);
|
||||
});
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
return moduleFactory;
|
||||
}
|
||||
resolveMockPath(path) {
|
||||
const config = this.config;
|
||||
const fsRoot = join("/@fs/", config.root);
|
||||
// URL can be /file/path.js, but path is resolved to /file/path
|
||||
if (path.startsWith(config.root)) {
|
||||
return path.slice(config.root.length);
|
||||
}
|
||||
if (path.startsWith(fsRoot)) {
|
||||
return path.slice(fsRoot.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
const versionRegexp = /(\?|&)v=\w{8}/;
|
||||
function cleanVersion(url) {
|
||||
return url.replace(versionRegexp, "");
|
||||
}
|
||||
|
||||
export { ModuleMocker as M, createCompilerHints as c, hot as h, rpc as r };
|
||||
174
node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
174
node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/\\]{2}/;
|
||||
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
||||
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
||||
const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
|
||||
const normalize = function(path) {
|
||||
if (path.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path = normalizeWindowsPath(path);
|
||||
const isUNCPath = path.match(_UNC_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path);
|
||||
const trailingSeparator = path[path.length - 1] === "/";
|
||||
path = normalizeString(path, !isPathAbsolute);
|
||||
if (path.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path += "/";
|
||||
}
|
||||
if (_DRIVE_LETTER_RE.test(path)) {
|
||||
path += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (!isPathAbsolute) {
|
||||
return `//./${path}`;
|
||||
}
|
||||
return `//${path}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
|
||||
};
|
||||
const join = function(...segments) {
|
||||
let path = "";
|
||||
for (const seg of segments) {
|
||||
if (!seg) {
|
||||
continue;
|
||||
}
|
||||
if (path.length > 0) {
|
||||
const pathTrailing = path[path.length - 1] === "/";
|
||||
const segLeading = seg[0] === "/";
|
||||
const both = pathTrailing && segLeading;
|
||||
if (both) {
|
||||
path += seg.slice(1);
|
||||
} else {
|
||||
path += pathTrailing || segLeading ? seg : `/${seg}`;
|
||||
}
|
||||
} else {
|
||||
path += seg;
|
||||
}
|
||||
}
|
||||
return normalize(path);
|
||||
};
|
||||
function cwd() {
|
||||
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
||||
return process.cwd().replace(/\\/g, "/");
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
const resolve = function(...arguments_) {
|
||||
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
||||
const path = index >= 0 ? arguments_[index] : cwd();
|
||||
if (!path || path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let index = 0; index <= path.length; ++index) {
|
||||
if (index < path.length) {
|
||||
char = path[index];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length > 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path.slice(lastSlash + 1, index)}`;
|
||||
} else {
|
||||
res = path.slice(lastSlash + 1, index);
|
||||
}
|
||||
lastSegmentLength = index - lastSlash - 1;
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
const extname = function(p) {
|
||||
if (p === "..") return "";
|
||||
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
|
||||
return match && match[1] || "";
|
||||
};
|
||||
const dirname = function(p) {
|
||||
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
||||
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
|
||||
segments[0] += "/";
|
||||
}
|
||||
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
||||
};
|
||||
const basename = function(p, extension) {
|
||||
const segments = normalizeWindowsPath(p).split("/");
|
||||
let lastSegment = "";
|
||||
for (let i = segments.length - 1; i >= 0; i--) {
|
||||
const val = segments[i];
|
||||
if (val) {
|
||||
lastSegment = val;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
|
||||
};
|
||||
|
||||
export { basename as b, dirname as d, extname as e, isAbsolute as i, join as j, resolve as r };
|
||||
185
node_modules/@vitest/mocker/dist/chunk-registry.js
generated
vendored
Normal file
185
node_modules/@vitest/mocker/dist/chunk-registry.js
generated
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
class MockerRegistry {
|
||||
registryByUrl = new Map();
|
||||
registryById = new Map();
|
||||
clear() {
|
||||
this.registryByUrl.clear();
|
||||
this.registryById.clear();
|
||||
}
|
||||
keys() {
|
||||
return this.registryByUrl.keys();
|
||||
}
|
||||
add(mock) {
|
||||
this.registryByUrl.set(mock.url, mock);
|
||||
this.registryById.set(mock.id, mock);
|
||||
}
|
||||
register(typeOrEvent, raw, id, url, factoryOrRedirect) {
|
||||
const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent;
|
||||
if (typeof typeOrEvent === "object") {
|
||||
const event = typeOrEvent;
|
||||
if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) {
|
||||
throw new TypeError(`[vitest] Cannot register a mock that is already defined. ` + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". ` + `Use "registry.add()" to update a mock instead.`);
|
||||
}
|
||||
if (event.type === "automock") {
|
||||
const module = AutomockedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "autospy") {
|
||||
const module = AutospiedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "redirect") {
|
||||
const module = RedirectedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "manual") {
|
||||
throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`);
|
||||
} else {
|
||||
throw new Error(`Unknown mock type: ${event.type}`);
|
||||
}
|
||||
}
|
||||
if (typeof raw !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require a raw string.");
|
||||
}
|
||||
if (typeof url !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require a url string.");
|
||||
}
|
||||
if (typeof id !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require an id string.");
|
||||
}
|
||||
if (type === "manual") {
|
||||
if (typeof factoryOrRedirect !== "function") {
|
||||
throw new TypeError("[vitest] Manual mocks require a factory function.");
|
||||
}
|
||||
const mock = new ManualMockedModule(raw, id, url, factoryOrRedirect);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else if (type === "automock" || type === "autospy") {
|
||||
const mock = type === "automock" ? new AutomockedModule(raw, id, url) : new AutospiedModule(raw, id, url);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else if (type === "redirect") {
|
||||
if (typeof factoryOrRedirect !== "string") {
|
||||
throw new TypeError("[vitest] Redirect mocks require a redirect string.");
|
||||
}
|
||||
const mock = new RedirectedModule(raw, id, url, factoryOrRedirect);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else {
|
||||
throw new Error(`[vitest] Unknown mock type: ${type}`);
|
||||
}
|
||||
}
|
||||
delete(id) {
|
||||
this.registryByUrl.delete(id);
|
||||
}
|
||||
deleteById(id) {
|
||||
this.registryById.delete(id);
|
||||
}
|
||||
get(id) {
|
||||
return this.registryByUrl.get(id);
|
||||
}
|
||||
getById(id) {
|
||||
return this.registryById.get(id);
|
||||
}
|
||||
has(id) {
|
||||
return this.registryByUrl.has(id);
|
||||
}
|
||||
}
|
||||
class AutomockedModule {
|
||||
type = "automock";
|
||||
constructor(raw, id, url) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new AutospiedModule(data.raw, data.id, data.url);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
raw: this.raw,
|
||||
id: this.id
|
||||
};
|
||||
}
|
||||
}
|
||||
class AutospiedModule {
|
||||
type = "autospy";
|
||||
constructor(raw, id, url) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new AutospiedModule(data.raw, data.id, data.url);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
id: this.id,
|
||||
raw: this.raw
|
||||
};
|
||||
}
|
||||
}
|
||||
class RedirectedModule {
|
||||
type = "redirect";
|
||||
constructor(raw, id, url, redirect) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
this.redirect = redirect;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new RedirectedModule(data.raw, data.id, data.url, data.redirect);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
raw: this.raw,
|
||||
id: this.id,
|
||||
redirect: this.redirect
|
||||
};
|
||||
}
|
||||
}
|
||||
class ManualMockedModule {
|
||||
cache;
|
||||
type = "manual";
|
||||
constructor(raw, id, url, factory) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
this.factory = factory;
|
||||
}
|
||||
async resolve() {
|
||||
if (this.cache) {
|
||||
return this.cache;
|
||||
}
|
||||
let exports$1;
|
||||
try {
|
||||
exports$1 = await 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;
|
||||
}
|
||||
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?`);
|
||||
}
|
||||
return this.cache = exports$1;
|
||||
}
|
||||
static fromJSON(data, factory) {
|
||||
return new ManualMockedModule(data.raw, data.id, data.url, factory);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
id: this.id,
|
||||
raw: this.raw
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b };
|
||||
16
node_modules/@vitest/mocker/dist/chunk-utils.js
generated
vendored
Normal file
16
node_modules/@vitest/mocker/dist/chunk-utils.js
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
const postfixRE = /[?#].*$/;
|
||||
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}"];`;
|
||||
}).join("\n");
|
||||
return `${source}\n${keys}`;
|
||||
}
|
||||
|
||||
export { cleanUrl as a, createManualModuleSource as c };
|
||||
25
node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts
generated
vendored
Normal file
25
node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
import './types.d-B8CCKmHt.js';
|
||||
|
||||
type Key = string | symbol;
|
||||
type CreateMockInstanceProcedure = (options?: {
|
||||
prototypeMembers?: (string | symbol)[];
|
||||
name?: string | symbol;
|
||||
originalImplementation?: (...args: any[]) => any;
|
||||
keepMembersImplementation?: boolean;
|
||||
}) => any;
|
||||
interface MockObjectOptions {
|
||||
type: "automock" | "autospy";
|
||||
globalConstructors: GlobalConstructors;
|
||||
createMockInstance: CreateMockInstanceProcedure;
|
||||
}
|
||||
declare function mockObject(options: MockObjectOptions, object: Record<Key, any>, mockExports?: Record<Key, any>): Record<Key, any>;
|
||||
interface GlobalConstructors {
|
||||
Object: ObjectConstructor;
|
||||
Function: FunctionConstructor;
|
||||
RegExp: RegExpConstructor;
|
||||
Array: ArrayConstructor;
|
||||
Map: MapConstructor;
|
||||
}
|
||||
|
||||
export { mockObject as m };
|
||||
export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M };
|
||||
2
node_modules/@vitest/mocker/dist/index.d.ts
generated
vendored
Normal file
2
node_modules/@vitest/mocker/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +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';
|
||||
185
node_modules/@vitest/mocker/dist/index.js
generated
vendored
Normal file
185
node_modules/@vitest/mocker/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js';
|
||||
|
||||
function mockObject(options, object, mockExports = {}) {
|
||||
const finalizers = new Array();
|
||||
const refs = new RefTracker();
|
||||
const define = (container, key, value) => {
|
||||
try {
|
||||
container[key] = value;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const createMock = (currentValue) => {
|
||||
if (!options.createMockInstance) {
|
||||
throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
|
||||
}
|
||||
const createMockInstance = options.createMockInstance;
|
||||
const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
|
||||
return createMockInstance({
|
||||
name: currentValue.name,
|
||||
prototypeMembers,
|
||||
originalImplementation: options.type === "autospy" ? currentValue : undefined,
|
||||
keepMembersImplementation: options.type === "autospy"
|
||||
});
|
||||
};
|
||||
const mockPropertiesOf = (container, newContainer) => {
|
||||
const containerType = getType(container);
|
||||
const isModule = containerType === "Module" || !!container.__esModule;
|
||||
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
|
||||
// Modules define their exports as getters. We want to process those.
|
||||
if (!isModule && descriptor.get) {
|
||||
try {
|
||||
if (options.type === "autospy") {
|
||||
Object.defineProperty(newContainer, property, descriptor);
|
||||
} else {
|
||||
Object.defineProperty(newContainer, property, {
|
||||
configurable: descriptor.configurable,
|
||||
enumerable: descriptor.enumerable,
|
||||
get: () => {},
|
||||
set: descriptor.set ? () => {} : undefined
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
continue;
|
||||
}
|
||||
// Skip special read-only props, we don't want to mess with those.
|
||||
if (isReadonlyProp(container[property], property)) {
|
||||
continue;
|
||||
}
|
||||
const value = container[property];
|
||||
// Special handling of references we've seen before to prevent infinite
|
||||
// recursion in circular objects.
|
||||
const refId = refs.getId(value);
|
||||
if (refId !== undefined) {
|
||||
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
|
||||
continue;
|
||||
}
|
||||
const type = getType(value);
|
||||
if (Array.isArray(value)) {
|
||||
if (options.type === "automock") {
|
||||
define(newContainer, property, []);
|
||||
} else {
|
||||
const array = value.map((value) => {
|
||||
if (value && typeof value === "object") {
|
||||
const newObject = {};
|
||||
mockPropertiesOf(value, newObject);
|
||||
return newObject;
|
||||
}
|
||||
if (typeof value === "function") {
|
||||
return createMock(value);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
define(newContainer, property, array);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const isFunction = type.includes("Function") && typeof value === "function";
|
||||
if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
|
||||
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 : {})) {
|
||||
continue;
|
||||
}
|
||||
if (isFunction) {
|
||||
const mock = createMock(newContainer[property]);
|
||||
newContainer[property] = mock;
|
||||
}
|
||||
refs.track(value, newContainer[property]);
|
||||
mockPropertiesOf(value, newContainer[property]);
|
||||
}
|
||||
};
|
||||
const mockedObject = mockExports;
|
||||
mockPropertiesOf(object, mockedObject);
|
||||
// Plug together refs
|
||||
for (const finalizer of finalizers) {
|
||||
finalizer();
|
||||
}
|
||||
return mockedObject;
|
||||
}
|
||||
class RefTracker {
|
||||
idMap = new Map();
|
||||
mockedValueMap = new Map();
|
||||
getId(value) {
|
||||
return this.idMap.get(value);
|
||||
}
|
||||
getMockedValue(id) {
|
||||
return this.mockedValueMap.get(id);
|
||||
}
|
||||
track(originalValue, mockedValue) {
|
||||
const newId = this.idMap.size;
|
||||
this.idMap.set(originalValue, newId);
|
||||
this.mockedValueMap.set(newId, mockedValue);
|
||||
return newId;
|
||||
}
|
||||
}
|
||||
function getType(value) {
|
||||
return Object.prototype.toString.apply(value).slice(8, -1);
|
||||
}
|
||||
function isReadonlyProp(object, prop) {
|
||||
if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
|
||||
const typeName = getType(object);
|
||||
return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
|
||||
}
|
||||
if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
|
||||
return getType(object) === "RegExp";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getAllMockableProperties(obj, isModule, constructors) {
|
||||
const { Map, Object, Function, RegExp, Array } = constructors;
|
||||
const allProps = new Map();
|
||||
let curr = obj;
|
||||
do {
|
||||
// we don't need properties from these
|
||||
if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) {
|
||||
break;
|
||||
}
|
||||
collectOwnProperties(curr, (key) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(curr, key);
|
||||
if (descriptor) {
|
||||
allProps.set(key, {
|
||||
key,
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
});
|
||||
} while (curr = Object.getPrototypeOf(curr));
|
||||
// default is not specified in ownKeys, if module is interoped
|
||||
if (isModule && !allProps.has("default") && "default" in obj) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(obj, "default");
|
||||
if (descriptor) {
|
||||
allProps.set("default", {
|
||||
key: "default",
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
}
|
||||
return Array.from(allProps.values());
|
||||
}
|
||||
function collectOwnProperties(obj, collector) {
|
||||
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
|
||||
Object.getOwnPropertyNames(obj).forEach(collect);
|
||||
Object.getOwnPropertySymbols(obj).forEach(collect);
|
||||
}
|
||||
function collectFunctionProperties(prototype) {
|
||||
const properties = new Set();
|
||||
collectOwnProperties(prototype, (prop) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
|
||||
if (!descriptor || descriptor.get) {
|
||||
return;
|
||||
}
|
||||
const type = getType(descriptor.value);
|
||||
if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
|
||||
properties.add(prop);
|
||||
}
|
||||
});
|
||||
return Array.from(properties);
|
||||
}
|
||||
|
||||
export { mockObject };
|
||||
81
node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts
generated
vendored
Normal file
81
node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
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';
|
||||
|
||||
interface CompilerHintsOptions {
|
||||
/**
|
||||
* This is the key used to access the globalThis object in the worker.
|
||||
* Unlike `globalThisAccessor` in other APIs, this is not injected into the script.
|
||||
* ```ts
|
||||
* // globalThisKey: '__my_variable__' produces:
|
||||
* globalThis['__my_variable__']
|
||||
* // globalThisKey: '"__my_variable__"' produces:
|
||||
* globalThis['"__my_variable__"'] // notice double quotes
|
||||
* ```
|
||||
* @default '__vitest_mocker__'
|
||||
*/
|
||||
globalThisKey?: string;
|
||||
}
|
||||
interface ModuleMockerCompilerHints {
|
||||
hoisted: <T>(factory: () => T) => T;
|
||||
mock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
|
||||
unmock: (path: string | Promise<unknown>) => void;
|
||||
doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
|
||||
doUnmock: (path: string | Promise<unknown>) => void;
|
||||
importActual: <T>(path: string) => Promise<T>;
|
||||
importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>;
|
||||
}
|
||||
declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints;
|
||||
|
||||
interface ModuleMockerInterceptor {
|
||||
register: (module: MockedModule) => Promise<void>;
|
||||
delete: (url: string) => Promise<void>;
|
||||
invalidate: () => Promise<void>;
|
||||
}
|
||||
|
||||
declare class ModuleMocker {
|
||||
private interceptor;
|
||||
private rpc;
|
||||
private createMockInstance;
|
||||
private config;
|
||||
protected registry: MockerRegistry;
|
||||
private queue;
|
||||
private mockedIds;
|
||||
constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig);
|
||||
prepare(): Promise<void>;
|
||||
resolveFactoryModule(id: string): Promise<Record<string | symbol, any>>;
|
||||
getFactoryModule(id: string): any;
|
||||
invalidate(): Promise<void>;
|
||||
importActual<T>(id: string, importer: string): Promise<T>;
|
||||
importMock<T>(rawId: string, importer: string): Promise<T>;
|
||||
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
|
||||
private resolveMockPath;
|
||||
}
|
||||
interface ResolveIdResult {
|
||||
id: string;
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
interface ResolveMockResult {
|
||||
mockType: MockedModuleType;
|
||||
resolvedId: string;
|
||||
resolvedUrl: string;
|
||||
redirectUrl?: string | null;
|
||||
needsInterop?: boolean;
|
||||
}
|
||||
interface ModuleMockerRPC {
|
||||
invalidate: (ids: string[]) => Promise<void>;
|
||||
resolveId: (id: string, importer: string) => Promise<ResolveIdResult | null>;
|
||||
resolveMock: (id: string, importer: string, options: {
|
||||
mock: "spy" | "factory" | "auto";
|
||||
}) => Promise<ResolveMockResult>;
|
||||
}
|
||||
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 };
|
||||
800
node_modules/@vitest/mocker/dist/node.d.ts
generated
vendored
Normal file
800
node_modules/@vitest/mocker/dist/node.d.ts
generated
vendored
Normal file
@@ -0,0 +1,800 @@
|
||||
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';
|
||||
export { findMockRedirect } from './redirect.js';
|
||||
|
||||
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
|
||||
|
||||
declare function automockPlugin(options?: AutomockOptions): Plugin;
|
||||
|
||||
interface DynamicImportPluginOptions {
|
||||
/**
|
||||
* @default `"__vitest_mocker__"`
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
filter?: (id: string) => boolean;
|
||||
}
|
||||
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)[];
|
||||
/**
|
||||
* overrides include/exclude options
|
||||
*/
|
||||
filter?: (id: string) => boolean;
|
||||
}
|
||||
declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin;
|
||||
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 {
|
||||
/**
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
registry?: MockerRegistry;
|
||||
}
|
||||
declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin;
|
||||
|
||||
interface MockerPluginOptions extends AutomockOptions {
|
||||
hoistMocks?: HoistMocksPluginOptions;
|
||||
}
|
||||
declare function mockerPlugin(options?: MockerPluginOptions): Plugin[];
|
||||
|
||||
interface ServerResolverOptions {
|
||||
/**
|
||||
* @default ['/node_modules/']
|
||||
*/
|
||||
moduleDirectories?: string[];
|
||||
}
|
||||
declare class ServerMockResolver {
|
||||
private server;
|
||||
private options;
|
||||
constructor(server: ViteDevServer, options?: ServerResolverOptions);
|
||||
resolveMock(rawId: string, importer: string, options: {
|
||||
mock: "spy" | "factory" | "auto";
|
||||
}): Promise<ServerMockResolution>;
|
||||
invalidate(ids: string[]): void;
|
||||
resolveId(id: string, importer?: string): Promise<ServerIdResolution | null>;
|
||||
private normalizeResolveIdToUrl;
|
||||
private resolveMockId;
|
||||
private resolveModule;
|
||||
}
|
||||
|
||||
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions };
|
||||
967
node_modules/@vitest/mocker/dist/node.js
generated
vendored
Normal file
967
node_modules/@vitest/mocker/dist/node.js
generated
vendored
Normal file
@@ -0,0 +1,967 @@
|
||||
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 { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path/posix';
|
||||
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
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';
|
||||
|
||||
function automockPlugin(options = {}) {
|
||||
return {
|
||||
name: "vitest:automock",
|
||||
enforce: "post",
|
||||
transform(code, id) {
|
||||
if (id.includes("mock=automock") || id.includes("mock=autospy")) {
|
||||
const mockType = id.includes("mock=automock") ? "automock" : "autospy";
|
||||
const ms = automockModule(code, mockType, this.parse, options);
|
||||
return {
|
||||
code: ms.toString(),
|
||||
map: ms.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const regexDynamicImport = /import\s*\(/;
|
||||
function dynamicImportPlugin(options = {}) {
|
||||
return {
|
||||
name: "vitest:browser:esm-injector",
|
||||
enforce: "post",
|
||||
transform(source, id) {
|
||||
// TODO: test is not called for static imports
|
||||
if (!regexDynamicImport.test(source)) {
|
||||
return;
|
||||
}
|
||||
if (options.filter && !options.filter(id)) {
|
||||
return;
|
||||
}
|
||||
return injectDynamicImport(source, id, this.parse, options);
|
||||
}
|
||||
};
|
||||
}
|
||||
function injectDynamicImport(code, id, parse, options = {}) {
|
||||
const s = new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (err) {
|
||||
console.error(`Cannot parse ${id}:\n${err.message}`);
|
||||
return;
|
||||
}
|
||||
// 3. convert references to import bindings & import.meta references
|
||||
esmWalker(ast, {
|
||||
onImportMeta() {
|
||||
// s.update(node.start, node.end, viImportMetaKey)
|
||||
},
|
||||
onDynamicImport(node) {
|
||||
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
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.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : ""));
|
||||
s.overwrite(node.end - 1, node.end, "))");
|
||||
}
|
||||
});
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: id
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
// 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 = [
|
||||
"mock",
|
||||
"unmock",
|
||||
"doMock",
|
||||
"doUnmock"
|
||||
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options;
|
||||
const methods = new Set([
|
||||
...hoistableMockMethodNames,
|
||||
...hoistedMethodNames,
|
||||
...dynamicImportMockMethodNames
|
||||
]);
|
||||
const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`);
|
||||
return {
|
||||
name: "vitest:mocks",
|
||||
enforce: "post",
|
||||
transform(code, id) {
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
return hoistMocks(code, id, this.parse, {
|
||||
regexpHoistable,
|
||||
hoistableMockMethodNames,
|
||||
hoistedMethodNames,
|
||||
utilsObjectNames,
|
||||
dynamicImportMockMethodNames,
|
||||
...options
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
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
|
||||
};
|
||||
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 = {}) {
|
||||
const registry = options.registry || new MockerRegistry();
|
||||
return {
|
||||
name: "vitest:mocks:interceptor",
|
||||
enforce: "pre",
|
||||
load: {
|
||||
order: "pre",
|
||||
async handler(id) {
|
||||
const mock = registry.getById(id);
|
||||
if (!mock) {
|
||||
return;
|
||||
}
|
||||
if (mock.type === "manual") {
|
||||
const exports$1 = Object.keys(await mock.resolve());
|
||||
const accessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
return createManualModuleSource(mock.url, exports$1, accessor);
|
||||
}
|
||||
if (mock.type === "redirect") {
|
||||
return readFile(mock.redirect, "utf-8");
|
||||
}
|
||||
}
|
||||
},
|
||||
transform: {
|
||||
order: "post",
|
||||
handler(code, id) {
|
||||
const mock = registry.getById(id);
|
||||
if (!mock) {
|
||||
return;
|
||||
}
|
||||
if (mock.type === "automock" || mock.type === "autospy") {
|
||||
const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor });
|
||||
return {
|
||||
code: m.toString(),
|
||||
map: m.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
configureServer(server) {
|
||||
server.ws.on("vitest:interceptor:register", (event) => {
|
||||
if (event.type === "manual") {
|
||||
const module = ManualMockedModule.fromJSON(event, async () => {
|
||||
const keys = await getFactoryExports(event.url);
|
||||
return Object.fromEntries(keys.map((key) => [key, null]));
|
||||
});
|
||||
registry.add(module);
|
||||
} else {
|
||||
if (event.type === "redirect") {
|
||||
const redirectUrl = new URL(event.redirect);
|
||||
event.redirect = join(server.config.root, redirectUrl.pathname);
|
||||
}
|
||||
registry.register(event);
|
||||
}
|
||||
server.ws.send("vitest:interceptor:register:result");
|
||||
});
|
||||
server.ws.on("vitest:interceptor:delete", (id) => {
|
||||
registry.delete(id);
|
||||
server.ws.send("vitest:interceptor:delete:result");
|
||||
});
|
||||
server.ws.on("vitest:interceptor:invalidate", () => {
|
||||
registry.clear();
|
||||
server.ws.send("vitest:interceptor:invalidate:result");
|
||||
});
|
||||
function getFactoryExports(url) {
|
||||
server.ws.send("vitest:interceptor:resolve", url);
|
||||
let timeout;
|
||||
return new Promise((resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(`Timeout while waiting for factory exports of ${url}`));
|
||||
}, 1e4);
|
||||
server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => {
|
||||
if (resolvedUrl === url) {
|
||||
clearTimeout(timeout);
|
||||
resolve(keys);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const VALID_ID_PREFIX = "/@id/";
|
||||
class ServerMockResolver {
|
||||
constructor(server, options = {}) {
|
||||
this.server = server;
|
||||
this.options = options;
|
||||
}
|
||||
async resolveMock(rawId, importer, options) {
|
||||
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;
|
||||
return {
|
||||
mockType: "manual",
|
||||
resolvedId: id,
|
||||
resolvedUrl,
|
||||
needsInterop
|
||||
};
|
||||
}
|
||||
if (options.mock === "spy") {
|
||||
return {
|
||||
mockType: "autospy",
|
||||
resolvedId: id,
|
||||
resolvedUrl
|
||||
};
|
||||
}
|
||||
const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external);
|
||||
return {
|
||||
mockType: redirectUrl === null ? "automock" : "redirect",
|
||||
redirectUrl,
|
||||
resolvedId: id,
|
||||
resolvedUrl
|
||||
};
|
||||
}
|
||||
invalidate(ids) {
|
||||
ids.forEach((id) => {
|
||||
const moduleGraph = this.server.moduleGraph;
|
||||
const module = moduleGraph.getModuleById(id);
|
||||
if (module) {
|
||||
module.transformResult = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
async resolveId(id, importer) {
|
||||
const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false });
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
return this.normalizeResolveIdToUrl(resolved);
|
||||
}
|
||||
normalizeResolveIdToUrl(resolved) {
|
||||
const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir));
|
||||
let url;
|
||||
// normalise the URL to be acceptable by the browser
|
||||
// https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103
|
||||
const root = this.server.config.root;
|
||||
if (resolved.id.startsWith(withTrailingSlash(root))) {
|
||||
url = resolved.id.slice(root.length);
|
||||
} else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) {
|
||||
url = join$1("/@fs/", resolved.id);
|
||||
} else {
|
||||
url = resolved.id;
|
||||
}
|
||||
if (url[0] !== "." && url[0] !== "/") {
|
||||
url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__");
|
||||
}
|
||||
return {
|
||||
id: resolved.id,
|
||||
url,
|
||||
optimized: isOptimized
|
||||
};
|
||||
}
|
||||
async resolveMockId(rawId, importer) {
|
||||
if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) {
|
||||
importer = join$1(this.server.config.root, importer);
|
||||
}
|
||||
const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false });
|
||||
return this.resolveModule(rawId, resolved);
|
||||
}
|
||||
resolveModule(rawId, resolved) {
|
||||
const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId;
|
||||
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
|
||||
return {
|
||||
id,
|
||||
fsPath: cleanUrl(id),
|
||||
external
|
||||
};
|
||||
}
|
||||
}
|
||||
function isModuleDirectory(config, path) {
|
||||
const moduleDirectories = config.moduleDirectories || ["/node_modules/"];
|
||||
return moduleDirectories.some((dir) => path.includes(dir));
|
||||
}
|
||||
const metadata = new WeakMap();
|
||||
function getViteDepsManifest(config) {
|
||||
if (metadata.has(config)) {
|
||||
return metadata.get(config);
|
||||
}
|
||||
const cacheDirPath = getDepsCacheDir(config);
|
||||
const metadataPath = resolve(cacheDirPath, "_metadata.json");
|
||||
if (!existsSync(metadataPath)) {
|
||||
return null;
|
||||
}
|
||||
const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8"));
|
||||
const newManifest = {};
|
||||
for (const name in optimized) {
|
||||
const dep = optimized[name];
|
||||
const file = resolve(cacheDirPath, dep.file);
|
||||
newManifest[file] = {
|
||||
hash: dep.fileHash,
|
||||
needsInterop: dep.needsInterop
|
||||
};
|
||||
}
|
||||
metadata.set(config, newManifest);
|
||||
return newManifest;
|
||||
}
|
||||
function getDepsCacheDir(config) {
|
||||
return resolve(config.cacheDir, "deps");
|
||||
}
|
||||
function withTrailingSlash(path) {
|
||||
if (path.at(-1) !== "/") {
|
||||
return `${path}/`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// this is an implementation for public usage
|
||||
// vitest doesn't use this plugin directly
|
||||
function mockerPlugin(options = {}) {
|
||||
let server;
|
||||
const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url)));
|
||||
return [
|
||||
{
|
||||
name: "vitest:mocker:ws-rpc",
|
||||
config(_, { command }) {
|
||||
if (command !== "serve") {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
server: { preTransformRequests: false },
|
||||
optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] }
|
||||
};
|
||||
},
|
||||
configureServer(server_) {
|
||||
server = server_;
|
||||
const mockResolver = new ServerMockResolver(server);
|
||||
server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => {
|
||||
const resolved = await mockResolver.resolveId(id, importer);
|
||||
server.ws.send("vitest:mocks:resolvedId:result", resolved);
|
||||
});
|
||||
server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => {
|
||||
const resolved = await mockResolver.resolveMock(id, importer, options);
|
||||
server.ws.send("vitest:mocks:resolveMock:result", resolved);
|
||||
});
|
||||
server.ws.on("vitest:mocks:invalidate", async ({ ids }) => {
|
||||
mockResolver.invalidate(ids);
|
||||
server.ws.send("vitest:mocks:invalidate:result");
|
||||
});
|
||||
},
|
||||
async load(id) {
|
||||
if (id !== registerPath) {
|
||||
return;
|
||||
}
|
||||
if (!server) {
|
||||
// mocker doesn't work during build
|
||||
return "export {}";
|
||||
}
|
||||
const content = await readFile(registerPath, "utf-8");
|
||||
const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root));
|
||||
return result;
|
||||
}
|
||||
},
|
||||
hoistMocksPlugin(options.hoistMocks),
|
||||
interceptorPlugin(options),
|
||||
automockPlugin(options),
|
||||
dynamicImportPlugin(options)
|
||||
];
|
||||
}
|
||||
|
||||
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
3
node_modules/@vitest/mocker/dist/redirect.d.ts
generated
vendored
Normal file
3
node_modules/@vitest/mocker/dist/redirect.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare function findMockRedirect(root: string, mockPath: string, external: string | null): string | null;
|
||||
|
||||
export { findMockRedirect };
|
||||
79
node_modules/@vitest/mocker/dist/redirect.js
generated
vendored
Normal file
79
node_modules/@vitest/mocker/dist/redirect.js
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import fs from 'node:fs';
|
||||
import nodeModule 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;
|
||||
function findMockRedirect(root, mockPath, external) {
|
||||
const path = external || mockPath;
|
||||
// it's a node_module alias
|
||||
// all mocks should be inside <root>/__mocks__
|
||||
if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
|
||||
const mockDirname = dirname(path);
|
||||
const mockFolder = join(root, "__mocks__", mockDirname);
|
||||
if (!existsSync(mockFolder)) {
|
||||
return null;
|
||||
}
|
||||
const baseOriginal = basename(path);
|
||||
function findFile(mockFolder, baseOriginal) {
|
||||
const files = readdirSync(mockFolder);
|
||||
for (const file of files) {
|
||||
const baseFile = basename(file, extname(file));
|
||||
if (baseFile === baseOriginal) {
|
||||
const path = resolve(mockFolder, file);
|
||||
// if the same name, return the file
|
||||
if (statSync(path).isFile()) {
|
||||
return path;
|
||||
} else {
|
||||
// find folder/index.{js,ts}
|
||||
const indexFile = findFile(path, "index");
|
||||
if (indexFile) {
|
||||
return indexFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return findFile(mockFolder, baseOriginal);
|
||||
}
|
||||
const dir = dirname(path);
|
||||
const baseId = basename(path);
|
||||
const fullPath = resolve(dir, "__mocks__", baseId);
|
||||
return existsSync(fullPath) ? fullPath : null;
|
||||
}
|
||||
const builtins = new Set([
|
||||
...nodeModule.builtinModules,
|
||||
"assert/strict",
|
||||
"diagnostics_channel",
|
||||
"dns/promises",
|
||||
"fs/promises",
|
||||
"path/posix",
|
||||
"path/win32",
|
||||
"readline/promises",
|
||||
"stream/consumers",
|
||||
"stream/promises",
|
||||
"stream/web",
|
||||
"timers/promises",
|
||||
"util/types",
|
||||
"wasi"
|
||||
]);
|
||||
// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
|
||||
const prefixedBuiltins = new Set([
|
||||
"node:sea",
|
||||
"node:sqlite",
|
||||
"node:test",
|
||||
"node:test/reporters"
|
||||
]);
|
||||
const NODE_BUILTIN_NAMESPACE = "node:";
|
||||
function isNodeBuiltin(id) {
|
||||
// Added in v18.6.0
|
||||
if (nodeModule.isBuiltin) {
|
||||
return nodeModule.isBuiltin(id);
|
||||
}
|
||||
if (prefixedBuiltins.has(id)) {
|
||||
return true;
|
||||
}
|
||||
return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id);
|
||||
}
|
||||
|
||||
export { findMockRedirect };
|
||||
9
node_modules/@vitest/mocker/dist/register.d.ts
generated
vendored
Normal file
9
node_modules/@vitest/mocker/dist/register.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js';
|
||||
import '@vitest/spy';
|
||||
import './types.d-B8CCKmHt.js';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
|
||||
declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints;
|
||||
declare function registerNativeFactoryResolver(mocker: ModuleMocker): void;
|
||||
|
||||
export { registerModuleMocker, registerNativeFactoryResolver };
|
||||
41
node_modules/@vitest/mocker/dist/register.js
generated
vendored
Normal file
41
node_modules/@vitest/mocker/dist/register.js
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
import { createMockInstance } from '@vitest/spy';
|
||||
import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
function registerModuleMocker(interceptor) {
|
||||
const mocker = new ModuleMocker(interceptor(__VITEST_GLOBAL_THIS_ACCESSOR__), {
|
||||
resolveId(id, importer) {
|
||||
return rpc("vitest:mocks:resolveId", {
|
||||
id,
|
||||
importer
|
||||
});
|
||||
},
|
||||
resolveMock(id, importer, options) {
|
||||
return rpc("vitest:mocks:resolveMock", {
|
||||
id,
|
||||
importer,
|
||||
options
|
||||
});
|
||||
},
|
||||
async invalidate(ids) {
|
||||
return rpc("vitest:mocks:invalidate", { ids });
|
||||
}
|
||||
}, createMockInstance, { root: __VITEST_MOCKER_ROOT__ });
|
||||
globalThis[__VITEST_GLOBAL_THIS_ACCESSOR__] = mocker;
|
||||
registerNativeFactoryResolver(mocker);
|
||||
return createCompilerHints({ globalThisKey: __VITEST_GLOBAL_THIS_ACCESSOR__ });
|
||||
}
|
||||
function registerNativeFactoryResolver(mocker) {
|
||||
hot.on("vitest:interceptor:resolve", async (url) => {
|
||||
const exports$1 = await mocker.resolveFactoryModule(url);
|
||||
const keys = Object.keys(exports$1);
|
||||
hot.send("vitest:interceptor:resolved", {
|
||||
url,
|
||||
keys
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export { registerModuleMocker, registerNativeFactoryResolver };
|
||||
107
node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts
generated
vendored
Normal file
107
node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
declare class MockerRegistry {
|
||||
private readonly registryByUrl;
|
||||
private readonly registryById;
|
||||
clear(): void;
|
||||
keys(): IterableIterator<string>;
|
||||
add(mock: MockedModule): void;
|
||||
register(json: MockedModuleSerialized): MockedModule;
|
||||
register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule;
|
||||
register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule;
|
||||
register(type: "automock", raw: string, id: string, url: string): AutomockedModule;
|
||||
register(type: "autospy", id: string, raw: string, url: string): AutospiedModule;
|
||||
delete(id: string): void;
|
||||
deleteById(id: string): void;
|
||||
get(id: string): MockedModule | undefined;
|
||||
getById(id: string): MockedModule | undefined;
|
||||
has(id: string): boolean;
|
||||
}
|
||||
type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule;
|
||||
type MockedModuleType = "automock" | "autospy" | "manual" | "redirect";
|
||||
type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized;
|
||||
declare class AutomockedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "automock";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutomockedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutomockedModuleSerialized;
|
||||
}
|
||||
interface AutomockedModuleSerialized {
|
||||
type: "automock";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class AutospiedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "autospy";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutospiedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutospiedModuleSerialized;
|
||||
}
|
||||
interface AutospiedModuleSerialized {
|
||||
type: "autospy";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class RedirectedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
redirect: string;
|
||||
readonly type = "redirect";
|
||||
constructor(raw: string, id: string, url: string, redirect: string);
|
||||
static fromJSON(data: RedirectedModuleSerialized): RedirectedModule;
|
||||
toJSON(): RedirectedModuleSerialized;
|
||||
}
|
||||
interface RedirectedModuleSerialized {
|
||||
type: "redirect";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
redirect: string;
|
||||
}
|
||||
declare class ManualMockedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
factory: () => any;
|
||||
cache: Record<string | symbol, any> | undefined;
|
||||
readonly type = "manual";
|
||||
constructor(raw: string, id: string, url: string, factory: () => any);
|
||||
resolve(): Promise<Record<string | symbol, any>>;
|
||||
static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule;
|
||||
toJSON(): ManualMockedModuleSerialized;
|
||||
}
|
||||
interface ManualMockedModuleSerialized {
|
||||
type: "manual";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
}
|
||||
|
||||
type Awaitable<T> = T | PromiseLike<T>;
|
||||
type ModuleMockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Awaitable<Partial<M>>;
|
||||
type ModuleMockFactory = () => any;
|
||||
interface ModuleMockOptions {
|
||||
spy?: boolean;
|
||||
}
|
||||
interface ServerMockResolution {
|
||||
mockType: "manual" | "redirect" | "automock" | "autospy";
|
||||
resolvedId: string;
|
||||
resolvedUrl: string;
|
||||
needsInterop?: boolean;
|
||||
redirectUrl?: string | null;
|
||||
}
|
||||
interface ServerIdResolution {
|
||||
id: string;
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
|
||||
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 };
|
||||
86
node_modules/@vitest/mocker/package.json
generated
vendored
Normal file
86
node_modules/@vitest/mocker/package.json
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"name": "@vitest/mocker",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Vitest module mocker implementation",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/mocker"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./node": {
|
||||
"types": "./dist/node.d.ts",
|
||||
"default": "./dist/node.js"
|
||||
},
|
||||
"./browser": {
|
||||
"types": "./dist/browser.d.ts",
|
||||
"default": "./dist/browser.js"
|
||||
},
|
||||
"./redirect": {
|
||||
"types": "./dist/redirect.d.ts",
|
||||
"default": "./dist/redirect.js"
|
||||
},
|
||||
"./automock": {
|
||||
"types": "./dist/automock.d.ts",
|
||||
"default": "./dist/automock.js"
|
||||
},
|
||||
"./register": {
|
||||
"types": "./dist/register.d.ts",
|
||||
"default": "./dist/register.js"
|
||||
},
|
||||
"./auto-register": {
|
||||
"types": "./dist/register.d.ts",
|
||||
"default": "./dist/register.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9",
|
||||
"vite": "^6.0.0 || ^7.0.0-0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^0.30.21",
|
||||
"@vitest/spy": "4.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/estree": "^1.0.8",
|
||||
"acorn-walk": "^8.3.4",
|
||||
"msw": "^2.12.3",
|
||||
"pathe": "^2.0.3",
|
||||
"vite": "^6.3.5",
|
||||
"@vitest/spy": "4.0.15",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user