@farming-labs/theme 0.0.26 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +1 -26
  2. package/dist/ai-search-dialog.mjs +1 -1
  3. package/dist/code-block-copy-wrapper.d.mts +1 -1
  4. package/dist/docs-layout.d.mts +1 -1
  5. package/dist/docs-layout.mjs +4 -4
  6. package/dist/docs-page-client.mjs +2 -2
  7. package/dist/index.mjs +1 -1
  8. package/dist/mdx.d.mts +1 -1
  9. package/dist/mdx.mjs +1 -1
  10. package/dist/page-actions.mjs +1 -1
  11. package/package.json +2 -2
  12. package/dist/get-app-dir.d.mts +0 -9
  13. package/dist/get-app-dir.test.d.mts +0 -1
  14. package/dist/get-app-dir.test.mjs +0 -41
  15. package/dist/node_modules/.pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs +0 -77
  16. package/dist/node_modules/.pnpm/@vitest_expect@3.2.4/node_modules/@vitest/expect/dist/index.mjs +0 -1356
  17. package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.mjs +0 -1119
  18. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.mjs +0 -1091
  19. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.mjs +0 -4
  20. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/utils.mjs +0 -3
  21. package/dist/node_modules/.pnpm/@vitest_snapshot@3.2.4/node_modules/@vitest/snapshot/dist/index.mjs +0 -1821
  22. package/dist/node_modules/.pnpm/@vitest_spy@3.2.4/node_modules/@vitest/spy/dist/index.mjs +0 -171
  23. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.mjs +0 -124
  24. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/diff.mjs +0 -1334
  25. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/error.mjs +0 -105
  26. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.mjs +0 -118
  27. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.mjs +0 -455
  28. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.mjs +0 -168
  29. package/dist/node_modules/.pnpm/chai@5.3.3/node_modules/chai/index.mjs +0 -3087
  30. package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.mjs +0 -384
  31. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.mjs +0 -11
  32. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.mjs +0 -16
  33. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.mjs +0 -11
  34. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.mjs +0 -15
  35. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.mjs +0 -13
  36. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.mjs +0 -34
  37. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.mjs +0 -12
  38. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.mjs +0 -122
  39. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.mjs +0 -39
  40. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.mjs +0 -99
  41. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.mjs +0 -25
  42. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.mjs +0 -14
  43. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.mjs +0 -21
  44. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.mjs +0 -5
  45. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.mjs +0 -12
  46. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.mjs +0 -18
  47. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.mjs +0 -25
  48. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.mjs +0 -8
  49. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.mjs +0 -30
  50. package/dist/node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs +0 -939
  51. package/dist/node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs +0 -81
  52. package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs +0 -51
  53. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.mjs +0 -81
  54. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.mjs +0 -9
  55. package/dist/node_modules/.pnpm/tinyspy@4.0.4/node_modules/tinyspy/dist/index.mjs +0 -125
  56. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/_commonjsHelpers.BFTU3MAI.mjs +0 -8
  57. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.mjs +0 -50
  58. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/utils.XdZDrNZV.mjs +0 -48
  59. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/vi.bdSIJ99Y.mjs +0 -2613
  60. package/dist/serialize-icon.d.mts +0 -4
@@ -1,2613 +0,0 @@
1
- import { assertTypes, createSimpleStackTrace } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.mjs";
2
- import { getSafeTimers } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.mjs";
3
- import { fn, isMockFunction, mocks, spyOn } from "../../../../../@vitest_spy@3.2.4/node_modules/@vitest/spy/dist/index.mjs";
4
- import { Assertion, assert, expect, use, utils_exports } from "../../../../../chai@5.3.3/node_modules/chai/index.mjs";
5
- import { ASYMMETRIC_MATCHERS_OBJECT, GLOBAL_EXPECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, addCustomEqualityTesters, customMatchers, equals, getState, iterableEquality, setState, subsetEquality } from "../../../../../@vitest_expect@3.2.4/node_modules/@vitest/expect/dist/index.mjs";
6
- import { parseSingleStack } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.mjs";
7
- import { getCurrentTest, getNames, getTestName } from "../../../../../@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.mjs";
8
- import "../../../../../@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.mjs";
9
- import "../../../../../@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/utils.mjs";
10
- import { getCurrentEnvironment, getWorkerState, isChildProcess, resetModules, waitForImportsToResolve } from "./utils.XdZDrNZV.mjs";
11
- import { commonjsGlobal, getDefaultExportFromCjs } from "./_commonjsHelpers.BFTU3MAI.mjs";
12
- import { SnapshotClient, addSerializer, stripSnapshotIndentation } from "../../../../../@vitest_snapshot@3.2.4/node_modules/@vitest/snapshot/dist/index.mjs";
13
- import { RealDate, mockDate, resetDate } from "./date.Bq6ZW5rf.mjs";
14
-
15
- //#region ../../node_modules/.pnpm/vitest@3.2.4_@types+debug@4.1.12_@types+node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/vi.bdSIJ99Y.js
16
- const unsupported = [
17
- "matchSnapshot",
18
- "toMatchSnapshot",
19
- "toMatchInlineSnapshot",
20
- "toThrowErrorMatchingSnapshot",
21
- "toThrowErrorMatchingInlineSnapshot",
22
- "throws",
23
- "Throw",
24
- "throw",
25
- "toThrow",
26
- "toThrowError"
27
- ];
28
- function createExpectPoll(expect) {
29
- return function poll(fn, options = {}) {
30
- const defaults = getWorkerState().config.expect?.poll ?? {};
31
- const { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options;
32
- const assertion = expect(null, message).withContext({ poll: true });
33
- fn = fn.bind(assertion);
34
- const test = utils_exports.flag(assertion, "vitest-test");
35
- if (!test) throw new Error("expect.poll() must be called inside a test");
36
- const proxy = new Proxy(assertion, { get(target, key, receiver) {
37
- const assertionFunction = Reflect.get(target, key, receiver);
38
- if (typeof assertionFunction !== "function") return assertionFunction instanceof Assertion ? proxy : assertionFunction;
39
- if (key === "assert") return assertionFunction;
40
- if (typeof key === "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
41
- return function(...args) {
42
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
43
- const promise = () => new Promise((resolve, reject) => {
44
- let intervalId;
45
- let timeoutId;
46
- let lastError;
47
- const { setTimeout, clearTimeout } = getSafeTimers();
48
- const check = async () => {
49
- try {
50
- utils_exports.flag(assertion, "_name", key);
51
- const obj = await fn();
52
- utils_exports.flag(assertion, "object", obj);
53
- resolve(await assertionFunction.call(assertion, ...args));
54
- clearTimeout(intervalId);
55
- clearTimeout(timeoutId);
56
- } catch (err) {
57
- lastError = err;
58
- if (!utils_exports.flag(assertion, "_isLastPollAttempt")) intervalId = setTimeout(check, interval);
59
- }
60
- };
61
- timeoutId = setTimeout(() => {
62
- clearTimeout(intervalId);
63
- utils_exports.flag(assertion, "_isLastPollAttempt", true);
64
- const rejectWithCause = (cause) => {
65
- reject(copyStackTrace$1(new Error("Matcher did not succeed in time.", { cause }), STACK_TRACE_ERROR));
66
- };
67
- check().then(() => rejectWithCause(lastError)).catch((e) => rejectWithCause(e));
68
- }, timeout);
69
- check();
70
- });
71
- let awaited = false;
72
- test.onFinished ??= [];
73
- test.onFinished.push(() => {
74
- if (!awaited) {
75
- const negated = utils_exports.flag(assertion, "negate") ? "not." : "";
76
- const assertionString = `expect.${utils_exports.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`;
77
- throw copyStackTrace$1(/* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`), STACK_TRACE_ERROR);
78
- }
79
- });
80
- let resultPromise;
81
- return {
82
- then(onFulfilled, onRejected) {
83
- awaited = true;
84
- return (resultPromise ||= promise()).then(onFulfilled, onRejected);
85
- },
86
- catch(onRejected) {
87
- return (resultPromise ||= promise()).catch(onRejected);
88
- },
89
- finally(onFinally) {
90
- return (resultPromise ||= promise()).finally(onFinally);
91
- },
92
- [Symbol.toStringTag]: "Promise"
93
- };
94
- };
95
- } });
96
- return proxy;
97
- };
98
- }
99
- function copyStackTrace$1(target, source) {
100
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
101
- return target;
102
- }
103
- function commonjsRequire(path) {
104
- throw new Error("Could not dynamically require \"" + path + "\". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.");
105
- }
106
- var chaiSubset$1 = { exports: {} };
107
- var chaiSubset = chaiSubset$1.exports;
108
- var hasRequiredChaiSubset;
109
- function requireChaiSubset() {
110
- if (hasRequiredChaiSubset) return chaiSubset$1.exports;
111
- hasRequiredChaiSubset = 1;
112
- (function(module, exports) {
113
- (function() {
114
- (function(chaiSubset) {
115
- if (typeof commonjsRequire === "function" && true) return module.exports = chaiSubset;
116
- else return chai.use(chaiSubset);
117
- })(function(chai, utils) {
118
- var Assertion = chai.Assertion;
119
- var assertionPrototype = Assertion.prototype;
120
- Assertion.addMethod("containSubset", function(expected) {
121
- var actual = utils.flag(this, "object");
122
- var showDiff = chai.config.showDiff;
123
- assertionPrototype.assert.call(this, compare(expected, actual), "expected #{act} to contain subset #{exp}", "expected #{act} to not contain subset #{exp}", expected, actual, showDiff);
124
- });
125
- chai.assert.containSubset = function(val, exp, msg) {
126
- new chai.Assertion(val, msg).to.be.containSubset(exp);
127
- };
128
- function compare(expected, actual) {
129
- if (expected === actual) return true;
130
- if (typeof actual !== typeof expected) return false;
131
- if (typeof expected !== "object" || expected === null) return expected === actual;
132
- if (!!expected && !actual) return false;
133
- if (Array.isArray(expected)) {
134
- if (typeof actual.length !== "number") return false;
135
- var aa = Array.prototype.slice.call(actual);
136
- return expected.every(function(exp) {
137
- return aa.some(function(act) {
138
- return compare(exp, act);
139
- });
140
- });
141
- }
142
- if (expected instanceof Date) if (actual instanceof Date) return expected.getTime() === actual.getTime();
143
- else return false;
144
- return Object.keys(expected).every(function(key) {
145
- var eo = expected[key];
146
- var ao = actual[key];
147
- if (typeof eo === "object" && eo !== null && ao !== null) return compare(eo, ao);
148
- if (typeof eo === "function") return eo(ao);
149
- return ao === eo;
150
- });
151
- }
152
- });
153
- }).call(chaiSubset);
154
- })(chaiSubset$1);
155
- return chaiSubset$1.exports;
156
- }
157
- var Subset = /* @__PURE__ */ getDefaultExportFromCjs(requireChaiSubset());
158
- function createAssertionMessage(util, assertion, hasArgs) {
159
- const not = util.flag(assertion, "negate") ? "not." : "";
160
- const name = `${util.flag(assertion, "_name")}(expected)`;
161
- const promiseName = util.flag(assertion, "promise");
162
- return `expect(actual)${promiseName ? `.${promiseName}` : ""}.${not}${name}`;
163
- }
164
- function recordAsyncExpect(_test, promise, assertion, error) {
165
- const test = _test;
166
- if (test && promise instanceof Promise) {
167
- promise = promise.finally(() => {
168
- if (!test.promises) return;
169
- const index = test.promises.indexOf(promise);
170
- if (index !== -1) test.promises.splice(index, 1);
171
- });
172
- if (!test.promises) test.promises = [];
173
- test.promises.push(promise);
174
- let resolved = false;
175
- test.onFinished ??= [];
176
- test.onFinished.push(() => {
177
- if (!resolved) {
178
- const stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
179
- console.warn([
180
- `Promise returned by \`${assertion}\` was not awaited. `,
181
- "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
182
- "Please remember to await the assertion.\n",
183
- stack
184
- ].join(""));
185
- }
186
- });
187
- return {
188
- then(onFulfilled, onRejected) {
189
- resolved = true;
190
- return promise.then(onFulfilled, onRejected);
191
- },
192
- catch(onRejected) {
193
- return promise.catch(onRejected);
194
- },
195
- finally(onFinally) {
196
- return promise.finally(onFinally);
197
- },
198
- [Symbol.toStringTag]: "Promise"
199
- };
200
- }
201
- return promise;
202
- }
203
- let _client;
204
- function getSnapshotClient() {
205
- if (!_client) _client = new SnapshotClient({ isEqual: (received, expected) => {
206
- return equals(received, expected, [iterableEquality, subsetEquality]);
207
- } });
208
- return _client;
209
- }
210
- function getError(expected, promise) {
211
- if (typeof expected !== "function") {
212
- if (!promise) throw new Error(`expected must be a function, received ${typeof expected}`);
213
- return expected;
214
- }
215
- try {
216
- expected();
217
- } catch (e) {
218
- return e;
219
- }
220
- throw new Error("snapshot function didn't throw");
221
- }
222
- function getTestNames(test) {
223
- return {
224
- filepath: test.file.filepath,
225
- name: getNames(test).slice(1).join(" > "),
226
- testId: test.id
227
- };
228
- }
229
- const SnapshotPlugin = (chai, utils) => {
230
- function getTest(assertionName, obj) {
231
- const test = utils.flag(obj, "vitest-test");
232
- if (!test) throw new Error(`'${assertionName}' cannot be used without test context`);
233
- return test;
234
- }
235
- for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
236
- utils.flag(this, "_name", key);
237
- if (utils.flag(this, "negate")) throw new Error(`${key} cannot be used with "not"`);
238
- const expected = utils.flag(this, "object");
239
- const test = getTest(key, this);
240
- if (typeof properties === "string" && typeof message === "undefined") {
241
- message = properties;
242
- properties = void 0;
243
- }
244
- const errorMessage = utils.flag(this, "message");
245
- getSnapshotClient().assert({
246
- received: expected,
247
- message,
248
- isInline: false,
249
- properties,
250
- errorMessage,
251
- ...getTestNames(test)
252
- });
253
- });
254
- utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
255
- utils.flag(this, "_name", "toMatchFileSnapshot");
256
- if (utils.flag(this, "negate")) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
257
- const error = /* @__PURE__ */ new Error("resolves");
258
- const expected = utils.flag(this, "object");
259
- const test = getTest("toMatchFileSnapshot", this);
260
- const errorMessage = utils.flag(this, "message");
261
- return recordAsyncExpect(test, getSnapshotClient().assertRaw({
262
- received: expected,
263
- message,
264
- isInline: false,
265
- rawSnapshot: { file },
266
- errorMessage,
267
- ...getTestNames(test)
268
- }), createAssertionMessage(utils, this), error);
269
- });
270
- utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
271
- utils.flag(this, "_name", "toMatchInlineSnapshot");
272
- if (utils.flag(this, "negate")) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
273
- const test = getTest("toMatchInlineSnapshot", this);
274
- if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
275
- const expected = utils.flag(this, "object");
276
- const error = utils.flag(this, "error");
277
- if (typeof properties === "string") {
278
- message = inlineSnapshot;
279
- inlineSnapshot = properties;
280
- properties = void 0;
281
- }
282
- if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
283
- const errorMessage = utils.flag(this, "message");
284
- getSnapshotClient().assert({
285
- received: expected,
286
- message,
287
- isInline: true,
288
- properties,
289
- inlineSnapshot,
290
- error,
291
- errorMessage,
292
- ...getTestNames(test)
293
- });
294
- });
295
- utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
296
- utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
297
- if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
298
- const expected = utils.flag(this, "object");
299
- const test = getTest("toThrowErrorMatchingSnapshot", this);
300
- const promise = utils.flag(this, "promise");
301
- const errorMessage = utils.flag(this, "message");
302
- getSnapshotClient().assert({
303
- received: getError(expected, promise),
304
- message,
305
- errorMessage,
306
- ...getTestNames(test)
307
- });
308
- });
309
- utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
310
- if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
311
- const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
312
- if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
313
- const expected = utils.flag(this, "object");
314
- const error = utils.flag(this, "error");
315
- const promise = utils.flag(this, "promise");
316
- const errorMessage = utils.flag(this, "message");
317
- if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
318
- getSnapshotClient().assert({
319
- received: getError(expected, promise),
320
- message,
321
- inlineSnapshot,
322
- isInline: true,
323
- error,
324
- errorMessage,
325
- ...getTestNames(test)
326
- });
327
- });
328
- utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
329
- };
330
- use(JestExtend);
331
- use(JestChaiExpect);
332
- use(Subset);
333
- use(SnapshotPlugin);
334
- use(JestAsymmetricMatchers);
335
- function createExpect(test) {
336
- const expect$1 = (value, message) => {
337
- const { assertionCalls } = getState(expect$1);
338
- setState({ assertionCalls: assertionCalls + 1 }, expect$1);
339
- const assert = expect(value, message);
340
- const _test = test || getCurrentTest();
341
- if (_test) return assert.withTest(_test);
342
- else return assert;
343
- };
344
- Object.assign(expect$1, expect);
345
- Object.assign(expect$1, globalThis[ASYMMETRIC_MATCHERS_OBJECT]);
346
- expect$1.getState = () => getState(expect$1);
347
- expect$1.setState = (state) => setState(state, expect$1);
348
- const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
349
- setState({
350
- ...globalState,
351
- assertionCalls: 0,
352
- isExpectingAssertions: false,
353
- isExpectingAssertionsError: null,
354
- expectedAssertionsNumber: null,
355
- expectedAssertionsNumberErrorGen: null,
356
- environment: getCurrentEnvironment(),
357
- get testPath() {
358
- return getWorkerState().filepath;
359
- },
360
- currentTestName: test ? getTestName(test) : globalState.currentTestName
361
- }, expect$1);
362
- expect$1.extend = (matchers) => expect.extend(expect$1, matchers);
363
- expect$1.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters);
364
- expect$1.soft = (...args) => {
365
- return expect$1(...args).withContext({ soft: true });
366
- };
367
- expect$1.poll = createExpectPoll(expect$1);
368
- expect$1.unreachable = (message) => {
369
- assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
370
- };
371
- function assertions(expected) {
372
- const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect$1.getState().assertionCalls}`);
373
- if (Error.captureStackTrace) Error.captureStackTrace(errorGen(), assertions);
374
- expect$1.setState({
375
- expectedAssertionsNumber: expected,
376
- expectedAssertionsNumberErrorGen: errorGen
377
- });
378
- }
379
- function hasAssertions() {
380
- const error = /* @__PURE__ */ new Error("expected any number of assertion, but got none");
381
- if (Error.captureStackTrace) Error.captureStackTrace(error, hasAssertions);
382
- expect$1.setState({
383
- isExpectingAssertions: true,
384
- isExpectingAssertionsError: error
385
- });
386
- }
387
- utils_exports.addMethod(expect$1, "assertions", assertions);
388
- utils_exports.addMethod(expect$1, "hasAssertions", hasAssertions);
389
- expect$1.extend(customMatchers);
390
- return expect$1;
391
- }
392
- const globalExpect = createExpect();
393
- Object.defineProperty(globalThis, GLOBAL_EXPECT, {
394
- value: globalExpect,
395
- writable: true,
396
- configurable: true
397
- });
398
- var fakeTimersSrc = {};
399
- var global;
400
- var hasRequiredGlobal;
401
- function requireGlobal() {
402
- if (hasRequiredGlobal) return global;
403
- hasRequiredGlobal = 1;
404
- /**
405
- * A reference to the global object
406
- * @type {object} globalObject
407
- */
408
- var globalObject;
409
- /* istanbul ignore else */
410
- if (typeof commonjsGlobal !== "undefined") globalObject = commonjsGlobal;
411
- else if (typeof window !== "undefined") globalObject = window;
412
- else globalObject = self;
413
- global = globalObject;
414
- return global;
415
- }
416
- var throwsOnProto_1;
417
- var hasRequiredThrowsOnProto;
418
- function requireThrowsOnProto() {
419
- if (hasRequiredThrowsOnProto) return throwsOnProto_1;
420
- hasRequiredThrowsOnProto = 1;
421
- /**
422
- * Is true when the environment causes an error to be thrown for accessing the
423
- * __proto__ property.
424
- * This is necessary in order to support `node --disable-proto=throw`.
425
- *
426
- * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
427
- * @type {boolean}
428
- */
429
- let throwsOnProto;
430
- try {
431
- ({}).__proto__;
432
- throwsOnProto = false;
433
- } catch (_) {
434
- /* istanbul ignore next */
435
- throwsOnProto = true;
436
- }
437
- throwsOnProto_1 = throwsOnProto;
438
- return throwsOnProto_1;
439
- }
440
- var copyPrototypeMethods;
441
- var hasRequiredCopyPrototypeMethods;
442
- function requireCopyPrototypeMethods() {
443
- if (hasRequiredCopyPrototypeMethods) return copyPrototypeMethods;
444
- hasRequiredCopyPrototypeMethods = 1;
445
- var call = Function.call;
446
- var throwsOnProto = requireThrowsOnProto();
447
- var disallowedProperties = [
448
- "size",
449
- "caller",
450
- "callee",
451
- "arguments"
452
- ];
453
- /* istanbul ignore next */
454
- if (throwsOnProto) disallowedProperties.push("__proto__");
455
- copyPrototypeMethods = function copyPrototypeMethods(prototype) {
456
- return Object.getOwnPropertyNames(prototype).reduce(function(result, name) {
457
- if (disallowedProperties.includes(name)) return result;
458
- if (typeof prototype[name] !== "function") return result;
459
- result[name] = call.bind(prototype[name]);
460
- return result;
461
- }, Object.create(null));
462
- };
463
- return copyPrototypeMethods;
464
- }
465
- var array;
466
- var hasRequiredArray;
467
- function requireArray() {
468
- if (hasRequiredArray) return array;
469
- hasRequiredArray = 1;
470
- array = requireCopyPrototypeMethods()(Array.prototype);
471
- return array;
472
- }
473
- var calledInOrder_1;
474
- var hasRequiredCalledInOrder;
475
- function requireCalledInOrder() {
476
- if (hasRequiredCalledInOrder) return calledInOrder_1;
477
- hasRequiredCalledInOrder = 1;
478
- var every = requireArray().every;
479
- /**
480
- * @private
481
- */
482
- function hasCallsLeft(callMap, spy) {
483
- if (callMap[spy.id] === void 0) callMap[spy.id] = 0;
484
- return callMap[spy.id] < spy.callCount;
485
- }
486
- /**
487
- * @private
488
- */
489
- function checkAdjacentCalls(callMap, spy, index, spies) {
490
- var calledBeforeNext = true;
491
- if (index !== spies.length - 1) calledBeforeNext = spy.calledBefore(spies[index + 1]);
492
- if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
493
- callMap[spy.id] += 1;
494
- return true;
495
- }
496
- return false;
497
- }
498
- /**
499
- * A Sinon proxy object (fake, spy, stub)
500
- * @typedef {object} SinonProxy
501
- * @property {Function} calledBefore - A method that determines if this proxy was called before another one
502
- * @property {string} id - Some id
503
- * @property {number} callCount - Number of times this proxy has been called
504
- */
505
- /**
506
- * Returns true when the spies have been called in the order they were supplied in
507
- * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
508
- * @returns {boolean} true when spies are called in order, false otherwise
509
- */
510
- function calledInOrder(spies) {
511
- return every(arguments.length > 1 ? arguments : spies, checkAdjacentCalls.bind(null, {}));
512
- }
513
- calledInOrder_1 = calledInOrder;
514
- return calledInOrder_1;
515
- }
516
- var className_1;
517
- var hasRequiredClassName;
518
- function requireClassName() {
519
- if (hasRequiredClassName) return className_1;
520
- hasRequiredClassName = 1;
521
- /**
522
- * Returns a display name for a value from a constructor
523
- * @param {object} value A value to examine
524
- * @returns {(string|null)} A string or null
525
- */
526
- function className(value) {
527
- return value.constructor && value.constructor.name || null;
528
- }
529
- className_1 = className;
530
- return className_1;
531
- }
532
- var deprecated = {};
533
- var hasRequiredDeprecated;
534
- function requireDeprecated() {
535
- if (hasRequiredDeprecated) return deprecated;
536
- hasRequiredDeprecated = 1;
537
- (function(exports) {
538
- /**
539
- * Returns a function that will invoke the supplied function and print a
540
- * deprecation warning to the console each time it is called.
541
- * @param {Function} func
542
- * @param {string} msg
543
- * @returns {Function}
544
- */
545
- exports.wrap = function(func, msg) {
546
- var wrapped = function() {
547
- exports.printWarning(msg);
548
- return func.apply(this, arguments);
549
- };
550
- if (func.prototype) wrapped.prototype = func.prototype;
551
- return wrapped;
552
- };
553
- /**
554
- * Returns a string which can be supplied to `wrap()` to notify the user that a
555
- * particular part of the sinon API has been deprecated.
556
- * @param {string} packageName
557
- * @param {string} funcName
558
- * @returns {string}
559
- */
560
- exports.defaultMsg = function(packageName, funcName) {
561
- return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
562
- };
563
- /**
564
- * Prints a warning on the console, when it exists
565
- * @param {string} msg
566
- * @returns {undefined}
567
- */
568
- exports.printWarning = function(msg) {
569
- /* istanbul ignore next */
570
- if (typeof process === "object" && process.emitWarning) process.emitWarning(msg);
571
- else if (console.info) console.info(msg);
572
- else console.log(msg);
573
- };
574
- })(deprecated);
575
- return deprecated;
576
- }
577
- var every;
578
- var hasRequiredEvery;
579
- function requireEvery() {
580
- if (hasRequiredEvery) return every;
581
- hasRequiredEvery = 1;
582
- /**
583
- * Returns true when fn returns true for all members of obj.
584
- * This is an every implementation that works for all iterables
585
- * @param {object} obj
586
- * @param {Function} fn
587
- * @returns {boolean}
588
- */
589
- every = function every(obj, fn) {
590
- var pass = true;
591
- try {
592
- obj.forEach(function() {
593
- if (!fn.apply(this, arguments)) throw new Error();
594
- });
595
- } catch (e) {
596
- pass = false;
597
- }
598
- return pass;
599
- };
600
- return every;
601
- }
602
- var functionName;
603
- var hasRequiredFunctionName;
604
- function requireFunctionName() {
605
- if (hasRequiredFunctionName) return functionName;
606
- hasRequiredFunctionName = 1;
607
- /**
608
- * Returns a display name for a function
609
- * @param {Function} func
610
- * @returns {string}
611
- */
612
- functionName = function functionName(func) {
613
- if (!func) return "";
614
- try {
615
- return func.displayName || func.name || (String(func).match(/function ([^\s(]+)/) || [])[1];
616
- } catch (e) {
617
- return "";
618
- }
619
- };
620
- return functionName;
621
- }
622
- var orderByFirstCall_1;
623
- var hasRequiredOrderByFirstCall;
624
- function requireOrderByFirstCall() {
625
- if (hasRequiredOrderByFirstCall) return orderByFirstCall_1;
626
- hasRequiredOrderByFirstCall = 1;
627
- var sort = requireArray().sort;
628
- var slice = requireArray().slice;
629
- /**
630
- * @private
631
- */
632
- function comparator(a, b) {
633
- var aCall = a.getCall(0);
634
- var bCall = b.getCall(0);
635
- return (aCall && aCall.callId || -1) < (bCall && bCall.callId || -1) ? -1 : 1;
636
- }
637
- /**
638
- * A Sinon proxy object (fake, spy, stub)
639
- * @typedef {object} SinonProxy
640
- * @property {Function} getCall - A method that can return the first call
641
- */
642
- /**
643
- * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
644
- * @param {SinonProxy[] | SinonProxy} spies
645
- * @returns {SinonProxy[]}
646
- */
647
- function orderByFirstCall(spies) {
648
- return sort(slice(spies), comparator);
649
- }
650
- orderByFirstCall_1 = orderByFirstCall;
651
- return orderByFirstCall_1;
652
- }
653
- var _function;
654
- var hasRequired_function;
655
- function require_function() {
656
- if (hasRequired_function) return _function;
657
- hasRequired_function = 1;
658
- _function = requireCopyPrototypeMethods()(Function.prototype);
659
- return _function;
660
- }
661
- var map;
662
- var hasRequiredMap;
663
- function requireMap() {
664
- if (hasRequiredMap) return map;
665
- hasRequiredMap = 1;
666
- map = requireCopyPrototypeMethods()(Map.prototype);
667
- return map;
668
- }
669
- var object;
670
- var hasRequiredObject;
671
- function requireObject() {
672
- if (hasRequiredObject) return object;
673
- hasRequiredObject = 1;
674
- object = requireCopyPrototypeMethods()(Object.prototype);
675
- return object;
676
- }
677
- var set;
678
- var hasRequiredSet;
679
- function requireSet() {
680
- if (hasRequiredSet) return set;
681
- hasRequiredSet = 1;
682
- set = requireCopyPrototypeMethods()(Set.prototype);
683
- return set;
684
- }
685
- var string;
686
- var hasRequiredString;
687
- function requireString() {
688
- if (hasRequiredString) return string;
689
- hasRequiredString = 1;
690
- string = requireCopyPrototypeMethods()(String.prototype);
691
- return string;
692
- }
693
- var prototypes;
694
- var hasRequiredPrototypes;
695
- function requirePrototypes() {
696
- if (hasRequiredPrototypes) return prototypes;
697
- hasRequiredPrototypes = 1;
698
- prototypes = {
699
- array: requireArray(),
700
- function: require_function(),
701
- map: requireMap(),
702
- object: requireObject(),
703
- set: requireSet(),
704
- string: requireString()
705
- };
706
- return prototypes;
707
- }
708
- var typeDetect$1 = { exports: {} };
709
- var typeDetect = typeDetect$1.exports;
710
- var hasRequiredTypeDetect;
711
- function requireTypeDetect() {
712
- if (hasRequiredTypeDetect) return typeDetect$1.exports;
713
- hasRequiredTypeDetect = 1;
714
- (function(module, exports) {
715
- (function(global, factory) {
716
- module.exports = factory();
717
- })(typeDetect, (function() {
718
- var promiseExists = typeof Promise === "function";
719
- var globalObject = typeof self === "object" ? self : commonjsGlobal;
720
- var symbolExists = typeof Symbol !== "undefined";
721
- var mapExists = typeof Map !== "undefined";
722
- var setExists = typeof Set !== "undefined";
723
- var weakMapExists = typeof WeakMap !== "undefined";
724
- var weakSetExists = typeof WeakSet !== "undefined";
725
- var dataViewExists = typeof DataView !== "undefined";
726
- var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== "undefined";
727
- var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== "undefined";
728
- var setEntriesExists = setExists && typeof Set.prototype.entries === "function";
729
- var mapEntriesExists = mapExists && typeof Map.prototype.entries === "function";
730
- var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Set()).entries());
731
- var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Map()).entries());
732
- var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === "function";
733
- var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
734
- var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === "function";
735
- var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(""[Symbol.iterator]());
736
- var toStringLeftSliceLength = 8;
737
- var toStringRightSliceLength = -1;
738
- /**
739
- * ### typeOf (obj)
740
- *
741
- * Uses `Object.prototype.toString` to determine the type of an object,
742
- * normalising behaviour across engine versions & well optimised.
743
- *
744
- * @param {Mixed} object
745
- * @return {String} object type
746
- * @api public
747
- */
748
- function typeDetect(obj) {
749
- var typeofObj = typeof obj;
750
- if (typeofObj !== "object") return typeofObj;
751
- if (obj === null) return "null";
752
- if (obj === globalObject) return "global";
753
- if (Array.isArray(obj) && (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))) return "Array";
754
- if (typeof window === "object" && window !== null) {
755
- if (typeof window.location === "object" && obj === window.location) return "Location";
756
- if (typeof window.document === "object" && obj === window.document) return "Document";
757
- if (typeof window.navigator === "object") {
758
- if (typeof window.navigator.mimeTypes === "object" && obj === window.navigator.mimeTypes) return "MimeTypeArray";
759
- if (typeof window.navigator.plugins === "object" && obj === window.navigator.plugins) return "PluginArray";
760
- }
761
- if ((typeof window.HTMLElement === "function" || typeof window.HTMLElement === "object") && obj instanceof window.HTMLElement) {
762
- if (obj.tagName === "BLOCKQUOTE") return "HTMLQuoteElement";
763
- if (obj.tagName === "TD") return "HTMLTableDataCellElement";
764
- if (obj.tagName === "TH") return "HTMLTableHeaderCellElement";
765
- }
766
- }
767
- var stringTag = symbolToStringTagExists && obj[Symbol.toStringTag];
768
- if (typeof stringTag === "string") return stringTag;
769
- var objPrototype = Object.getPrototypeOf(obj);
770
- if (objPrototype === RegExp.prototype) return "RegExp";
771
- if (objPrototype === Date.prototype) return "Date";
772
- if (promiseExists && objPrototype === Promise.prototype) return "Promise";
773
- if (setExists && objPrototype === Set.prototype) return "Set";
774
- if (mapExists && objPrototype === Map.prototype) return "Map";
775
- if (weakSetExists && objPrototype === WeakSet.prototype) return "WeakSet";
776
- if (weakMapExists && objPrototype === WeakMap.prototype) return "WeakMap";
777
- if (dataViewExists && objPrototype === DataView.prototype) return "DataView";
778
- if (mapExists && objPrototype === mapIteratorPrototype) return "Map Iterator";
779
- if (setExists && objPrototype === setIteratorPrototype) return "Set Iterator";
780
- if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) return "Array Iterator";
781
- if (stringIteratorExists && objPrototype === stringIteratorPrototype) return "String Iterator";
782
- if (objPrototype === null) return "Object";
783
- return Object.prototype.toString.call(obj).slice(toStringLeftSliceLength, toStringRightSliceLength);
784
- }
785
- return typeDetect;
786
- }));
787
- })(typeDetect$1);
788
- return typeDetect$1.exports;
789
- }
790
- var typeOf;
791
- var hasRequiredTypeOf;
792
- function requireTypeOf() {
793
- if (hasRequiredTypeOf) return typeOf;
794
- hasRequiredTypeOf = 1;
795
- var type = requireTypeDetect();
796
- /**
797
- * Returns the lower-case result of running type from type-detect on the value
798
- * @param {*} value
799
- * @returns {string}
800
- */
801
- typeOf = function typeOf(value) {
802
- return type(value).toLowerCase();
803
- };
804
- return typeOf;
805
- }
806
- var valueToString_1;
807
- var hasRequiredValueToString;
808
- function requireValueToString() {
809
- if (hasRequiredValueToString) return valueToString_1;
810
- hasRequiredValueToString = 1;
811
- /**
812
- * Returns a string representation of the value
813
- * @param {*} value
814
- * @returns {string}
815
- */
816
- function valueToString(value) {
817
- if (value && value.toString) return value.toString();
818
- return String(value);
819
- }
820
- valueToString_1 = valueToString;
821
- return valueToString_1;
822
- }
823
- var lib;
824
- var hasRequiredLib;
825
- function requireLib() {
826
- if (hasRequiredLib) return lib;
827
- hasRequiredLib = 1;
828
- lib = {
829
- global: requireGlobal(),
830
- calledInOrder: requireCalledInOrder(),
831
- className: requireClassName(),
832
- deprecated: requireDeprecated(),
833
- every: requireEvery(),
834
- functionName: requireFunctionName(),
835
- orderByFirstCall: requireOrderByFirstCall(),
836
- prototypes: requirePrototypes(),
837
- typeOf: requireTypeOf(),
838
- valueToString: requireValueToString()
839
- };
840
- return lib;
841
- }
842
- var hasRequiredFakeTimersSrc;
843
- function requireFakeTimersSrc() {
844
- if (hasRequiredFakeTimersSrc) return fakeTimersSrc;
845
- hasRequiredFakeTimersSrc = 1;
846
- const globalObject = requireLib().global;
847
- let timersModule, timersPromisesModule;
848
- if (typeof __vitest_required__ !== "undefined") {
849
- try {
850
- timersModule = __vitest_required__.timers;
851
- } catch (e) {}
852
- try {
853
- timersPromisesModule = __vitest_required__.timersPromises;
854
- } catch (e) {}
855
- }
856
- /**
857
- * @typedef {object} IdleDeadline
858
- * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
859
- * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
860
- */
861
- /**
862
- * Queues a function to be called during a browser's idle periods
863
- * @callback RequestIdleCallback
864
- * @param {function(IdleDeadline)} callback
865
- * @param {{timeout: number}} options - an options object
866
- * @returns {number} the id
867
- */
868
- /**
869
- * @callback NextTick
870
- * @param {VoidVarArgsFunc} callback - the callback to run
871
- * @param {...*} args - optional arguments to call the callback with
872
- * @returns {void}
873
- */
874
- /**
875
- * @callback SetImmediate
876
- * @param {VoidVarArgsFunc} callback - the callback to run
877
- * @param {...*} args - optional arguments to call the callback with
878
- * @returns {NodeImmediate}
879
- */
880
- /**
881
- * @callback VoidVarArgsFunc
882
- * @param {...*} callback - the callback to run
883
- * @returns {void}
884
- */
885
- /**
886
- * @typedef RequestAnimationFrame
887
- * @property {function(number):void} requestAnimationFrame
888
- * @returns {number} - the id
889
- */
890
- /**
891
- * @typedef Performance
892
- * @property {function(): number} now
893
- */
894
- /**
895
- * @typedef {object} Clock
896
- * @property {number} now - the current time
897
- * @property {Date} Date - the Date constructor
898
- * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
899
- * @property {RequestIdleCallback} requestIdleCallback
900
- * @property {function(number):void} cancelIdleCallback
901
- * @property {setTimeout} setTimeout
902
- * @property {clearTimeout} clearTimeout
903
- * @property {NextTick} nextTick
904
- * @property {queueMicrotask} queueMicrotask
905
- * @property {setInterval} setInterval
906
- * @property {clearInterval} clearInterval
907
- * @property {SetImmediate} setImmediate
908
- * @property {function(NodeImmediate):void} clearImmediate
909
- * @property {function():number} countTimers
910
- * @property {RequestAnimationFrame} requestAnimationFrame
911
- * @property {function(number):void} cancelAnimationFrame
912
- * @property {function():void} runMicrotasks
913
- * @property {function(string | number): number} tick
914
- * @property {function(string | number): Promise<number>} tickAsync
915
- * @property {function(): number} next
916
- * @property {function(): Promise<number>} nextAsync
917
- * @property {function(): number} runAll
918
- * @property {function(): number} runToFrame
919
- * @property {function(): Promise<number>} runAllAsync
920
- * @property {function(): number} runToLast
921
- * @property {function(): Promise<number>} runToLastAsync
922
- * @property {function(): void} reset
923
- * @property {function(number | Date): void} setSystemTime
924
- * @property {function(number): void} jump
925
- * @property {Performance} performance
926
- * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
927
- * @property {function(): void} uninstall Uninstall the clock.
928
- * @property {Function[]} methods - the methods that are faked
929
- * @property {boolean} [shouldClearNativeTimers] inherited from config
930
- * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
931
- * @property {{methodName:string, original:any}[] | undefined} timersPromisesModuleMethods
932
- * @property {Map<function(): void, AbortSignal>} abortListenerMap
933
- */
934
- /**
935
- * Configuration object for the `install` method.
936
- * @typedef {object} Config
937
- * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
938
- * @property {string[]} [toFake] names of the methods that should be faked.
939
- * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
940
- * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
941
- * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
942
- * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
943
- * @property {boolean} [ignoreMissingTimers] default is false, meaning asking to fake timers that are not present will throw an error
944
- */
945
- /**
946
- * The internal structure to describe a scheduled fake timer
947
- * @typedef {object} Timer
948
- * @property {Function} func
949
- * @property {*[]} args
950
- * @property {number} delay
951
- * @property {number} callAt
952
- * @property {number} createdAt
953
- * @property {boolean} immediate
954
- * @property {number} id
955
- * @property {Error} [error]
956
- */
957
- /**
958
- * A Node timer
959
- * @typedef {object} NodeImmediate
960
- * @property {function(): boolean} hasRef
961
- * @property {function(): NodeImmediate} ref
962
- * @property {function(): NodeImmediate} unref
963
- */
964
- /**
965
- * Mocks available features in the specified global namespace.
966
- * @param {*} _global Namespace to mock (e.g. `window`)
967
- * @returns {FakeTimers}
968
- */
969
- function withGlobal(_global) {
970
- const maxTimeout = Math.pow(2, 31) - 1;
971
- const idCounterStart = 0xe8d4a51000;
972
- const NOOP = function() {};
973
- const NOOP_ARRAY = function() {
974
- return [];
975
- };
976
- const isPresent = {};
977
- let timeoutResult, addTimerReturnsObject = false;
978
- if (_global.setTimeout) {
979
- isPresent.setTimeout = true;
980
- timeoutResult = _global.setTimeout(NOOP, 0);
981
- addTimerReturnsObject = typeof timeoutResult === "object";
982
- }
983
- isPresent.clearTimeout = Boolean(_global.clearTimeout);
984
- isPresent.setInterval = Boolean(_global.setInterval);
985
- isPresent.clearInterval = Boolean(_global.clearInterval);
986
- isPresent.hrtime = _global.process && typeof _global.process.hrtime === "function";
987
- isPresent.hrtimeBigint = isPresent.hrtime && typeof _global.process.hrtime.bigint === "function";
988
- isPresent.nextTick = _global.process && typeof _global.process.nextTick === "function";
989
- const utilPromisify = _global.process && _global.__vitest_required__ && _global.__vitest_required__.util.promisify;
990
- isPresent.performance = _global.performance && typeof _global.performance.now === "function";
991
- const hasPerformancePrototype = _global.Performance && (typeof _global.Performance).match(/^(function|object)$/);
992
- const hasPerformanceConstructorPrototype = _global.performance && _global.performance.constructor && _global.performance.constructor.prototype;
993
- isPresent.queueMicrotask = _global.hasOwnProperty("queueMicrotask");
994
- isPresent.requestAnimationFrame = _global.requestAnimationFrame && typeof _global.requestAnimationFrame === "function";
995
- isPresent.cancelAnimationFrame = _global.cancelAnimationFrame && typeof _global.cancelAnimationFrame === "function";
996
- isPresent.requestIdleCallback = _global.requestIdleCallback && typeof _global.requestIdleCallback === "function";
997
- isPresent.cancelIdleCallbackPresent = _global.cancelIdleCallback && typeof _global.cancelIdleCallback === "function";
998
- isPresent.setImmediate = _global.setImmediate && typeof _global.setImmediate === "function";
999
- isPresent.clearImmediate = _global.clearImmediate && typeof _global.clearImmediate === "function";
1000
- isPresent.Intl = _global.Intl && typeof _global.Intl === "object";
1001
- if (_global.clearTimeout) _global.clearTimeout(timeoutResult);
1002
- const NativeDate = _global.Date;
1003
- const NativeIntl = isPresent.Intl ? Object.defineProperties(Object.create(null), Object.getOwnPropertyDescriptors(_global.Intl)) : void 0;
1004
- let uniqueTimerId = idCounterStart;
1005
- if (NativeDate === void 0) throw new Error("The global scope doesn't have a `Date` object (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)");
1006
- isPresent.Date = true;
1007
- /**
1008
- * The PerformanceEntry object encapsulates a single performance metric
1009
- * that is part of the browser's performance timeline.
1010
- *
1011
- * This is an object returned by the `mark` and `measure` methods on the Performance prototype
1012
- */
1013
- class FakePerformanceEntry {
1014
- constructor(name, entryType, startTime, duration) {
1015
- this.name = name;
1016
- this.entryType = entryType;
1017
- this.startTime = startTime;
1018
- this.duration = duration;
1019
- }
1020
- toJSON() {
1021
- return JSON.stringify({ ...this });
1022
- }
1023
- }
1024
- /**
1025
- * @param {number} num
1026
- * @returns {boolean}
1027
- */
1028
- function isNumberFinite(num) {
1029
- if (Number.isFinite) return Number.isFinite(num);
1030
- return isFinite(num);
1031
- }
1032
- let isNearInfiniteLimit = false;
1033
- /**
1034
- * @param {Clock} clock
1035
- * @param {number} i
1036
- */
1037
- function checkIsNearInfiniteLimit(clock, i) {
1038
- if (clock.loopLimit && i === clock.loopLimit - 1) isNearInfiniteLimit = true;
1039
- }
1040
- /**
1041
- *
1042
- */
1043
- function resetIsNearInfiniteLimit() {
1044
- isNearInfiniteLimit = false;
1045
- }
1046
- /**
1047
- * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1048
- * number of milliseconds. This is used to support human-readable strings passed
1049
- * to clock.tick()
1050
- * @param {string} str
1051
- * @returns {number}
1052
- */
1053
- function parseTime(str) {
1054
- if (!str) return 0;
1055
- const strings = str.split(":");
1056
- const l = strings.length;
1057
- let i = l;
1058
- let ms = 0;
1059
- let parsed;
1060
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) throw new Error("tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits");
1061
- while (i--) {
1062
- parsed = parseInt(strings[i], 10);
1063
- if (parsed >= 60) throw new Error(`Invalid time ${str}`);
1064
- ms += parsed * Math.pow(60, l - i - 1);
1065
- }
1066
- return ms * 1e3;
1067
- }
1068
- /**
1069
- * Get the decimal part of the millisecond value as nanoseconds
1070
- * @param {number} msFloat the number of milliseconds
1071
- * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1072
- *
1073
- * Example: nanoRemainer(123.456789) -> 456789
1074
- */
1075
- function nanoRemainder(msFloat) {
1076
- const modulo = 1e6;
1077
- const remainder = msFloat * 1e6 % modulo;
1078
- const positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
1079
- return Math.floor(positiveRemainder);
1080
- }
1081
- /**
1082
- * Used to grok the `now` parameter to createClock.
1083
- * @param {Date|number} epoch the system time
1084
- * @returns {number}
1085
- */
1086
- function getEpoch(epoch) {
1087
- if (!epoch) return 0;
1088
- if (typeof epoch.getTime === "function") return epoch.getTime();
1089
- if (typeof epoch === "number") return epoch;
1090
- throw new TypeError("now should be milliseconds since UNIX epoch");
1091
- }
1092
- /**
1093
- * @param {number} from
1094
- * @param {number} to
1095
- * @param {Timer} timer
1096
- * @returns {boolean}
1097
- */
1098
- function inRange(from, to, timer) {
1099
- return timer && timer.callAt >= from && timer.callAt <= to;
1100
- }
1101
- /**
1102
- * @param {Clock} clock
1103
- * @param {Timer} job
1104
- */
1105
- function getInfiniteLoopError(clock, job) {
1106
- const infiniteLoopError = /* @__PURE__ */ new Error(`Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`);
1107
- if (!job.error) return infiniteLoopError;
1108
- const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1109
- let clockMethodPattern = new RegExp(String(Object.keys(clock).join("|")));
1110
- if (addTimerReturnsObject) clockMethodPattern = new RegExp(`\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`);
1111
- let matchedLineIndex = -1;
1112
- job.error.stack.split("\n").some(function(line, i) {
1113
- /* istanbul ignore if */
1114
- if (line.match(computedTargetPattern)) {
1115
- matchedLineIndex = i;
1116
- return true;
1117
- }
1118
- if (line.match(clockMethodPattern)) {
1119
- matchedLineIndex = i;
1120
- return false;
1121
- }
1122
- return matchedLineIndex >= 0;
1123
- });
1124
- const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${job.func.name || "anonymous"}\n${job.error.stack.split("\n").slice(matchedLineIndex + 1).join("\n")}`;
1125
- try {
1126
- Object.defineProperty(infiniteLoopError, "stack", { value: stack });
1127
- } catch (e) {}
1128
- return infiniteLoopError;
1129
- }
1130
- function createDate() {
1131
- class ClockDate extends NativeDate {
1132
- /**
1133
- * @param {number} year
1134
- * @param {number} month
1135
- * @param {number} date
1136
- * @param {number} hour
1137
- * @param {number} minute
1138
- * @param {number} second
1139
- * @param {number} ms
1140
- * @returns void
1141
- */
1142
- constructor(year, month, date, hour, minute, second, ms) {
1143
- if (arguments.length === 0) super(ClockDate.clock.now);
1144
- else super(...arguments);
1145
- Object.defineProperty(this, "constructor", {
1146
- value: NativeDate,
1147
- enumerable: false
1148
- });
1149
- }
1150
- static [Symbol.hasInstance](instance) {
1151
- return instance instanceof NativeDate;
1152
- }
1153
- }
1154
- ClockDate.isFake = true;
1155
- if (NativeDate.now) ClockDate.now = function now() {
1156
- return ClockDate.clock.now;
1157
- };
1158
- if (NativeDate.toSource) ClockDate.toSource = function toSource() {
1159
- return NativeDate.toSource();
1160
- };
1161
- ClockDate.toString = function toString() {
1162
- return NativeDate.toString();
1163
- };
1164
- return new Proxy(ClockDate, { apply() {
1165
- if (this instanceof ClockDate) throw new TypeError("A Proxy should only capture `new` calls with the `construct` handler. This is not supposed to be possible, so check the logic.");
1166
- return new NativeDate(ClockDate.clock.now).toString();
1167
- } });
1168
- }
1169
- /**
1170
- * Mirror Intl by default on our fake implementation
1171
- *
1172
- * Most of the properties are the original native ones,
1173
- * but we need to take control of those that have a
1174
- * dependency on the current clock.
1175
- * @returns {object} the partly fake Intl implementation
1176
- */
1177
- function createIntl() {
1178
- const ClockIntl = {};
1179
- Object.getOwnPropertyNames(NativeIntl).forEach((property) => ClockIntl[property] = NativeIntl[property]);
1180
- ClockIntl.DateTimeFormat = function(...args) {
1181
- const realFormatter = new NativeIntl.DateTimeFormat(...args);
1182
- const formatter = {};
1183
- [
1184
- "formatRange",
1185
- "formatRangeToParts",
1186
- "resolvedOptions"
1187
- ].forEach((method) => {
1188
- formatter[method] = realFormatter[method].bind(realFormatter);
1189
- });
1190
- ["format", "formatToParts"].forEach((method) => {
1191
- formatter[method] = function(date) {
1192
- return realFormatter[method](date || ClockIntl.clock.now);
1193
- };
1194
- });
1195
- return formatter;
1196
- };
1197
- ClockIntl.DateTimeFormat.prototype = Object.create(NativeIntl.DateTimeFormat.prototype);
1198
- ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;
1199
- return ClockIntl;
1200
- }
1201
- function enqueueJob(clock, job) {
1202
- if (!clock.jobs) clock.jobs = [];
1203
- clock.jobs.push(job);
1204
- }
1205
- function runJobs(clock) {
1206
- if (!clock.jobs) return;
1207
- for (let i = 0; i < clock.jobs.length; i++) {
1208
- const job = clock.jobs[i];
1209
- job.func.apply(null, job.args);
1210
- checkIsNearInfiniteLimit(clock, i);
1211
- if (clock.loopLimit && i > clock.loopLimit) throw getInfiniteLoopError(clock, job);
1212
- }
1213
- resetIsNearInfiniteLimit();
1214
- clock.jobs = [];
1215
- }
1216
- /**
1217
- * @param {Clock} clock
1218
- * @param {Timer} timer
1219
- * @returns {number} id of the created timer
1220
- */
1221
- function addTimer(clock, timer) {
1222
- if (timer.func === void 0) throw new Error("Callback must be provided to timer calls");
1223
- if (addTimerReturnsObject) {
1224
- if (typeof timer.func !== "function") throw new TypeError(`[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${timer.func} of type ${typeof timer.func}`);
1225
- }
1226
- if (isNearInfiniteLimit) timer.error = /* @__PURE__ */ new Error();
1227
- timer.type = timer.immediate ? "Immediate" : "Timeout";
1228
- if (timer.hasOwnProperty("delay")) {
1229
- if (typeof timer.delay !== "number") timer.delay = parseInt(timer.delay, 10);
1230
- if (!isNumberFinite(timer.delay)) timer.delay = 0;
1231
- timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1232
- timer.delay = Math.max(0, timer.delay);
1233
- }
1234
- if (timer.hasOwnProperty("interval")) {
1235
- timer.type = "Interval";
1236
- timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1237
- }
1238
- if (timer.hasOwnProperty("animation")) {
1239
- timer.type = "AnimationFrame";
1240
- timer.animation = true;
1241
- }
1242
- if (timer.hasOwnProperty("idleCallback")) {
1243
- timer.type = "IdleCallback";
1244
- timer.idleCallback = true;
1245
- }
1246
- if (!clock.timers) clock.timers = {};
1247
- timer.id = uniqueTimerId++;
1248
- timer.createdAt = clock.now;
1249
- timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1250
- clock.timers[timer.id] = timer;
1251
- if (addTimerReturnsObject) {
1252
- const res = {
1253
- refed: true,
1254
- ref: function() {
1255
- this.refed = true;
1256
- return res;
1257
- },
1258
- unref: function() {
1259
- this.refed = false;
1260
- return res;
1261
- },
1262
- hasRef: function() {
1263
- return this.refed;
1264
- },
1265
- refresh: function() {
1266
- timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1267
- clock.timers[timer.id] = timer;
1268
- return res;
1269
- },
1270
- [Symbol.toPrimitive]: function() {
1271
- return timer.id;
1272
- }
1273
- };
1274
- return res;
1275
- }
1276
- return timer.id;
1277
- }
1278
- /**
1279
- * Timer comparitor
1280
- * @param {Timer} a
1281
- * @param {Timer} b
1282
- * @returns {number}
1283
- */
1284
- function compareTimers(a, b) {
1285
- if (a.callAt < b.callAt) return -1;
1286
- if (a.callAt > b.callAt) return 1;
1287
- if (a.immediate && !b.immediate) return -1;
1288
- if (!a.immediate && b.immediate) return 1;
1289
- if (a.createdAt < b.createdAt) return -1;
1290
- if (a.createdAt > b.createdAt) return 1;
1291
- if (a.id < b.id) return -1;
1292
- if (a.id > b.id) return 1;
1293
- }
1294
- /**
1295
- * @param {Clock} clock
1296
- * @param {number} from
1297
- * @param {number} to
1298
- * @returns {Timer}
1299
- */
1300
- function firstTimerInRange(clock, from, to) {
1301
- const timers = clock.timers;
1302
- let timer = null;
1303
- let id, isInRange;
1304
- for (id in timers) if (timers.hasOwnProperty(id)) {
1305
- isInRange = inRange(from, to, timers[id]);
1306
- if (isInRange && (!timer || compareTimers(timer, timers[id]) === 1)) timer = timers[id];
1307
- }
1308
- return timer;
1309
- }
1310
- /**
1311
- * @param {Clock} clock
1312
- * @returns {Timer}
1313
- */
1314
- function firstTimer(clock) {
1315
- const timers = clock.timers;
1316
- let timer = null;
1317
- let id;
1318
- for (id in timers) if (timers.hasOwnProperty(id)) {
1319
- if (!timer || compareTimers(timer, timers[id]) === 1) timer = timers[id];
1320
- }
1321
- return timer;
1322
- }
1323
- /**
1324
- * @param {Clock} clock
1325
- * @returns {Timer}
1326
- */
1327
- function lastTimer(clock) {
1328
- const timers = clock.timers;
1329
- let timer = null;
1330
- let id;
1331
- for (id in timers) if (timers.hasOwnProperty(id)) {
1332
- if (!timer || compareTimers(timer, timers[id]) === -1) timer = timers[id];
1333
- }
1334
- return timer;
1335
- }
1336
- /**
1337
- * @param {Clock} clock
1338
- * @param {Timer} timer
1339
- */
1340
- function callTimer(clock, timer) {
1341
- if (typeof timer.interval === "number") clock.timers[timer.id].callAt += timer.interval;
1342
- else delete clock.timers[timer.id];
1343
- if (typeof timer.func === "function") timer.func.apply(null, timer.args);
1344
- else {
1345
- const eval2 = eval;
1346
- (function() {
1347
- eval2(timer.func);
1348
- })();
1349
- }
1350
- }
1351
- /**
1352
- * Gets clear handler name for a given timer type
1353
- * @param {string} ttype
1354
- */
1355
- function getClearHandler(ttype) {
1356
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") return `cancel${ttype}`;
1357
- return `clear${ttype}`;
1358
- }
1359
- /**
1360
- * Gets schedule handler name for a given timer type
1361
- * @param {string} ttype
1362
- */
1363
- function getScheduleHandler(ttype) {
1364
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") return `request${ttype}`;
1365
- return `set${ttype}`;
1366
- }
1367
- /**
1368
- * Creates an anonymous function to warn only once
1369
- */
1370
- function createWarnOnce() {
1371
- let calls = 0;
1372
- return function(msg) {
1373
- !calls++ && console.warn(msg);
1374
- };
1375
- }
1376
- const warnOnce = createWarnOnce();
1377
- /**
1378
- * @param {Clock} clock
1379
- * @param {number} timerId
1380
- * @param {string} ttype
1381
- */
1382
- function clearTimer(clock, timerId, ttype) {
1383
- if (!timerId) return;
1384
- if (!clock.timers) clock.timers = {};
1385
- const id = Number(timerId);
1386
- if (Number.isNaN(id) || id < idCounterStart) {
1387
- const handlerName = getClearHandler(ttype);
1388
- if (clock.shouldClearNativeTimers === true) {
1389
- const nativeHandler = clock[`_${handlerName}`];
1390
- return typeof nativeHandler === "function" ? nativeHandler(timerId) : void 0;
1391
- }
1392
- warnOnce(`FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.
1393
- To automatically clean-up native timers, use \`shouldClearNativeTimers\`.`);
1394
- }
1395
- if (clock.timers.hasOwnProperty(id)) {
1396
- const timer = clock.timers[id];
1397
- if (timer.type === ttype || timer.type === "Timeout" && ttype === "Interval" || timer.type === "Interval" && ttype === "Timeout") delete clock.timers[id];
1398
- else {
1399
- const clear = getClearHandler(ttype);
1400
- const schedule = getScheduleHandler(timer.type);
1401
- throw new Error(`Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`);
1402
- }
1403
- }
1404
- }
1405
- /**
1406
- * @param {Clock} clock
1407
- * @param {Config} config
1408
- * @returns {Timer[]}
1409
- */
1410
- function uninstall(clock, config) {
1411
- let method, i, l;
1412
- const installedHrTime = "_hrtime";
1413
- const installedNextTick = "_nextTick";
1414
- for (i = 0, l = clock.methods.length; i < l; i++) {
1415
- method = clock.methods[i];
1416
- if (method === "hrtime" && _global.process) _global.process.hrtime = clock[installedHrTime];
1417
- else if (method === "nextTick" && _global.process) _global.process.nextTick = clock[installedNextTick];
1418
- else if (method === "performance") {
1419
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(clock, `_${method}`);
1420
- if (originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set) Object.defineProperty(_global, method, originalPerfDescriptor);
1421
- else if (originalPerfDescriptor.configurable) _global[method] = clock[`_${method}`];
1422
- } else if (_global[method] && _global[method].hadOwnProperty) _global[method] = clock[`_${method}`];
1423
- else try {
1424
- delete _global[method];
1425
- } catch (ignore) {}
1426
- if (clock.timersModuleMethods !== void 0) for (let j = 0; j < clock.timersModuleMethods.length; j++) {
1427
- const entry = clock.timersModuleMethods[j];
1428
- timersModule[entry.methodName] = entry.original;
1429
- }
1430
- if (clock.timersPromisesModuleMethods !== void 0) for (let j = 0; j < clock.timersPromisesModuleMethods.length; j++) {
1431
- const entry = clock.timersPromisesModuleMethods[j];
1432
- timersPromisesModule[entry.methodName] = entry.original;
1433
- }
1434
- }
1435
- if (config.shouldAdvanceTime === true) _global.clearInterval(clock.attachedInterval);
1436
- clock.methods = [];
1437
- for (const [listener, signal] of clock.abortListenerMap.entries()) {
1438
- signal.removeEventListener("abort", listener);
1439
- clock.abortListenerMap.delete(listener);
1440
- }
1441
- if (!clock.timers) return [];
1442
- return Object.keys(clock.timers).map(function mapper(key) {
1443
- return clock.timers[key];
1444
- });
1445
- }
1446
- /**
1447
- * @param {object} target the target containing the method to replace
1448
- * @param {string} method the keyname of the method on the target
1449
- * @param {Clock} clock
1450
- */
1451
- function hijackMethod(target, method, clock) {
1452
- clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
1453
- clock[`_${method}`] = target[method];
1454
- if (method === "Date") target[method] = clock[method];
1455
- else if (method === "Intl") target[method] = clock[method];
1456
- else if (method === "performance") {
1457
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(target, method);
1458
- if (originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set) {
1459
- Object.defineProperty(clock, `_${method}`, originalPerfDescriptor);
1460
- const perfDescriptor = Object.getOwnPropertyDescriptor(clock, method);
1461
- Object.defineProperty(target, method, perfDescriptor);
1462
- } else target[method] = clock[method];
1463
- } else {
1464
- target[method] = function() {
1465
- return clock[method].apply(clock, arguments);
1466
- };
1467
- Object.defineProperties(target[method], Object.getOwnPropertyDescriptors(clock[method]));
1468
- }
1469
- target[method].clock = clock;
1470
- }
1471
- /**
1472
- * @param {Clock} clock
1473
- * @param {number} advanceTimeDelta
1474
- */
1475
- function doIntervalTick(clock, advanceTimeDelta) {
1476
- clock.tick(advanceTimeDelta);
1477
- }
1478
- /**
1479
- * @typedef {object} Timers
1480
- * @property {setTimeout} setTimeout
1481
- * @property {clearTimeout} clearTimeout
1482
- * @property {setInterval} setInterval
1483
- * @property {clearInterval} clearInterval
1484
- * @property {Date} Date
1485
- * @property {Intl} Intl
1486
- * @property {SetImmediate=} setImmediate
1487
- * @property {function(NodeImmediate): void=} clearImmediate
1488
- * @property {function(number[]):number[]=} hrtime
1489
- * @property {NextTick=} nextTick
1490
- * @property {Performance=} performance
1491
- * @property {RequestAnimationFrame=} requestAnimationFrame
1492
- * @property {boolean=} queueMicrotask
1493
- * @property {function(number): void=} cancelAnimationFrame
1494
- * @property {RequestIdleCallback=} requestIdleCallback
1495
- * @property {function(number): void=} cancelIdleCallback
1496
- */
1497
- /** @type {Timers} */
1498
- const timers = {
1499
- setTimeout: _global.setTimeout,
1500
- clearTimeout: _global.clearTimeout,
1501
- setInterval: _global.setInterval,
1502
- clearInterval: _global.clearInterval,
1503
- Date: _global.Date
1504
- };
1505
- if (isPresent.setImmediate) timers.setImmediate = _global.setImmediate;
1506
- if (isPresent.clearImmediate) timers.clearImmediate = _global.clearImmediate;
1507
- if (isPresent.hrtime) timers.hrtime = _global.process.hrtime;
1508
- if (isPresent.nextTick) timers.nextTick = _global.process.nextTick;
1509
- if (isPresent.performance) timers.performance = _global.performance;
1510
- if (isPresent.requestAnimationFrame) timers.requestAnimationFrame = _global.requestAnimationFrame;
1511
- if (isPresent.queueMicrotask) timers.queueMicrotask = _global.queueMicrotask;
1512
- if (isPresent.cancelAnimationFrame) timers.cancelAnimationFrame = _global.cancelAnimationFrame;
1513
- if (isPresent.requestIdleCallback) timers.requestIdleCallback = _global.requestIdleCallback;
1514
- if (isPresent.cancelIdleCallback) timers.cancelIdleCallback = _global.cancelIdleCallback;
1515
- if (isPresent.Intl) timers.Intl = NativeIntl;
1516
- const originalSetTimeout = _global.setImmediate || _global.setTimeout;
1517
- /**
1518
- * @param {Date|number} [start] the system time - non-integer values are floored
1519
- * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
1520
- * @returns {Clock}
1521
- */
1522
- function createClock(start, loopLimit) {
1523
- start = Math.floor(getEpoch(start));
1524
- loopLimit = loopLimit || 1e3;
1525
- let nanos = 0;
1526
- const adjustedSystemTime = [0, 0];
1527
- const clock = {
1528
- now: start,
1529
- Date: createDate(),
1530
- loopLimit
1531
- };
1532
- clock.Date.clock = clock;
1533
- function getTimeToNextFrame() {
1534
- return 16 - (clock.now - start) % 16;
1535
- }
1536
- function hrtime(prev) {
1537
- const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
1538
- const secsSinceStart = Math.floor(millisSinceStart / 1e3);
1539
- const remainderInNanos = (millisSinceStart - secsSinceStart * 1e3) * 1e6 + nanos - adjustedSystemTime[1];
1540
- if (Array.isArray(prev)) {
1541
- if (prev[1] > 1e9) throw new TypeError("Number of nanoseconds can't exceed a billion");
1542
- const oldSecs = prev[0];
1543
- let nanoDiff = remainderInNanos - prev[1];
1544
- let secDiff = secsSinceStart - oldSecs;
1545
- if (nanoDiff < 0) {
1546
- nanoDiff += 1e9;
1547
- secDiff -= 1;
1548
- }
1549
- return [secDiff, nanoDiff];
1550
- }
1551
- return [secsSinceStart, remainderInNanos];
1552
- }
1553
- /**
1554
- * A high resolution timestamp in milliseconds.
1555
- * @typedef {number} DOMHighResTimeStamp
1556
- */
1557
- /**
1558
- * performance.now()
1559
- * @returns {DOMHighResTimeStamp}
1560
- */
1561
- function fakePerformanceNow() {
1562
- const hrt = hrtime();
1563
- return hrt[0] * 1e3 + hrt[1] / 1e6;
1564
- }
1565
- if (isPresent.hrtimeBigint) hrtime.bigint = function() {
1566
- const parts = hrtime();
1567
- return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]);
1568
- };
1569
- if (isPresent.Intl) {
1570
- clock.Intl = createIntl();
1571
- clock.Intl.clock = clock;
1572
- }
1573
- clock.requestIdleCallback = function requestIdleCallback(func, timeout) {
1574
- let timeToNextIdlePeriod = 0;
1575
- if (clock.countTimers() > 0) timeToNextIdlePeriod = 50;
1576
- const result = addTimer(clock, {
1577
- func,
1578
- args: Array.prototype.slice.call(arguments, 2),
1579
- delay: typeof timeout === "undefined" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod),
1580
- idleCallback: true
1581
- });
1582
- return Number(result);
1583
- };
1584
- clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
1585
- return clearTimer(clock, timerId, "IdleCallback");
1586
- };
1587
- clock.setTimeout = function setTimeout(func, timeout) {
1588
- return addTimer(clock, {
1589
- func,
1590
- args: Array.prototype.slice.call(arguments, 2),
1591
- delay: timeout
1592
- });
1593
- };
1594
- if (typeof _global.Promise !== "undefined" && utilPromisify) clock.setTimeout[utilPromisify.custom] = function promisifiedSetTimeout(timeout, arg) {
1595
- return new _global.Promise(function setTimeoutExecutor(resolve) {
1596
- addTimer(clock, {
1597
- func: resolve,
1598
- args: [arg],
1599
- delay: timeout
1600
- });
1601
- });
1602
- };
1603
- clock.clearTimeout = function clearTimeout(timerId) {
1604
- return clearTimer(clock, timerId, "Timeout");
1605
- };
1606
- clock.nextTick = function nextTick(func) {
1607
- return enqueueJob(clock, {
1608
- func,
1609
- args: Array.prototype.slice.call(arguments, 1),
1610
- error: isNearInfiniteLimit ? /* @__PURE__ */ new Error() : null
1611
- });
1612
- };
1613
- clock.queueMicrotask = function queueMicrotask(func) {
1614
- return clock.nextTick(func);
1615
- };
1616
- clock.setInterval = function setInterval(func, timeout) {
1617
- timeout = parseInt(timeout, 10);
1618
- return addTimer(clock, {
1619
- func,
1620
- args: Array.prototype.slice.call(arguments, 2),
1621
- delay: timeout,
1622
- interval: timeout
1623
- });
1624
- };
1625
- clock.clearInterval = function clearInterval(timerId) {
1626
- return clearTimer(clock, timerId, "Interval");
1627
- };
1628
- if (isPresent.setImmediate) {
1629
- clock.setImmediate = function setImmediate(func) {
1630
- return addTimer(clock, {
1631
- func,
1632
- args: Array.prototype.slice.call(arguments, 1),
1633
- immediate: true
1634
- });
1635
- };
1636
- if (typeof _global.Promise !== "undefined" && utilPromisify) clock.setImmediate[utilPromisify.custom] = function promisifiedSetImmediate(arg) {
1637
- return new _global.Promise(function setImmediateExecutor(resolve) {
1638
- addTimer(clock, {
1639
- func: resolve,
1640
- args: [arg],
1641
- immediate: true
1642
- });
1643
- });
1644
- };
1645
- clock.clearImmediate = function clearImmediate(timerId) {
1646
- return clearTimer(clock, timerId, "Immediate");
1647
- };
1648
- }
1649
- clock.countTimers = function countTimers() {
1650
- return Object.keys(clock.timers || {}).length + (clock.jobs || []).length;
1651
- };
1652
- clock.requestAnimationFrame = function requestAnimationFrame(func) {
1653
- const result = addTimer(clock, {
1654
- func,
1655
- delay: getTimeToNextFrame(),
1656
- get args() {
1657
- return [fakePerformanceNow()];
1658
- },
1659
- animation: true
1660
- });
1661
- return Number(result);
1662
- };
1663
- clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
1664
- return clearTimer(clock, timerId, "AnimationFrame");
1665
- };
1666
- clock.runMicrotasks = function runMicrotasks() {
1667
- runJobs(clock);
1668
- };
1669
- /**
1670
- * @param {number|string} tickValue milliseconds or a string parseable by parseTime
1671
- * @param {boolean} isAsync
1672
- * @param {Function} resolve
1673
- * @param {Function} reject
1674
- * @returns {number|undefined} will return the new `now` value or nothing for async
1675
- */
1676
- function doTick(tickValue, isAsync, resolve, reject) {
1677
- const msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
1678
- const ms = Math.floor(msFloat);
1679
- const remainder = nanoRemainder(msFloat);
1680
- let nanosTotal = nanos + remainder;
1681
- let tickTo = clock.now + ms;
1682
- if (msFloat < 0) throw new TypeError("Negative ticks are not supported");
1683
- if (nanosTotal >= 1e6) {
1684
- tickTo += 1;
1685
- nanosTotal -= 1e6;
1686
- }
1687
- nanos = nanosTotal;
1688
- let tickFrom = clock.now;
1689
- let previous = clock.now;
1690
- let timer, firstException, oldNow, nextPromiseTick, compensationCheck, postTimerCall;
1691
- clock.duringTick = true;
1692
- oldNow = clock.now;
1693
- runJobs(clock);
1694
- if (oldNow !== clock.now) {
1695
- tickFrom += clock.now - oldNow;
1696
- tickTo += clock.now - oldNow;
1697
- }
1698
- function doTickInner() {
1699
- timer = firstTimerInRange(clock, tickFrom, tickTo);
1700
- while (timer && tickFrom <= tickTo) {
1701
- if (clock.timers[timer.id]) {
1702
- tickFrom = timer.callAt;
1703
- clock.now = timer.callAt;
1704
- oldNow = clock.now;
1705
- try {
1706
- runJobs(clock);
1707
- callTimer(clock, timer);
1708
- } catch (e) {
1709
- firstException = firstException || e;
1710
- }
1711
- if (isAsync) {
1712
- originalSetTimeout(nextPromiseTick);
1713
- return;
1714
- }
1715
- compensationCheck();
1716
- }
1717
- postTimerCall();
1718
- }
1719
- oldNow = clock.now;
1720
- runJobs(clock);
1721
- if (oldNow !== clock.now) {
1722
- tickFrom += clock.now - oldNow;
1723
- tickTo += clock.now - oldNow;
1724
- }
1725
- clock.duringTick = false;
1726
- timer = firstTimerInRange(clock, tickFrom, tickTo);
1727
- if (timer) try {
1728
- clock.tick(tickTo - clock.now);
1729
- } catch (e) {
1730
- firstException = firstException || e;
1731
- }
1732
- else {
1733
- clock.now = tickTo;
1734
- nanos = nanosTotal;
1735
- }
1736
- if (firstException) throw firstException;
1737
- if (isAsync) resolve(clock.now);
1738
- else return clock.now;
1739
- }
1740
- nextPromiseTick = isAsync && function() {
1741
- try {
1742
- compensationCheck();
1743
- postTimerCall();
1744
- doTickInner();
1745
- } catch (e) {
1746
- reject(e);
1747
- }
1748
- };
1749
- compensationCheck = function() {
1750
- if (oldNow !== clock.now) {
1751
- tickFrom += clock.now - oldNow;
1752
- tickTo += clock.now - oldNow;
1753
- previous += clock.now - oldNow;
1754
- }
1755
- };
1756
- postTimerCall = function() {
1757
- timer = firstTimerInRange(clock, previous, tickTo);
1758
- previous = tickFrom;
1759
- };
1760
- return doTickInner();
1761
- }
1762
- /**
1763
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1764
- * @returns {number} will return the new `now` value
1765
- */
1766
- clock.tick = function tick(tickValue) {
1767
- return doTick(tickValue, false);
1768
- };
1769
- if (typeof _global.Promise !== "undefined")
1770
- /**
1771
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1772
- * @returns {Promise}
1773
- */
1774
- clock.tickAsync = function tickAsync(tickValue) {
1775
- return new _global.Promise(function(resolve, reject) {
1776
- originalSetTimeout(function() {
1777
- try {
1778
- doTick(tickValue, true, resolve, reject);
1779
- } catch (e) {
1780
- reject(e);
1781
- }
1782
- });
1783
- });
1784
- };
1785
- clock.next = function next() {
1786
- runJobs(clock);
1787
- const timer = firstTimer(clock);
1788
- if (!timer) return clock.now;
1789
- clock.duringTick = true;
1790
- try {
1791
- clock.now = timer.callAt;
1792
- callTimer(clock, timer);
1793
- runJobs(clock);
1794
- return clock.now;
1795
- } finally {
1796
- clock.duringTick = false;
1797
- }
1798
- };
1799
- if (typeof _global.Promise !== "undefined") clock.nextAsync = function nextAsync() {
1800
- return new _global.Promise(function(resolve, reject) {
1801
- originalSetTimeout(function() {
1802
- try {
1803
- const timer = firstTimer(clock);
1804
- if (!timer) {
1805
- resolve(clock.now);
1806
- return;
1807
- }
1808
- let err;
1809
- clock.duringTick = true;
1810
- clock.now = timer.callAt;
1811
- try {
1812
- callTimer(clock, timer);
1813
- } catch (e) {
1814
- err = e;
1815
- }
1816
- clock.duringTick = false;
1817
- originalSetTimeout(function() {
1818
- if (err) reject(err);
1819
- else resolve(clock.now);
1820
- });
1821
- } catch (e) {
1822
- reject(e);
1823
- }
1824
- });
1825
- });
1826
- };
1827
- clock.runAll = function runAll() {
1828
- let numTimers, i;
1829
- runJobs(clock);
1830
- for (i = 0; i < clock.loopLimit; i++) {
1831
- if (!clock.timers) {
1832
- resetIsNearInfiniteLimit();
1833
- return clock.now;
1834
- }
1835
- numTimers = Object.keys(clock.timers).length;
1836
- if (numTimers === 0) {
1837
- resetIsNearInfiniteLimit();
1838
- return clock.now;
1839
- }
1840
- clock.next();
1841
- checkIsNearInfiniteLimit(clock, i);
1842
- }
1843
- throw getInfiniteLoopError(clock, firstTimer(clock));
1844
- };
1845
- clock.runToFrame = function runToFrame() {
1846
- return clock.tick(getTimeToNextFrame());
1847
- };
1848
- if (typeof _global.Promise !== "undefined") clock.runAllAsync = function runAllAsync() {
1849
- return new _global.Promise(function(resolve, reject) {
1850
- let i = 0;
1851
- /**
1852
- *
1853
- */
1854
- function doRun() {
1855
- originalSetTimeout(function() {
1856
- try {
1857
- runJobs(clock);
1858
- let numTimers;
1859
- if (i < clock.loopLimit) {
1860
- if (!clock.timers) {
1861
- resetIsNearInfiniteLimit();
1862
- resolve(clock.now);
1863
- return;
1864
- }
1865
- numTimers = Object.keys(clock.timers).length;
1866
- if (numTimers === 0) {
1867
- resetIsNearInfiniteLimit();
1868
- resolve(clock.now);
1869
- return;
1870
- }
1871
- clock.next();
1872
- i++;
1873
- doRun();
1874
- checkIsNearInfiniteLimit(clock, i);
1875
- return;
1876
- }
1877
- reject(getInfiniteLoopError(clock, firstTimer(clock)));
1878
- } catch (e) {
1879
- reject(e);
1880
- }
1881
- });
1882
- }
1883
- doRun();
1884
- });
1885
- };
1886
- clock.runToLast = function runToLast() {
1887
- const timer = lastTimer(clock);
1888
- if (!timer) {
1889
- runJobs(clock);
1890
- return clock.now;
1891
- }
1892
- return clock.tick(timer.callAt - clock.now);
1893
- };
1894
- if (typeof _global.Promise !== "undefined") clock.runToLastAsync = function runToLastAsync() {
1895
- return new _global.Promise(function(resolve, reject) {
1896
- originalSetTimeout(function() {
1897
- try {
1898
- const timer = lastTimer(clock);
1899
- if (!timer) {
1900
- runJobs(clock);
1901
- resolve(clock.now);
1902
- }
1903
- resolve(clock.tickAsync(timer.callAt - clock.now));
1904
- } catch (e) {
1905
- reject(e);
1906
- }
1907
- });
1908
- });
1909
- };
1910
- clock.reset = function reset() {
1911
- nanos = 0;
1912
- clock.timers = {};
1913
- clock.jobs = [];
1914
- clock.now = start;
1915
- };
1916
- clock.setSystemTime = function setSystemTime(systemTime) {
1917
- const newNow = getEpoch(systemTime);
1918
- const difference = newNow - clock.now;
1919
- let id, timer;
1920
- adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
1921
- adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
1922
- clock.now = newNow;
1923
- nanos = 0;
1924
- for (id in clock.timers) if (clock.timers.hasOwnProperty(id)) {
1925
- timer = clock.timers[id];
1926
- timer.createdAt += difference;
1927
- timer.callAt += difference;
1928
- }
1929
- };
1930
- /**
1931
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1932
- * @returns {number} will return the new `now` value
1933
- */
1934
- clock.jump = function jump(tickValue) {
1935
- const msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
1936
- const ms = Math.floor(msFloat);
1937
- for (const timer of Object.values(clock.timers)) if (clock.now + ms > timer.callAt) timer.callAt = clock.now + ms;
1938
- clock.tick(ms);
1939
- };
1940
- if (isPresent.performance) {
1941
- clock.performance = Object.create(null);
1942
- clock.performance.now = fakePerformanceNow;
1943
- }
1944
- if (isPresent.hrtime) clock.hrtime = hrtime;
1945
- return clock;
1946
- }
1947
- /**
1948
- * @param {Config=} [config] Optional config
1949
- * @returns {Clock}
1950
- */
1951
- function install(config) {
1952
- if (arguments.length > 1 || config instanceof Date || Array.isArray(config) || typeof config === "number") throw new TypeError(`FakeTimers.install called with ${String(config)} install requires an object parameter`);
1953
- if (_global.Date.isFake === true) throw new TypeError("Can't install fake timers twice on the same global object.");
1954
- config = typeof config !== "undefined" ? config : {};
1955
- config.shouldAdvanceTime = config.shouldAdvanceTime || false;
1956
- config.advanceTimeDelta = config.advanceTimeDelta || 20;
1957
- config.shouldClearNativeTimers = config.shouldClearNativeTimers || false;
1958
- if (config.target) throw new TypeError("config.target is no longer supported. Use `withGlobal(target)` instead.");
1959
- /**
1960
- * @param {string} timer/object the name of the thing that is not present
1961
- * @param timer
1962
- */
1963
- function handleMissingTimer(timer) {
1964
- if (config.ignoreMissingTimers) return;
1965
- throw new ReferenceError(`non-existent timers and/or objects cannot be faked: '${timer}'`);
1966
- }
1967
- let i, l;
1968
- const clock = createClock(config.now, config.loopLimit);
1969
- clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
1970
- clock.uninstall = function() {
1971
- return uninstall(clock, config);
1972
- };
1973
- clock.abortListenerMap = /* @__PURE__ */ new Map();
1974
- clock.methods = config.toFake || [];
1975
- if (clock.methods.length === 0) clock.methods = Object.keys(timers);
1976
- if (config.shouldAdvanceTime === true) {
1977
- const intervalTick = doIntervalTick.bind(null, clock, config.advanceTimeDelta);
1978
- clock.attachedInterval = _global.setInterval(intervalTick, config.advanceTimeDelta);
1979
- }
1980
- if (clock.methods.includes("performance")) {
1981
- const proto = (() => {
1982
- if (hasPerformanceConstructorPrototype) return _global.performance.constructor.prototype;
1983
- if (hasPerformancePrototype) return _global.Performance.prototype;
1984
- })();
1985
- if (proto) {
1986
- Object.getOwnPropertyNames(proto).forEach(function(name) {
1987
- if (name !== "now") clock.performance[name] = name.indexOf("getEntries") === 0 ? NOOP_ARRAY : NOOP;
1988
- });
1989
- clock.performance.mark = (name) => new FakePerformanceEntry(name, "mark", 0, 0);
1990
- clock.performance.measure = (name) => new FakePerformanceEntry(name, "measure", 0, 100);
1991
- clock.performance.timeOrigin = getEpoch(config.now);
1992
- } else if ((config.toFake || []).includes("performance")) return handleMissingTimer("performance");
1993
- }
1994
- if (_global === globalObject && timersModule) clock.timersModuleMethods = [];
1995
- if (_global === globalObject && timersPromisesModule) clock.timersPromisesModuleMethods = [];
1996
- for (i = 0, l = clock.methods.length; i < l; i++) {
1997
- const nameOfMethodToReplace = clock.methods[i];
1998
- if (!isPresent[nameOfMethodToReplace]) {
1999
- handleMissingTimer(nameOfMethodToReplace);
2000
- continue;
2001
- }
2002
- if (nameOfMethodToReplace === "hrtime") {
2003
- if (_global.process && typeof _global.process.hrtime === "function") hijackMethod(_global.process, nameOfMethodToReplace, clock);
2004
- } else if (nameOfMethodToReplace === "nextTick") {
2005
- if (_global.process && typeof _global.process.nextTick === "function") hijackMethod(_global.process, nameOfMethodToReplace, clock);
2006
- } else hijackMethod(_global, nameOfMethodToReplace, clock);
2007
- if (clock.timersModuleMethods !== void 0 && timersModule[nameOfMethodToReplace]) {
2008
- const original = timersModule[nameOfMethodToReplace];
2009
- clock.timersModuleMethods.push({
2010
- methodName: nameOfMethodToReplace,
2011
- original
2012
- });
2013
- timersModule[nameOfMethodToReplace] = _global[nameOfMethodToReplace];
2014
- }
2015
- if (clock.timersPromisesModuleMethods !== void 0) {
2016
- if (nameOfMethodToReplace === "setTimeout") {
2017
- clock.timersPromisesModuleMethods.push({
2018
- methodName: "setTimeout",
2019
- original: timersPromisesModule.setTimeout
2020
- });
2021
- timersPromisesModule.setTimeout = (delay, value, options = {}) => new Promise((resolve, reject) => {
2022
- const abort = () => {
2023
- options.signal.removeEventListener("abort", abort);
2024
- clock.abortListenerMap.delete(abort);
2025
- clock.clearTimeout(handle);
2026
- reject(options.signal.reason);
2027
- };
2028
- const handle = clock.setTimeout(() => {
2029
- if (options.signal) {
2030
- options.signal.removeEventListener("abort", abort);
2031
- clock.abortListenerMap.delete(abort);
2032
- }
2033
- resolve(value);
2034
- }, delay);
2035
- if (options.signal) if (options.signal.aborted) abort();
2036
- else {
2037
- options.signal.addEventListener("abort", abort);
2038
- clock.abortListenerMap.set(abort, options.signal);
2039
- }
2040
- });
2041
- } else if (nameOfMethodToReplace === "setImmediate") {
2042
- clock.timersPromisesModuleMethods.push({
2043
- methodName: "setImmediate",
2044
- original: timersPromisesModule.setImmediate
2045
- });
2046
- timersPromisesModule.setImmediate = (value, options = {}) => new Promise((resolve, reject) => {
2047
- const abort = () => {
2048
- options.signal.removeEventListener("abort", abort);
2049
- clock.abortListenerMap.delete(abort);
2050
- clock.clearImmediate(handle);
2051
- reject(options.signal.reason);
2052
- };
2053
- const handle = clock.setImmediate(() => {
2054
- if (options.signal) {
2055
- options.signal.removeEventListener("abort", abort);
2056
- clock.abortListenerMap.delete(abort);
2057
- }
2058
- resolve(value);
2059
- });
2060
- if (options.signal) if (options.signal.aborted) abort();
2061
- else {
2062
- options.signal.addEventListener("abort", abort);
2063
- clock.abortListenerMap.set(abort, options.signal);
2064
- }
2065
- });
2066
- } else if (nameOfMethodToReplace === "setInterval") {
2067
- clock.timersPromisesModuleMethods.push({
2068
- methodName: "setInterval",
2069
- original: timersPromisesModule.setInterval
2070
- });
2071
- timersPromisesModule.setInterval = (delay, value, options = {}) => ({ [Symbol.asyncIterator]: () => {
2072
- const createResolvable = () => {
2073
- let resolve, reject;
2074
- const promise = new Promise((res, rej) => {
2075
- resolve = res;
2076
- reject = rej;
2077
- });
2078
- promise.resolve = resolve;
2079
- promise.reject = reject;
2080
- return promise;
2081
- };
2082
- let done = false;
2083
- let hasThrown = false;
2084
- let returnCall;
2085
- let nextAvailable = 0;
2086
- const nextQueue = [];
2087
- const handle = clock.setInterval(() => {
2088
- if (nextQueue.length > 0) nextQueue.shift().resolve();
2089
- else nextAvailable++;
2090
- }, delay);
2091
- const abort = () => {
2092
- options.signal.removeEventListener("abort", abort);
2093
- clock.abortListenerMap.delete(abort);
2094
- clock.clearInterval(handle);
2095
- done = true;
2096
- for (const resolvable of nextQueue) resolvable.resolve();
2097
- };
2098
- if (options.signal) if (options.signal.aborted) done = true;
2099
- else {
2100
- options.signal.addEventListener("abort", abort);
2101
- clock.abortListenerMap.set(abort, options.signal);
2102
- }
2103
- return {
2104
- next: async () => {
2105
- if (options.signal?.aborted && !hasThrown) {
2106
- hasThrown = true;
2107
- throw options.signal.reason;
2108
- }
2109
- if (done) return {
2110
- done: true,
2111
- value: void 0
2112
- };
2113
- if (nextAvailable > 0) {
2114
- nextAvailable--;
2115
- return {
2116
- done: false,
2117
- value
2118
- };
2119
- }
2120
- const resolvable = createResolvable();
2121
- nextQueue.push(resolvable);
2122
- await resolvable;
2123
- if (returnCall && nextQueue.length === 0) returnCall.resolve();
2124
- if (options.signal?.aborted && !hasThrown) {
2125
- hasThrown = true;
2126
- throw options.signal.reason;
2127
- }
2128
- if (done) return {
2129
- done: true,
2130
- value: void 0
2131
- };
2132
- return {
2133
- done: false,
2134
- value
2135
- };
2136
- },
2137
- return: async () => {
2138
- if (done) return {
2139
- done: true,
2140
- value: void 0
2141
- };
2142
- if (nextQueue.length > 0) {
2143
- returnCall = createResolvable();
2144
- await returnCall;
2145
- }
2146
- clock.clearInterval(handle);
2147
- done = true;
2148
- if (options.signal) {
2149
- options.signal.removeEventListener("abort", abort);
2150
- clock.abortListenerMap.delete(abort);
2151
- }
2152
- return {
2153
- done: true,
2154
- value: void 0
2155
- };
2156
- }
2157
- };
2158
- } });
2159
- }
2160
- }
2161
- }
2162
- return clock;
2163
- }
2164
- return {
2165
- timers,
2166
- createClock,
2167
- install,
2168
- withGlobal
2169
- };
2170
- }
2171
- /**
2172
- * @typedef {object} FakeTimers
2173
- * @property {Timers} timers
2174
- * @property {createClock} createClock
2175
- * @property {Function} install
2176
- * @property {withGlobal} withGlobal
2177
- */
2178
- /** @type {FakeTimers} */
2179
- const defaultImplementation = withGlobal(globalObject);
2180
- fakeTimersSrc.timers = defaultImplementation.timers;
2181
- fakeTimersSrc.createClock = defaultImplementation.createClock;
2182
- fakeTimersSrc.install = defaultImplementation.install;
2183
- fakeTimersSrc.withGlobal = withGlobal;
2184
- return fakeTimersSrc;
2185
- }
2186
- var fakeTimersSrcExports = requireFakeTimersSrc();
2187
- var FakeTimers = class {
2188
- _global;
2189
- _clock;
2190
- _fakingTime;
2191
- _fakingDate;
2192
- _fakeTimers;
2193
- _userConfig;
2194
- _now = RealDate.now;
2195
- constructor({ global, config }) {
2196
- this._userConfig = config;
2197
- this._fakingDate = null;
2198
- this._fakingTime = false;
2199
- this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
2200
- this._global = global;
2201
- }
2202
- clearAllTimers() {
2203
- if (this._fakingTime) this._clock.reset();
2204
- }
2205
- dispose() {
2206
- this.useRealTimers();
2207
- }
2208
- runAllTimers() {
2209
- if (this._checkFakeTimers()) this._clock.runAll();
2210
- }
2211
- async runAllTimersAsync() {
2212
- if (this._checkFakeTimers()) await this._clock.runAllAsync();
2213
- }
2214
- runOnlyPendingTimers() {
2215
- if (this._checkFakeTimers()) this._clock.runToLast();
2216
- }
2217
- async runOnlyPendingTimersAsync() {
2218
- if (this._checkFakeTimers()) await this._clock.runToLastAsync();
2219
- }
2220
- advanceTimersToNextTimer(steps = 1) {
2221
- if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
2222
- this._clock.next();
2223
- this._clock.tick(0);
2224
- if (this._clock.countTimers() === 0) break;
2225
- }
2226
- }
2227
- async advanceTimersToNextTimerAsync(steps = 1) {
2228
- if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
2229
- await this._clock.nextAsync();
2230
- this._clock.tick(0);
2231
- if (this._clock.countTimers() === 0) break;
2232
- }
2233
- }
2234
- advanceTimersByTime(msToRun) {
2235
- if (this._checkFakeTimers()) this._clock.tick(msToRun);
2236
- }
2237
- async advanceTimersByTimeAsync(msToRun) {
2238
- if (this._checkFakeTimers()) await this._clock.tickAsync(msToRun);
2239
- }
2240
- advanceTimersToNextFrame() {
2241
- if (this._checkFakeTimers()) this._clock.runToFrame();
2242
- }
2243
- runAllTicks() {
2244
- if (this._checkFakeTimers()) this._clock.runMicrotasks();
2245
- }
2246
- useRealTimers() {
2247
- if (this._fakingDate) {
2248
- resetDate();
2249
- this._fakingDate = null;
2250
- }
2251
- if (this._fakingTime) {
2252
- this._clock.uninstall();
2253
- this._fakingTime = false;
2254
- }
2255
- }
2256
- useFakeTimers() {
2257
- if (this._fakingDate) throw new Error("\"setSystemTime\" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.");
2258
- if (!this._fakingTime) {
2259
- const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
2260
- if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
2261
- this._clock = this._fakeTimers.install({
2262
- now: Date.now(),
2263
- ...this._userConfig,
2264
- toFake: this._userConfig?.toFake || toFake,
2265
- ignoreMissingTimers: true
2266
- });
2267
- this._fakingTime = true;
2268
- }
2269
- }
2270
- reset() {
2271
- if (this._checkFakeTimers()) {
2272
- const { now } = this._clock;
2273
- this._clock.reset();
2274
- this._clock.setSystemTime(now);
2275
- }
2276
- }
2277
- setSystemTime(now) {
2278
- const date = typeof now === "undefined" || now instanceof Date ? now : new Date(now);
2279
- if (this._fakingTime) this._clock.setSystemTime(date);
2280
- else {
2281
- this._fakingDate = date ?? new Date(this.getRealSystemTime());
2282
- mockDate(this._fakingDate);
2283
- }
2284
- }
2285
- getMockedSystemTime() {
2286
- return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
2287
- }
2288
- getRealSystemTime() {
2289
- return this._now();
2290
- }
2291
- getTimerCount() {
2292
- if (this._checkFakeTimers()) return this._clock.countTimers();
2293
- return 0;
2294
- }
2295
- configure(config) {
2296
- this._userConfig = config;
2297
- }
2298
- isFakeTimers() {
2299
- return this._fakingTime;
2300
- }
2301
- _checkFakeTimers() {
2302
- if (!this._fakingTime) throw new Error("Timers are not mocked. Try calling \"vi.useFakeTimers()\" first.");
2303
- return this._fakingTime;
2304
- }
2305
- };
2306
- function copyStackTrace(target, source) {
2307
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
2308
- return target;
2309
- }
2310
- function waitFor(callback, options = {}) {
2311
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
2312
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
2313
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
2314
- return new Promise((resolve, reject) => {
2315
- let lastError;
2316
- let promiseStatus = "idle";
2317
- let timeoutId;
2318
- let intervalId;
2319
- const onResolve = (result) => {
2320
- if (timeoutId) clearTimeout(timeoutId);
2321
- if (intervalId) clearInterval(intervalId);
2322
- resolve(result);
2323
- };
2324
- const handleTimeout = () => {
2325
- if (intervalId) clearInterval(intervalId);
2326
- let error = lastError;
2327
- if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
2328
- reject(error);
2329
- };
2330
- const checkCallback = () => {
2331
- if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
2332
- if (promiseStatus === "pending") return;
2333
- try {
2334
- const result = callback();
2335
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
2336
- const thenable = result;
2337
- promiseStatus = "pending";
2338
- thenable.then((resolvedValue) => {
2339
- promiseStatus = "resolved";
2340
- onResolve(resolvedValue);
2341
- }, (rejectedValue) => {
2342
- promiseStatus = "rejected";
2343
- lastError = rejectedValue;
2344
- });
2345
- } else {
2346
- onResolve(result);
2347
- return true;
2348
- }
2349
- } catch (error) {
2350
- lastError = error;
2351
- }
2352
- };
2353
- if (checkCallback() === true) return;
2354
- timeoutId = setTimeout(handleTimeout, timeout);
2355
- intervalId = setInterval(checkCallback, interval);
2356
- });
2357
- }
2358
- function waitUntil(callback, options = {}) {
2359
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
2360
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
2361
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
2362
- return new Promise((resolve, reject) => {
2363
- let promiseStatus = "idle";
2364
- let timeoutId;
2365
- let intervalId;
2366
- const onReject = (error) => {
2367
- if (intervalId) clearInterval(intervalId);
2368
- if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
2369
- reject(error);
2370
- };
2371
- const onResolve = (result) => {
2372
- if (!result) return;
2373
- if (timeoutId) clearTimeout(timeoutId);
2374
- if (intervalId) clearInterval(intervalId);
2375
- resolve(result);
2376
- return true;
2377
- };
2378
- const checkCallback = () => {
2379
- if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
2380
- if (promiseStatus === "pending") return;
2381
- try {
2382
- const result = callback();
2383
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
2384
- const thenable = result;
2385
- promiseStatus = "pending";
2386
- thenable.then((resolvedValue) => {
2387
- promiseStatus = "resolved";
2388
- onResolve(resolvedValue);
2389
- }, (rejectedValue) => {
2390
- promiseStatus = "rejected";
2391
- onReject(rejectedValue);
2392
- });
2393
- } else return onResolve(result);
2394
- } catch (error) {
2395
- onReject(error);
2396
- }
2397
- };
2398
- if (checkCallback() === true) return;
2399
- timeoutId = setTimeout(onReject, timeout);
2400
- intervalId = setInterval(checkCallback, interval);
2401
- });
2402
- }
2403
- function createVitest() {
2404
- let _config = null;
2405
- const workerState = getWorkerState();
2406
- let _timers;
2407
- const timers = () => _timers ||= new FakeTimers({
2408
- global: globalThis,
2409
- config: workerState.config.fakeTimers
2410
- });
2411
- const _stubsGlobal = /* @__PURE__ */ new Map();
2412
- const _stubsEnv = /* @__PURE__ */ new Map();
2413
- const _envBooleans = [
2414
- "PROD",
2415
- "DEV",
2416
- "SSR"
2417
- ];
2418
- const utils = {
2419
- useFakeTimers(config) {
2420
- if (isChildProcess()) {
2421
- if (config?.toFake?.includes("nextTick") || workerState.config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
2422
- }
2423
- if (config) timers().configure({
2424
- ...workerState.config.fakeTimers,
2425
- ...config
2426
- });
2427
- else timers().configure(workerState.config.fakeTimers);
2428
- timers().useFakeTimers();
2429
- return utils;
2430
- },
2431
- isFakeTimers() {
2432
- return timers().isFakeTimers();
2433
- },
2434
- useRealTimers() {
2435
- timers().useRealTimers();
2436
- return utils;
2437
- },
2438
- runOnlyPendingTimers() {
2439
- timers().runOnlyPendingTimers();
2440
- return utils;
2441
- },
2442
- async runOnlyPendingTimersAsync() {
2443
- await timers().runOnlyPendingTimersAsync();
2444
- return utils;
2445
- },
2446
- runAllTimers() {
2447
- timers().runAllTimers();
2448
- return utils;
2449
- },
2450
- async runAllTimersAsync() {
2451
- await timers().runAllTimersAsync();
2452
- return utils;
2453
- },
2454
- runAllTicks() {
2455
- timers().runAllTicks();
2456
- return utils;
2457
- },
2458
- advanceTimersByTime(ms) {
2459
- timers().advanceTimersByTime(ms);
2460
- return utils;
2461
- },
2462
- async advanceTimersByTimeAsync(ms) {
2463
- await timers().advanceTimersByTimeAsync(ms);
2464
- return utils;
2465
- },
2466
- advanceTimersToNextTimer() {
2467
- timers().advanceTimersToNextTimer();
2468
- return utils;
2469
- },
2470
- async advanceTimersToNextTimerAsync() {
2471
- await timers().advanceTimersToNextTimerAsync();
2472
- return utils;
2473
- },
2474
- advanceTimersToNextFrame() {
2475
- timers().advanceTimersToNextFrame();
2476
- return utils;
2477
- },
2478
- getTimerCount() {
2479
- return timers().getTimerCount();
2480
- },
2481
- setSystemTime(time) {
2482
- timers().setSystemTime(time);
2483
- return utils;
2484
- },
2485
- getMockedSystemTime() {
2486
- return timers().getMockedSystemTime();
2487
- },
2488
- getRealSystemTime() {
2489
- return timers().getRealSystemTime();
2490
- },
2491
- clearAllTimers() {
2492
- timers().clearAllTimers();
2493
- return utils;
2494
- },
2495
- spyOn,
2496
- fn,
2497
- waitFor,
2498
- waitUntil,
2499
- hoisted(factory) {
2500
- assertTypes(factory, "\"vi.hoisted\" factory", ["function"]);
2501
- return factory();
2502
- },
2503
- mock(path, factory) {
2504
- if (typeof path !== "string") throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
2505
- const importer = getImporter("mock");
2506
- _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
2507
- },
2508
- unmock(path) {
2509
- if (typeof path !== "string") throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
2510
- _mocker().queueUnmock(path, getImporter("unmock"));
2511
- },
2512
- doMock(path, factory) {
2513
- if (typeof path !== "string") throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
2514
- const importer = getImporter("doMock");
2515
- _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
2516
- },
2517
- doUnmock(path) {
2518
- if (typeof path !== "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
2519
- _mocker().queueUnmock(path, getImporter("doUnmock"));
2520
- },
2521
- async importActual(path) {
2522
- return _mocker().importActual(path, getImporter("importActual"), _mocker().getMockContext().callstack);
2523
- },
2524
- async importMock(path) {
2525
- return _mocker().importMock(path, getImporter("importMock"));
2526
- },
2527
- mockObject(value) {
2528
- return _mocker().mockObject({ value }).value;
2529
- },
2530
- mocked(item, _options = {}) {
2531
- return item;
2532
- },
2533
- isMockFunction(fn) {
2534
- return isMockFunction(fn);
2535
- },
2536
- clearAllMocks() {
2537
- [...mocks].reverse().forEach((spy) => spy.mockClear());
2538
- return utils;
2539
- },
2540
- resetAllMocks() {
2541
- [...mocks].reverse().forEach((spy) => spy.mockReset());
2542
- return utils;
2543
- },
2544
- restoreAllMocks() {
2545
- [...mocks].reverse().forEach((spy) => spy.mockRestore());
2546
- return utils;
2547
- },
2548
- stubGlobal(name, value) {
2549
- if (!_stubsGlobal.has(name)) _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
2550
- Object.defineProperty(globalThis, name, {
2551
- value,
2552
- writable: true,
2553
- configurable: true,
2554
- enumerable: true
2555
- });
2556
- return utils;
2557
- },
2558
- stubEnv(name, value) {
2559
- if (!_stubsEnv.has(name)) _stubsEnv.set(name, process.env[name]);
2560
- if (_envBooleans.includes(name)) process.env[name] = value ? "1" : "";
2561
- else if (value === void 0) delete process.env[name];
2562
- else process.env[name] = String(value);
2563
- return utils;
2564
- },
2565
- unstubAllGlobals() {
2566
- _stubsGlobal.forEach((original, name) => {
2567
- if (!original) Reflect.deleteProperty(globalThis, name);
2568
- else Object.defineProperty(globalThis, name, original);
2569
- });
2570
- _stubsGlobal.clear();
2571
- return utils;
2572
- },
2573
- unstubAllEnvs() {
2574
- _stubsEnv.forEach((original, name) => {
2575
- if (original === void 0) delete process.env[name];
2576
- else process.env[name] = original;
2577
- });
2578
- _stubsEnv.clear();
2579
- return utils;
2580
- },
2581
- resetModules() {
2582
- resetModules(workerState.moduleCache);
2583
- return utils;
2584
- },
2585
- async dynamicImportSettled() {
2586
- return waitForImportsToResolve();
2587
- },
2588
- setConfig(config) {
2589
- if (!_config) _config = { ...workerState.config };
2590
- Object.assign(workerState.config, config);
2591
- },
2592
- resetConfig() {
2593
- if (_config) Object.assign(workerState.config, _config);
2594
- }
2595
- };
2596
- return utils;
2597
- }
2598
- const vitest = createVitest();
2599
- const vi = vitest;
2600
- function _mocker() {
2601
- return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, { get(_, name) {
2602
- throw new Error(`Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`);
2603
- } });
2604
- }
2605
- function getImporter(name) {
2606
- const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n");
2607
- return parseSingleStack(stackArray[stackArray.findIndex((stack) => {
2608
- return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
2609
- }) + 1])?.file || "";
2610
- }
2611
-
2612
- //#endregion
2613
- export { globalExpect };