@jcheesepkg/nanobot 0.8.7 → 0.8.9

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