vitest 1.0.0-beta.1 → 1.0.0-beta.2

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 (40) hide show
  1. package/dist/browser.d.ts +2 -2
  2. package/dist/browser.js +2 -2
  3. package/dist/child.js +1 -1
  4. package/dist/{chunk-api-setup.0aeabd21.js → chunk-api-setup.5d9a93c7.js} +3 -0
  5. package/dist/{chunk-install-pkg.a430b45e.js → chunk-install-pkg.43d58972.js} +17 -14
  6. package/dist/{chunk-integrations-globals.c3c5e678.js → chunk-integrations-globals.9df12d91.js} +2 -3
  7. package/dist/{chunk-node-git.36288174.js → chunk-node-git.2f1df48f.js} +1 -1
  8. package/dist/{chunk-runtime-console.ea222ffb.js → chunk-runtime-console.f3263f87.js} +19 -4
  9. package/dist/cli-wrapper.js +1 -1
  10. package/dist/cli.js +7 -4
  11. package/dist/config.cjs +2 -1
  12. package/dist/config.d.ts +2 -2
  13. package/dist/config.js +2 -1
  14. package/dist/coverage.d.ts +1 -1
  15. package/dist/entry-vm.js +8 -3
  16. package/dist/entry.js +9 -4
  17. package/dist/environments.d.ts +1 -1
  18. package/dist/environments.js +1 -1
  19. package/dist/execute.d.ts +1 -1
  20. package/dist/index.d.ts +5 -4
  21. package/dist/index.js +3 -4
  22. package/dist/node.d.ts +2 -2
  23. package/dist/node.js +8 -5
  24. package/dist/{reporters-7bd09217.d.ts → reporters-d10f25e1.d.ts} +23 -18
  25. package/dist/reporters.d.ts +1 -1
  26. package/dist/reporters.js +6 -1
  27. package/dist/runners.d.ts +1 -1
  28. package/dist/runners.js +1 -2
  29. package/dist/{suite-543d56bd.d.ts → suite-919dd548.d.ts} +1 -1
  30. package/dist/suite.d.ts +2 -2
  31. package/dist/{vendor-environments.e73c5410.js → vendor-environments.094f240c.js} +2 -0
  32. package/dist/{vendor-index.f7fcd5e8.js → vendor-index.68ecee35.js} +1 -1
  33. package/dist/{vendor-index.85fc950a.js → vendor-index.e006069f.js} +4 -4
  34. package/dist/{vendor-node.bde9fb47.js → vendor-node.e5a35bfe.js} +83 -46
  35. package/dist/{vendor-reporters.f6975b8d.js → vendor-reporters.2953082e.js} +2 -1
  36. package/dist/vendor-vi.d30b47ae.js +3510 -0
  37. package/dist/vm.js +2 -2
  38. package/dist/worker.js +1 -1
  39. package/package.json +9 -9
  40. package/dist/vendor-vi.7f2b988f.js +0 -3491
@@ -0,0 +1,3510 @@
1
+ import * as chai$1 from 'chai';
2
+ import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './vendor-_commonjsHelpers.7d1333e8.js';
3
+ import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT as GLOBAL_EXPECT$1, getState, setState } from '@vitest/expect';
4
+ import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
5
+ import { getNames } from '@vitest/runner/utils';
6
+ import '@vitest/utils/error';
7
+ import { getCurrentTest } from '@vitest/runner';
8
+ import { g as getFullName } from './vendor-tasks.f9d75aed.js';
9
+ import { g as getWorkerState, a as getCurrentEnvironment } from './vendor-global.97e4527c.js';
10
+ import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
11
+ import { parseSingleStack } from '@vitest/utils/source-map';
12
+ import { R as RealDate, r as resetDate, m as mockDate } from './vendor-date.6e993429.js';
13
+ import { spyOn, fn, isMockFunction, spies } from '@vitest/spy';
14
+
15
+ function resetModules(modules, resetMocks = false) {
16
+ const skipPaths = [
17
+ // Vitest
18
+ /\/vitest\/dist\//,
19
+ /\/vite-node\/dist\//,
20
+ // yarn's .store folder
21
+ /vitest-virtual-\w+\/dist/,
22
+ // cnpm
23
+ /@vitest\/dist/,
24
+ // don't clear mocks
25
+ ...!resetMocks ? [/^mock:/] : []
26
+ ];
27
+ modules.forEach((mod, path) => {
28
+ if (skipPaths.some((re) => re.test(path)))
29
+ return;
30
+ modules.invalidateModule(mod);
31
+ });
32
+ }
33
+ function waitNextTick() {
34
+ const { setTimeout } = getSafeTimers();
35
+ return new Promise((resolve) => setTimeout(resolve, 0));
36
+ }
37
+ async function waitForImportsToResolve() {
38
+ await waitNextTick();
39
+ const state = getWorkerState();
40
+ const promises = [];
41
+ let resolvingCount = 0;
42
+ for (const mod of state.moduleCache.values()) {
43
+ if (mod.promise && !mod.evaluated)
44
+ promises.push(mod.promise);
45
+ if (mod.resolving)
46
+ resolvingCount++;
47
+ }
48
+ if (!promises.length && !resolvingCount)
49
+ return;
50
+ await Promise.allSettled(promises);
51
+ await waitForImportsToResolve();
52
+ }
53
+
54
+ function commonjsRequire(path) {
55
+ 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.');
56
+ }
57
+
58
+ var chaiSubset = {exports: {}};
59
+
60
+ (function (module, exports) {
61
+ (function() {
62
+ (function(chaiSubset) {
63
+ if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
64
+ return module.exports = chaiSubset;
65
+ } else {
66
+ return chai.use(chaiSubset);
67
+ }
68
+ })(function(chai, utils) {
69
+ var Assertion = chai.Assertion;
70
+ var assertionPrototype = Assertion.prototype;
71
+
72
+ Assertion.addMethod('containSubset', function (expected) {
73
+ var actual = utils.flag(this, 'object');
74
+ var showDiff = chai.config.showDiff;
75
+
76
+ assertionPrototype.assert.call(this,
77
+ compare(expected, actual),
78
+ 'expected #{act} to contain subset #{exp}',
79
+ 'expected #{act} to not contain subset #{exp}',
80
+ expected,
81
+ actual,
82
+ showDiff
83
+ );
84
+ });
85
+
86
+ chai.assert.containSubset = function(val, exp, msg) {
87
+ new chai.Assertion(val, msg).to.be.containSubset(exp);
88
+ };
89
+
90
+ function compare(expected, actual) {
91
+ if (expected === actual) {
92
+ return true;
93
+ }
94
+ if (typeof(actual) !== typeof(expected)) {
95
+ return false;
96
+ }
97
+ if (typeof(expected) !== 'object' || expected === null) {
98
+ return expected === actual;
99
+ }
100
+ if (!!expected && !actual) {
101
+ return false;
102
+ }
103
+
104
+ if (Array.isArray(expected)) {
105
+ if (typeof(actual.length) !== 'number') {
106
+ return false;
107
+ }
108
+ var aa = Array.prototype.slice.call(actual);
109
+ return expected.every(function (exp) {
110
+ return aa.some(function (act) {
111
+ return compare(exp, act);
112
+ });
113
+ });
114
+ }
115
+
116
+ if (expected instanceof Date) {
117
+ if (actual instanceof Date) {
118
+ return expected.getTime() === actual.getTime();
119
+ } else {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ return Object.keys(expected).every(function (key) {
125
+ var eo = expected[key];
126
+ var ao = actual[key];
127
+ if (typeof(eo) === 'object' && eo !== null && ao !== null) {
128
+ return compare(eo, ao);
129
+ }
130
+ if (typeof(eo) === 'function') {
131
+ return eo(ao);
132
+ }
133
+ return ao === eo;
134
+ });
135
+ }
136
+ });
137
+
138
+ }).call(commonjsGlobal);
139
+ } (chaiSubset));
140
+
141
+ var chaiSubsetExports = chaiSubset.exports;
142
+ var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
143
+
144
+ const MATCHERS_OBJECT = Symbol.for("matchers-object");
145
+ const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
146
+ const GLOBAL_EXPECT = Symbol.for("expect-global");
147
+
148
+ if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
149
+ const globalState = /* @__PURE__ */ new WeakMap();
150
+ const matchers = /* @__PURE__ */ Object.create(null);
151
+ Object.defineProperty(globalThis, MATCHERS_OBJECT, {
152
+ get: () => globalState
153
+ });
154
+ Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
155
+ configurable: true,
156
+ get: () => ({
157
+ state: globalState.get(globalThis[GLOBAL_EXPECT]),
158
+ matchers
159
+ })
160
+ });
161
+ }
162
+
163
+ function recordAsyncExpect(test, promise) {
164
+ if (test && promise instanceof Promise) {
165
+ promise = promise.finally(() => {
166
+ const index = test.promises.indexOf(promise);
167
+ if (index !== -1)
168
+ test.promises.splice(index, 1);
169
+ });
170
+ if (!test.promises)
171
+ test.promises = [];
172
+ test.promises.push(promise);
173
+ }
174
+ return promise;
175
+ }
176
+
177
+ let _client;
178
+ function getSnapshotClient() {
179
+ if (!_client) {
180
+ _client = new SnapshotClient({
181
+ isEqual: (received, expected) => {
182
+ return equals(received, expected, [iterableEquality, subsetEquality]);
183
+ }
184
+ });
185
+ }
186
+ return _client;
187
+ }
188
+ function getErrorMessage(err) {
189
+ if (err instanceof Error)
190
+ return err.message;
191
+ return err;
192
+ }
193
+ function getErrorString(expected, promise) {
194
+ if (typeof expected !== "function") {
195
+ if (!promise)
196
+ throw new Error(`expected must be a function, received ${typeof expected}`);
197
+ return getErrorMessage(expected);
198
+ }
199
+ try {
200
+ expected();
201
+ } catch (e) {
202
+ return getErrorMessage(e);
203
+ }
204
+ throw new Error("snapshot function didn't throw");
205
+ }
206
+ const SnapshotPlugin = (chai, utils) => {
207
+ const getTestNames = (test) => {
208
+ var _a;
209
+ if (!test)
210
+ return {};
211
+ return {
212
+ filepath: (_a = test.file) == null ? void 0 : _a.filepath,
213
+ name: getNames(test).slice(1).join(" > ")
214
+ };
215
+ };
216
+ for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
217
+ utils.addMethod(
218
+ chai.Assertion.prototype,
219
+ key,
220
+ function(properties, message) {
221
+ const expected = utils.flag(this, "object");
222
+ const test = utils.flag(this, "vitest-test");
223
+ if (typeof properties === "string" && typeof message === "undefined") {
224
+ message = properties;
225
+ properties = void 0;
226
+ }
227
+ const errorMessage = utils.flag(this, "message");
228
+ getSnapshotClient().assert({
229
+ received: expected,
230
+ message,
231
+ isInline: false,
232
+ properties,
233
+ errorMessage,
234
+ ...getTestNames(test)
235
+ });
236
+ }
237
+ );
238
+ }
239
+ utils.addMethod(
240
+ chai.Assertion.prototype,
241
+ "toMatchFileSnapshot",
242
+ function(file, message) {
243
+ const expected = utils.flag(this, "object");
244
+ const test = utils.flag(this, "vitest-test");
245
+ const errorMessage = utils.flag(this, "message");
246
+ const promise = getSnapshotClient().assertRaw({
247
+ received: expected,
248
+ message,
249
+ isInline: false,
250
+ rawSnapshot: {
251
+ file
252
+ },
253
+ errorMessage,
254
+ ...getTestNames(test)
255
+ });
256
+ return recordAsyncExpect(test, promise);
257
+ }
258
+ );
259
+ utils.addMethod(
260
+ chai.Assertion.prototype,
261
+ "toMatchInlineSnapshot",
262
+ function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
263
+ var _a;
264
+ const test = utils.flag(this, "vitest-test");
265
+ const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
266
+ if (isInsideEach)
267
+ 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)
276
+ inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
277
+ const errorMessage = utils.flag(this, "message");
278
+ getSnapshotClient().assert({
279
+ received: expected,
280
+ message,
281
+ isInline: true,
282
+ properties,
283
+ inlineSnapshot,
284
+ error,
285
+ errorMessage,
286
+ ...getTestNames(test)
287
+ });
288
+ }
289
+ );
290
+ utils.addMethod(
291
+ chai.Assertion.prototype,
292
+ "toThrowErrorMatchingSnapshot",
293
+ function(message) {
294
+ const expected = utils.flag(this, "object");
295
+ const test = utils.flag(this, "vitest-test");
296
+ const promise = utils.flag(this, "promise");
297
+ const errorMessage = utils.flag(this, "message");
298
+ getSnapshotClient().assert({
299
+ received: getErrorString(expected, promise),
300
+ message,
301
+ errorMessage,
302
+ ...getTestNames(test)
303
+ });
304
+ }
305
+ );
306
+ utils.addMethod(
307
+ chai.Assertion.prototype,
308
+ "toThrowErrorMatchingInlineSnapshot",
309
+ function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
310
+ var _a;
311
+ const test = utils.flag(this, "vitest-test");
312
+ const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
313
+ if (isInsideEach)
314
+ throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
315
+ const expected = utils.flag(this, "object");
316
+ const error = utils.flag(this, "error");
317
+ const promise = utils.flag(this, "promise");
318
+ const errorMessage = utils.flag(this, "message");
319
+ getSnapshotClient().assert({
320
+ received: getErrorString(expected, promise),
321
+ message,
322
+ inlineSnapshot,
323
+ isInline: true,
324
+ error,
325
+ errorMessage,
326
+ ...getTestNames(test)
327
+ });
328
+ }
329
+ );
330
+ utils.addMethod(
331
+ chai.expect,
332
+ "addSnapshotSerializer",
333
+ addSerializer
334
+ );
335
+ };
336
+
337
+ chai$1.use(JestExtend);
338
+ chai$1.use(JestChaiExpect);
339
+ chai$1.use(Subset);
340
+ chai$1.use(SnapshotPlugin);
341
+ chai$1.use(JestAsymmetricMatchers);
342
+
343
+ function createExpect(test) {
344
+ var _a;
345
+ const expect = (value, message) => {
346
+ const { assertionCalls } = getState(expect);
347
+ setState({ assertionCalls: assertionCalls + 1, soft: false }, expect);
348
+ const assert2 = chai$1.expect(value, message);
349
+ const _test = test || getCurrentTest();
350
+ if (_test)
351
+ return assert2.withTest(_test);
352
+ else
353
+ return assert2;
354
+ };
355
+ Object.assign(expect, chai$1.expect);
356
+ expect.getState = () => getState(expect);
357
+ expect.setState = (state) => setState(state, expect);
358
+ const globalState = getState(globalThis[GLOBAL_EXPECT$1]) || {};
359
+ setState({
360
+ // this should also add "snapshotState" that is added conditionally
361
+ ...globalState,
362
+ assertionCalls: 0,
363
+ isExpectingAssertions: false,
364
+ isExpectingAssertionsError: null,
365
+ expectedAssertionsNumber: null,
366
+ expectedAssertionsNumberErrorGen: null,
367
+ environment: getCurrentEnvironment(),
368
+ testPath: test ? (_a = test.suite.file) == null ? void 0 : _a.filepath : globalState.testPath,
369
+ currentTestName: test ? getFullName(test) : globalState.currentTestName
370
+ }, expect);
371
+ expect.extend = (matchers) => chai$1.expect.extend(expect, matchers);
372
+ expect.soft = (...args) => {
373
+ const assert2 = expect(...args);
374
+ expect.setState({
375
+ soft: true
376
+ });
377
+ return assert2;
378
+ };
379
+ expect.unreachable = (message) => {
380
+ chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
381
+ };
382
+ function assertions(expected) {
383
+ const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
384
+ if (Error.captureStackTrace)
385
+ Error.captureStackTrace(errorGen(), assertions);
386
+ expect.setState({
387
+ expectedAssertionsNumber: expected,
388
+ expectedAssertionsNumberErrorGen: errorGen
389
+ });
390
+ }
391
+ function hasAssertions() {
392
+ const error = new Error("expected any number of assertion, but got none");
393
+ if (Error.captureStackTrace)
394
+ Error.captureStackTrace(error, hasAssertions);
395
+ expect.setState({
396
+ isExpectingAssertions: true,
397
+ isExpectingAssertionsError: error
398
+ });
399
+ }
400
+ chai$1.util.addMethod(expect, "assertions", assertions);
401
+ chai$1.util.addMethod(expect, "hasAssertions", hasAssertions);
402
+ return expect;
403
+ }
404
+ const globalExpect = createExpect();
405
+ Object.defineProperty(globalThis, GLOBAL_EXPECT$1, {
406
+ value: globalExpect,
407
+ writable: true,
408
+ configurable: true
409
+ });
410
+
411
+ /**
412
+ * A reference to the global object
413
+ *
414
+ * @type {object} globalObject
415
+ */
416
+ var globalObject$1;
417
+
418
+ /* istanbul ignore else */
419
+ if (typeof commonjsGlobal !== "undefined") {
420
+ // Node
421
+ globalObject$1 = commonjsGlobal;
422
+ } else if (typeof window !== "undefined") {
423
+ // Browser
424
+ globalObject$1 = window;
425
+ } else {
426
+ // WebWorker
427
+ globalObject$1 = self;
428
+ }
429
+
430
+ var global = globalObject$1;
431
+
432
+ /**
433
+ * Is true when the environment causes an error to be thrown for accessing the
434
+ * __proto__ property.
435
+ *
436
+ * This is necessary in order to support `node --disable-proto=throw`.
437
+ *
438
+ * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
439
+ *
440
+ * @type {boolean}
441
+ */
442
+ let throwsOnProto$1;
443
+ try {
444
+ const object = {};
445
+ // eslint-disable-next-line no-proto, no-unused-expressions
446
+ object.__proto__;
447
+ throwsOnProto$1 = false;
448
+ } catch (_) {
449
+ // This branch is covered when tests are run with `--disable-proto=throw`,
450
+ // however we can test both branches at the same time, so this is ignored
451
+ /* istanbul ignore next */
452
+ throwsOnProto$1 = true;
453
+ }
454
+
455
+ var throwsOnProto_1 = throwsOnProto$1;
456
+
457
+ var call = Function.call;
458
+ var throwsOnProto = throwsOnProto_1;
459
+
460
+ var disallowedProperties = [
461
+ // ignore size because it throws from Map
462
+ "size",
463
+ "caller",
464
+ "callee",
465
+ "arguments",
466
+ ];
467
+
468
+ // This branch is covered when tests are run with `--disable-proto=throw`,
469
+ // however we can test both branches at the same time, so this is ignored
470
+ /* istanbul ignore next */
471
+ if (throwsOnProto) {
472
+ disallowedProperties.push("__proto__");
473
+ }
474
+
475
+ var copyPrototypeMethods = function copyPrototypeMethods(prototype) {
476
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
477
+ return Object.getOwnPropertyNames(prototype).reduce(function (
478
+ result,
479
+ name
480
+ ) {
481
+ if (disallowedProperties.includes(name)) {
482
+ return result;
483
+ }
484
+
485
+ if (typeof prototype[name] !== "function") {
486
+ return result;
487
+ }
488
+
489
+ result[name] = call.bind(prototype[name]);
490
+
491
+ return result;
492
+ },
493
+ Object.create(null));
494
+ };
495
+
496
+ var copyPrototype$5 = copyPrototypeMethods;
497
+
498
+ var array = copyPrototype$5(Array.prototype);
499
+
500
+ var every$1 = array.every;
501
+
502
+ /**
503
+ * @private
504
+ */
505
+ function hasCallsLeft(callMap, spy) {
506
+ if (callMap[spy.id] === undefined) {
507
+ callMap[spy.id] = 0;
508
+ }
509
+
510
+ return callMap[spy.id] < spy.callCount;
511
+ }
512
+
513
+ /**
514
+ * @private
515
+ */
516
+ function checkAdjacentCalls(callMap, spy, index, spies) {
517
+ var calledBeforeNext = true;
518
+
519
+ if (index !== spies.length - 1) {
520
+ calledBeforeNext = spy.calledBefore(spies[index + 1]);
521
+ }
522
+
523
+ if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
524
+ callMap[spy.id] += 1;
525
+ return true;
526
+ }
527
+
528
+ return false;
529
+ }
530
+
531
+ /**
532
+ * A Sinon proxy object (fake, spy, stub)
533
+ *
534
+ * @typedef {object} SinonProxy
535
+ * @property {Function} calledBefore - A method that determines if this proxy was called before another one
536
+ * @property {string} id - Some id
537
+ * @property {number} callCount - Number of times this proxy has been called
538
+ */
539
+
540
+ /**
541
+ * Returns true when the spies have been called in the order they were supplied in
542
+ *
543
+ * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
544
+ * @returns {boolean} true when spies are called in order, false otherwise
545
+ */
546
+ function calledInOrder(spies) {
547
+ var callMap = {};
548
+ // eslint-disable-next-line no-underscore-dangle
549
+ var _spies = arguments.length > 1 ? arguments : spies;
550
+
551
+ return every$1(_spies, checkAdjacentCalls.bind(null, callMap));
552
+ }
553
+
554
+ var calledInOrder_1 = calledInOrder;
555
+
556
+ /**
557
+ * Returns a display name for a function
558
+ *
559
+ * @param {Function} func
560
+ * @returns {string}
561
+ */
562
+ var functionName$1 = function functionName(func) {
563
+ if (!func) {
564
+ return "";
565
+ }
566
+
567
+ try {
568
+ return (
569
+ func.displayName ||
570
+ func.name ||
571
+ // Use function decomposition as a last resort to get function
572
+ // name. Does not rely on function decomposition to work - if it
573
+ // doesn't debugging will be slightly less informative
574
+ // (i.e. toString will say 'spy' rather than 'myFunc').
575
+ (String(func).match(/function ([^\s(]+)/) || [])[1]
576
+ );
577
+ } catch (e) {
578
+ // Stringify may fail and we might get an exception, as a last-last
579
+ // resort fall back to empty string.
580
+ return "";
581
+ }
582
+ };
583
+
584
+ var functionName = functionName$1;
585
+
586
+ /**
587
+ * Returns a display name for a value from a constructor
588
+ *
589
+ * @param {object} value A value to examine
590
+ * @returns {(string|null)} A string or null
591
+ */
592
+ function className(value) {
593
+ return (
594
+ (value.constructor && value.constructor.name) ||
595
+ // The next branch is for IE11 support only:
596
+ // Because the name property is not set on the prototype
597
+ // of the Function object, we finally try to grab the
598
+ // name from its definition. This will never be reached
599
+ // in node, so we are not able to test this properly.
600
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
601
+ (typeof value.constructor === "function" &&
602
+ /* istanbul ignore next */
603
+ functionName(value.constructor)) ||
604
+ null
605
+ );
606
+ }
607
+
608
+ var className_1 = className;
609
+
610
+ var deprecated = {};
611
+
612
+ /* eslint-disable no-console */
613
+
614
+ (function (exports) {
615
+
616
+ /**
617
+ * Returns a function that will invoke the supplied function and print a
618
+ * deprecation warning to the console each time it is called.
619
+ *
620
+ * @param {Function} func
621
+ * @param {string} msg
622
+ * @returns {Function}
623
+ */
624
+ exports.wrap = function (func, msg) {
625
+ var wrapped = function () {
626
+ exports.printWarning(msg);
627
+ return func.apply(this, arguments);
628
+ };
629
+ if (func.prototype) {
630
+ wrapped.prototype = func.prototype;
631
+ }
632
+ return wrapped;
633
+ };
634
+
635
+ /**
636
+ * Returns a string which can be supplied to `wrap()` to notify the user that a
637
+ * particular part of the sinon API has been deprecated.
638
+ *
639
+ * @param {string} packageName
640
+ * @param {string} funcName
641
+ * @returns {string}
642
+ */
643
+ exports.defaultMsg = function (packageName, funcName) {
644
+ return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
645
+ };
646
+
647
+ /**
648
+ * Prints a warning on the console, when it exists
649
+ *
650
+ * @param {string} msg
651
+ * @returns {undefined}
652
+ */
653
+ exports.printWarning = function (msg) {
654
+ /* istanbul ignore next */
655
+ if (typeof process === "object" && process.emitWarning) {
656
+ // Emit Warnings in Node
657
+ process.emitWarning(msg);
658
+ } else if (console.info) {
659
+ console.info(msg);
660
+ } else {
661
+ console.log(msg);
662
+ }
663
+ };
664
+ } (deprecated));
665
+
666
+ /**
667
+ * Returns true when fn returns true for all members of obj.
668
+ * This is an every implementation that works for all iterables
669
+ *
670
+ * @param {object} obj
671
+ * @param {Function} fn
672
+ * @returns {boolean}
673
+ */
674
+ var every = function every(obj, fn) {
675
+ var pass = true;
676
+
677
+ try {
678
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
679
+ obj.forEach(function () {
680
+ if (!fn.apply(this, arguments)) {
681
+ // Throwing an error is the only way to break `forEach`
682
+ throw new Error();
683
+ }
684
+ });
685
+ } catch (e) {
686
+ pass = false;
687
+ }
688
+
689
+ return pass;
690
+ };
691
+
692
+ var sort = array.sort;
693
+ var slice = array.slice;
694
+
695
+ /**
696
+ * @private
697
+ */
698
+ function comparator(a, b) {
699
+ // uuid, won't ever be equal
700
+ var aCall = a.getCall(0);
701
+ var bCall = b.getCall(0);
702
+ var aId = (aCall && aCall.callId) || -1;
703
+ var bId = (bCall && bCall.callId) || -1;
704
+
705
+ return aId < bId ? -1 : 1;
706
+ }
707
+
708
+ /**
709
+ * A Sinon proxy object (fake, spy, stub)
710
+ *
711
+ * @typedef {object} SinonProxy
712
+ * @property {Function} getCall - A method that can return the first call
713
+ */
714
+
715
+ /**
716
+ * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
717
+ *
718
+ * @param {SinonProxy[] | SinonProxy} spies
719
+ * @returns {SinonProxy[]}
720
+ */
721
+ function orderByFirstCall(spies) {
722
+ return sort(slice(spies), comparator);
723
+ }
724
+
725
+ var orderByFirstCall_1 = orderByFirstCall;
726
+
727
+ var copyPrototype$4 = copyPrototypeMethods;
728
+
729
+ var _function = copyPrototype$4(Function.prototype);
730
+
731
+ var copyPrototype$3 = copyPrototypeMethods;
732
+
733
+ var map = copyPrototype$3(Map.prototype);
734
+
735
+ var copyPrototype$2 = copyPrototypeMethods;
736
+
737
+ var object = copyPrototype$2(Object.prototype);
738
+
739
+ var copyPrototype$1 = copyPrototypeMethods;
740
+
741
+ var set = copyPrototype$1(Set.prototype);
742
+
743
+ var copyPrototype = copyPrototypeMethods;
744
+
745
+ var string = copyPrototype(String.prototype);
746
+
747
+ var prototypes = {
748
+ array: array,
749
+ function: _function,
750
+ map: map,
751
+ object: object,
752
+ set: set,
753
+ string: string,
754
+ };
755
+
756
+ var typeDetect = {exports: {}};
757
+
758
+ (function (module, exports) {
759
+ (function (global, factory) {
760
+ module.exports = factory() ;
761
+ }(commonjsGlobal, (function () {
762
+ /* !
763
+ * type-detect
764
+ * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
765
+ * MIT Licensed
766
+ */
767
+ var promiseExists = typeof Promise === 'function';
768
+
769
+ /* eslint-disable no-undef */
770
+ var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist
771
+
772
+ var symbolExists = typeof Symbol !== 'undefined';
773
+ var mapExists = typeof Map !== 'undefined';
774
+ var setExists = typeof Set !== 'undefined';
775
+ var weakMapExists = typeof WeakMap !== 'undefined';
776
+ var weakSetExists = typeof WeakSet !== 'undefined';
777
+ var dataViewExists = typeof DataView !== 'undefined';
778
+ var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
779
+ var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
780
+ var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
781
+ var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
782
+ var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
783
+ var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
784
+ var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
785
+ var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
786
+ var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
787
+ var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
788
+ var toStringLeftSliceLength = 8;
789
+ var toStringRightSliceLength = -1;
790
+ /**
791
+ * ### typeOf (obj)
792
+ *
793
+ * Uses `Object.prototype.toString` to determine the type of an object,
794
+ * normalising behaviour across engine versions & well optimised.
795
+ *
796
+ * @param {Mixed} object
797
+ * @return {String} object type
798
+ * @api public
799
+ */
800
+ function typeDetect(obj) {
801
+ /* ! Speed optimisation
802
+ * Pre:
803
+ * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
804
+ * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
805
+ * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
806
+ * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
807
+ * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
808
+ * Post:
809
+ * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
810
+ * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
811
+ * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
812
+ * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
813
+ * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
814
+ */
815
+ var typeofObj = typeof obj;
816
+ if (typeofObj !== 'object') {
817
+ return typeofObj;
818
+ }
819
+
820
+ /* ! Speed optimisation
821
+ * Pre:
822
+ * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
823
+ * Post:
824
+ * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
825
+ */
826
+ if (obj === null) {
827
+ return 'null';
828
+ }
829
+
830
+ /* ! Spec Conformance
831
+ * Test: `Object.prototype.toString.call(window)``
832
+ * - Node === "[object global]"
833
+ * - Chrome === "[object global]"
834
+ * - Firefox === "[object Window]"
835
+ * - PhantomJS === "[object Window]"
836
+ * - Safari === "[object Window]"
837
+ * - IE 11 === "[object Window]"
838
+ * - IE Edge === "[object Window]"
839
+ * Test: `Object.prototype.toString.call(this)``
840
+ * - Chrome Worker === "[object global]"
841
+ * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
842
+ * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
843
+ * - IE 11 Worker === "[object WorkerGlobalScope]"
844
+ * - IE Edge Worker === "[object WorkerGlobalScope]"
845
+ */
846
+ if (obj === globalObject) {
847
+ return 'global';
848
+ }
849
+
850
+ /* ! Speed optimisation
851
+ * Pre:
852
+ * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
853
+ * Post:
854
+ * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
855
+ */
856
+ if (
857
+ Array.isArray(obj) &&
858
+ (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
859
+ ) {
860
+ return 'Array';
861
+ }
862
+
863
+ // Not caching existence of `window` and related properties due to potential
864
+ // for `window` to be unset before tests in quasi-browser environments.
865
+ if (typeof window === 'object' && window !== null) {
866
+ /* ! Spec Conformance
867
+ * (https://html.spec.whatwg.org/multipage/browsers.html#location)
868
+ * WhatWG HTML$7.7.3 - The `Location` interface
869
+ * Test: `Object.prototype.toString.call(window.location)``
870
+ * - IE <=11 === "[object Object]"
871
+ * - IE Edge <=13 === "[object Object]"
872
+ */
873
+ if (typeof window.location === 'object' && obj === window.location) {
874
+ return 'Location';
875
+ }
876
+
877
+ /* ! Spec Conformance
878
+ * (https://html.spec.whatwg.org/#document)
879
+ * WhatWG HTML$3.1.1 - The `Document` object
880
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
881
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
882
+ * which suggests that browsers should use HTMLTableCellElement for
883
+ * both TD and TH elements. WhatWG separates these.
884
+ * WhatWG HTML states:
885
+ * > For historical reasons, Window objects must also have a
886
+ * > writable, configurable, non-enumerable property named
887
+ * > HTMLDocument whose value is the Document interface object.
888
+ * Test: `Object.prototype.toString.call(document)``
889
+ * - Chrome === "[object HTMLDocument]"
890
+ * - Firefox === "[object HTMLDocument]"
891
+ * - Safari === "[object HTMLDocument]"
892
+ * - IE <=10 === "[object Document]"
893
+ * - IE 11 === "[object HTMLDocument]"
894
+ * - IE Edge <=13 === "[object HTMLDocument]"
895
+ */
896
+ if (typeof window.document === 'object' && obj === window.document) {
897
+ return 'Document';
898
+ }
899
+
900
+ if (typeof window.navigator === 'object') {
901
+ /* ! Spec Conformance
902
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
903
+ * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
904
+ * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
905
+ * - IE <=10 === "[object MSMimeTypesCollection]"
906
+ */
907
+ if (typeof window.navigator.mimeTypes === 'object' &&
908
+ obj === window.navigator.mimeTypes) {
909
+ return 'MimeTypeArray';
910
+ }
911
+
912
+ /* ! Spec Conformance
913
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
914
+ * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
915
+ * Test: `Object.prototype.toString.call(navigator.plugins)``
916
+ * - IE <=10 === "[object MSPluginsCollection]"
917
+ */
918
+ if (typeof window.navigator.plugins === 'object' &&
919
+ obj === window.navigator.plugins) {
920
+ return 'PluginArray';
921
+ }
922
+ }
923
+
924
+ if ((typeof window.HTMLElement === 'function' ||
925
+ typeof window.HTMLElement === 'object') &&
926
+ obj instanceof window.HTMLElement) {
927
+ /* ! Spec Conformance
928
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
929
+ * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
930
+ * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
931
+ * - IE <=10 === "[object HTMLBlockElement]"
932
+ */
933
+ if (obj.tagName === 'BLOCKQUOTE') {
934
+ return 'HTMLQuoteElement';
935
+ }
936
+
937
+ /* ! Spec Conformance
938
+ * (https://html.spec.whatwg.org/#htmltabledatacellelement)
939
+ * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
940
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
941
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
942
+ * which suggests that browsers should use HTMLTableCellElement for
943
+ * both TD and TH elements. WhatWG separates these.
944
+ * Test: Object.prototype.toString.call(document.createElement('td'))
945
+ * - Chrome === "[object HTMLTableCellElement]"
946
+ * - Firefox === "[object HTMLTableCellElement]"
947
+ * - Safari === "[object HTMLTableCellElement]"
948
+ */
949
+ if (obj.tagName === 'TD') {
950
+ return 'HTMLTableDataCellElement';
951
+ }
952
+
953
+ /* ! Spec Conformance
954
+ * (https://html.spec.whatwg.org/#htmltableheadercellelement)
955
+ * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
956
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
957
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
958
+ * which suggests that browsers should use HTMLTableCellElement for
959
+ * both TD and TH elements. WhatWG separates these.
960
+ * Test: Object.prototype.toString.call(document.createElement('th'))
961
+ * - Chrome === "[object HTMLTableCellElement]"
962
+ * - Firefox === "[object HTMLTableCellElement]"
963
+ * - Safari === "[object HTMLTableCellElement]"
964
+ */
965
+ if (obj.tagName === 'TH') {
966
+ return 'HTMLTableHeaderCellElement';
967
+ }
968
+ }
969
+ }
970
+
971
+ /* ! Speed optimisation
972
+ * Pre:
973
+ * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
974
+ * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
975
+ * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
976
+ * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
977
+ * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
978
+ * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
979
+ * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
980
+ * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
981
+ * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
982
+ * Post:
983
+ * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
984
+ * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
985
+ * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
986
+ * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
987
+ * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
988
+ * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
989
+ * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
990
+ * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
991
+ * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
992
+ */
993
+ var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
994
+ if (typeof stringTag === 'string') {
995
+ return stringTag;
996
+ }
997
+
998
+ var objPrototype = Object.getPrototypeOf(obj);
999
+ /* ! Speed optimisation
1000
+ * Pre:
1001
+ * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
1002
+ * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
1003
+ * Post:
1004
+ * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
1005
+ * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
1006
+ */
1007
+ if (objPrototype === RegExp.prototype) {
1008
+ return 'RegExp';
1009
+ }
1010
+
1011
+ /* ! Speed optimisation
1012
+ * Pre:
1013
+ * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
1014
+ * Post:
1015
+ * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
1016
+ */
1017
+ if (objPrototype === Date.prototype) {
1018
+ return 'Date';
1019
+ }
1020
+
1021
+ /* ! Spec Conformance
1022
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
1023
+ * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
1024
+ * Test: `Object.prototype.toString.call(Promise.resolve())``
1025
+ * - Chrome <=47 === "[object Object]"
1026
+ * - Edge <=20 === "[object Object]"
1027
+ * - Firefox 29-Latest === "[object Promise]"
1028
+ * - Safari 7.1-Latest === "[object Promise]"
1029
+ */
1030
+ if (promiseExists && objPrototype === Promise.prototype) {
1031
+ return 'Promise';
1032
+ }
1033
+
1034
+ /* ! Speed optimisation
1035
+ * Pre:
1036
+ * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
1037
+ * Post:
1038
+ * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
1039
+ */
1040
+ if (setExists && objPrototype === Set.prototype) {
1041
+ return 'Set';
1042
+ }
1043
+
1044
+ /* ! Speed optimisation
1045
+ * Pre:
1046
+ * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
1047
+ * Post:
1048
+ * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
1049
+ */
1050
+ if (mapExists && objPrototype === Map.prototype) {
1051
+ return 'Map';
1052
+ }
1053
+
1054
+ /* ! Speed optimisation
1055
+ * Pre:
1056
+ * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
1057
+ * Post:
1058
+ * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
1059
+ */
1060
+ if (weakSetExists && objPrototype === WeakSet.prototype) {
1061
+ return 'WeakSet';
1062
+ }
1063
+
1064
+ /* ! Speed optimisation
1065
+ * Pre:
1066
+ * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
1067
+ * Post:
1068
+ * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
1069
+ */
1070
+ if (weakMapExists && objPrototype === WeakMap.prototype) {
1071
+ return 'WeakMap';
1072
+ }
1073
+
1074
+ /* ! Spec Conformance
1075
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
1076
+ * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
1077
+ * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
1078
+ * - Edge <=13 === "[object Object]"
1079
+ */
1080
+ if (dataViewExists && objPrototype === DataView.prototype) {
1081
+ return 'DataView';
1082
+ }
1083
+
1084
+ /* ! Spec Conformance
1085
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
1086
+ * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
1087
+ * Test: `Object.prototype.toString.call(new Map().entries())``
1088
+ * - Edge <=13 === "[object Object]"
1089
+ */
1090
+ if (mapExists && objPrototype === mapIteratorPrototype) {
1091
+ return 'Map Iterator';
1092
+ }
1093
+
1094
+ /* ! Spec Conformance
1095
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
1096
+ * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
1097
+ * Test: `Object.prototype.toString.call(new Set().entries())``
1098
+ * - Edge <=13 === "[object Object]"
1099
+ */
1100
+ if (setExists && objPrototype === setIteratorPrototype) {
1101
+ return 'Set Iterator';
1102
+ }
1103
+
1104
+ /* ! Spec Conformance
1105
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
1106
+ * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
1107
+ * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
1108
+ * - Edge <=13 === "[object Object]"
1109
+ */
1110
+ if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
1111
+ return 'Array Iterator';
1112
+ }
1113
+
1114
+ /* ! Spec Conformance
1115
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
1116
+ * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
1117
+ * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
1118
+ * - Edge <=13 === "[object Object]"
1119
+ */
1120
+ if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
1121
+ return 'String Iterator';
1122
+ }
1123
+
1124
+ /* ! Speed optimisation
1125
+ * Pre:
1126
+ * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
1127
+ * Post:
1128
+ * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
1129
+ */
1130
+ if (objPrototype === null) {
1131
+ return 'Object';
1132
+ }
1133
+
1134
+ return Object
1135
+ .prototype
1136
+ .toString
1137
+ .call(obj)
1138
+ .slice(toStringLeftSliceLength, toStringRightSliceLength);
1139
+ }
1140
+
1141
+ return typeDetect;
1142
+
1143
+ })));
1144
+ } (typeDetect));
1145
+
1146
+ var typeDetectExports = typeDetect.exports;
1147
+
1148
+ var type = typeDetectExports;
1149
+
1150
+ /**
1151
+ * Returns the lower-case result of running type from type-detect on the value
1152
+ *
1153
+ * @param {*} value
1154
+ * @returns {string}
1155
+ */
1156
+ var typeOf = function typeOf(value) {
1157
+ return type(value).toLowerCase();
1158
+ };
1159
+
1160
+ /**
1161
+ * Returns a string representation of the value
1162
+ *
1163
+ * @param {*} value
1164
+ * @returns {string}
1165
+ */
1166
+ function valueToString(value) {
1167
+ if (value && value.toString) {
1168
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
1169
+ return value.toString();
1170
+ }
1171
+ return String(value);
1172
+ }
1173
+
1174
+ var valueToString_1 = valueToString;
1175
+
1176
+ var lib = {
1177
+ global: global,
1178
+ calledInOrder: calledInOrder_1,
1179
+ className: className_1,
1180
+ deprecated: deprecated,
1181
+ every: every,
1182
+ functionName: functionName$1,
1183
+ orderByFirstCall: orderByFirstCall_1,
1184
+ prototypes: prototypes,
1185
+ typeOf: typeOf,
1186
+ valueToString: valueToString_1,
1187
+ };
1188
+
1189
+ const globalObject = lib.global;
1190
+ let timersModule;
1191
+ if (typeof __vitest_required__ !== 'undefined') {
1192
+ try {
1193
+ timersModule = __vitest_required__.timers;
1194
+ } catch (e) {
1195
+ // ignored
1196
+ }
1197
+ }
1198
+
1199
+ /**
1200
+ * @typedef {object} IdleDeadline
1201
+ * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
1202
+ * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
1203
+ */
1204
+
1205
+ /**
1206
+ * Queues a function to be called during a browser's idle periods
1207
+ *
1208
+ * @callback RequestIdleCallback
1209
+ * @param {function(IdleDeadline)} callback
1210
+ * @param {{timeout: number}} options - an options object
1211
+ * @returns {number} the id
1212
+ */
1213
+
1214
+ /**
1215
+ * @callback NextTick
1216
+ * @param {VoidVarArgsFunc} callback - the callback to run
1217
+ * @param {...*} arguments - optional arguments to call the callback with
1218
+ * @returns {void}
1219
+ */
1220
+
1221
+ /**
1222
+ * @callback SetImmediate
1223
+ * @param {VoidVarArgsFunc} callback - the callback to run
1224
+ * @param {...*} arguments - optional arguments to call the callback with
1225
+ * @returns {NodeImmediate}
1226
+ */
1227
+
1228
+ /**
1229
+ * @callback VoidVarArgsFunc
1230
+ * @param {...*} callback - the callback to run
1231
+ * @returns {void}
1232
+ */
1233
+
1234
+ /**
1235
+ * @typedef RequestAnimationFrame
1236
+ * @property {function(number):void} requestAnimationFrame
1237
+ * @returns {number} - the id
1238
+ */
1239
+
1240
+ /**
1241
+ * @typedef Performance
1242
+ * @property {function(): number} now
1243
+ */
1244
+
1245
+ /* eslint-disable jsdoc/require-property-description */
1246
+ /**
1247
+ * @typedef {object} Clock
1248
+ * @property {number} now - the current time
1249
+ * @property {Date} Date - the Date constructor
1250
+ * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
1251
+ * @property {RequestIdleCallback} requestIdleCallback
1252
+ * @property {function(number):void} cancelIdleCallback
1253
+ * @property {setTimeout} setTimeout
1254
+ * @property {clearTimeout} clearTimeout
1255
+ * @property {NextTick} nextTick
1256
+ * @property {queueMicrotask} queueMicrotask
1257
+ * @property {setInterval} setInterval
1258
+ * @property {clearInterval} clearInterval
1259
+ * @property {SetImmediate} setImmediate
1260
+ * @property {function(NodeImmediate):void} clearImmediate
1261
+ * @property {function():number} countTimers
1262
+ * @property {RequestAnimationFrame} requestAnimationFrame
1263
+ * @property {function(number):void} cancelAnimationFrame
1264
+ * @property {function():void} runMicrotasks
1265
+ * @property {function(string | number): number} tick
1266
+ * @property {function(string | number): Promise<number>} tickAsync
1267
+ * @property {function(): number} next
1268
+ * @property {function(): Promise<number>} nextAsync
1269
+ * @property {function(): number} runAll
1270
+ * @property {function(): number} runToFrame
1271
+ * @property {function(): Promise<number>} runAllAsync
1272
+ * @property {function(): number} runToLast
1273
+ * @property {function(): Promise<number>} runToLastAsync
1274
+ * @property {function(): void} reset
1275
+ * @property {function(number | Date): void} setSystemTime
1276
+ * @property {function(number): void} jump
1277
+ * @property {Performance} performance
1278
+ * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
1279
+ * @property {function(): void} uninstall Uninstall the clock.
1280
+ * @property {Function[]} methods - the methods that are faked
1281
+ * @property {boolean} [shouldClearNativeTimers] inherited from config
1282
+ * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
1283
+ */
1284
+ /* eslint-enable jsdoc/require-property-description */
1285
+
1286
+ /**
1287
+ * Configuration object for the `install` method.
1288
+ *
1289
+ * @typedef {object} Config
1290
+ * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
1291
+ * @property {string[]} [toFake] names of the methods that should be faked.
1292
+ * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
1293
+ * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
1294
+ * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
1295
+ * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
1296
+ */
1297
+
1298
+ /* eslint-disable jsdoc/require-property-description */
1299
+ /**
1300
+ * The internal structure to describe a scheduled fake timer
1301
+ *
1302
+ * @typedef {object} Timer
1303
+ * @property {Function} func
1304
+ * @property {*[]} args
1305
+ * @property {number} delay
1306
+ * @property {number} callAt
1307
+ * @property {number} createdAt
1308
+ * @property {boolean} immediate
1309
+ * @property {number} id
1310
+ * @property {Error} [error]
1311
+ */
1312
+
1313
+ /**
1314
+ * A Node timer
1315
+ *
1316
+ * @typedef {object} NodeImmediate
1317
+ * @property {function(): boolean} hasRef
1318
+ * @property {function(): NodeImmediate} ref
1319
+ * @property {function(): NodeImmediate} unref
1320
+ */
1321
+ /* eslint-enable jsdoc/require-property-description */
1322
+
1323
+ /* eslint-disable complexity */
1324
+
1325
+ /**
1326
+ * Mocks available features in the specified global namespace.
1327
+ *
1328
+ * @param {*} _global Namespace to mock (e.g. `window`)
1329
+ * @returns {FakeTimers}
1330
+ */
1331
+ function withGlobal(_global) {
1332
+ const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
1333
+ const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
1334
+ const NOOP = function () {
1335
+ return undefined;
1336
+ };
1337
+ const NOOP_ARRAY = function () {
1338
+ return [];
1339
+ };
1340
+ const timeoutResult = _global.setTimeout(NOOP, 0);
1341
+ const addTimerReturnsObject = typeof timeoutResult === "object";
1342
+ const hrtimePresent =
1343
+ _global.process && typeof _global.process.hrtime === "function";
1344
+ const hrtimeBigintPresent =
1345
+ hrtimePresent && typeof _global.process.hrtime.bigint === "function";
1346
+ const nextTickPresent =
1347
+ _global.process && typeof _global.process.nextTick === "function";
1348
+ const utilPromisify = _global.process && _global.__vitest_required__ && _global.__vitest_required__.util.promisify;
1349
+ const performancePresent =
1350
+ _global.performance && typeof _global.performance.now === "function";
1351
+ const hasPerformancePrototype =
1352
+ _global.Performance &&
1353
+ (typeof _global.Performance).match(/^(function|object)$/);
1354
+ const hasPerformanceConstructorPrototype =
1355
+ _global.performance &&
1356
+ _global.performance.constructor &&
1357
+ _global.performance.constructor.prototype;
1358
+ const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask");
1359
+ const requestAnimationFramePresent =
1360
+ _global.requestAnimationFrame &&
1361
+ typeof _global.requestAnimationFrame === "function";
1362
+ const cancelAnimationFramePresent =
1363
+ _global.cancelAnimationFrame &&
1364
+ typeof _global.cancelAnimationFrame === "function";
1365
+ const requestIdleCallbackPresent =
1366
+ _global.requestIdleCallback &&
1367
+ typeof _global.requestIdleCallback === "function";
1368
+ const cancelIdleCallbackPresent =
1369
+ _global.cancelIdleCallback &&
1370
+ typeof _global.cancelIdleCallback === "function";
1371
+ const setImmediatePresent =
1372
+ _global.setImmediate && typeof _global.setImmediate === "function";
1373
+ const intlPresent = _global.Intl && typeof _global.Intl === "object";
1374
+
1375
+ _global.clearTimeout(timeoutResult);
1376
+
1377
+ const NativeDate = _global.Date;
1378
+ const NativeIntl = _global.Intl;
1379
+ let uniqueTimerId = idCounterStart;
1380
+
1381
+ /**
1382
+ * @param {number} num
1383
+ * @returns {boolean}
1384
+ */
1385
+ function isNumberFinite(num) {
1386
+ if (Number.isFinite) {
1387
+ return Number.isFinite(num);
1388
+ }
1389
+
1390
+ return isFinite(num);
1391
+ }
1392
+
1393
+ let isNearInfiniteLimit = false;
1394
+
1395
+ /**
1396
+ * @param {Clock} clock
1397
+ * @param {number} i
1398
+ */
1399
+ function checkIsNearInfiniteLimit(clock, i) {
1400
+ if (clock.loopLimit && i === clock.loopLimit - 1) {
1401
+ isNearInfiniteLimit = true;
1402
+ }
1403
+ }
1404
+
1405
+ /**
1406
+ *
1407
+ */
1408
+ function resetIsNearInfiniteLimit() {
1409
+ isNearInfiniteLimit = false;
1410
+ }
1411
+
1412
+ /**
1413
+ * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1414
+ * number of milliseconds. This is used to support human-readable strings passed
1415
+ * to clock.tick()
1416
+ *
1417
+ * @param {string} str
1418
+ * @returns {number}
1419
+ */
1420
+ function parseTime(str) {
1421
+ if (!str) {
1422
+ return 0;
1423
+ }
1424
+
1425
+ const strings = str.split(":");
1426
+ const l = strings.length;
1427
+ let i = l;
1428
+ let ms = 0;
1429
+ let parsed;
1430
+
1431
+ if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
1432
+ throw new Error(
1433
+ "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
1434
+ );
1435
+ }
1436
+
1437
+ while (i--) {
1438
+ parsed = parseInt(strings[i], 10);
1439
+
1440
+ if (parsed >= 60) {
1441
+ throw new Error(`Invalid time ${str}`);
1442
+ }
1443
+
1444
+ ms += parsed * Math.pow(60, l - i - 1);
1445
+ }
1446
+
1447
+ return ms * 1000;
1448
+ }
1449
+
1450
+ /**
1451
+ * Get the decimal part of the millisecond value as nanoseconds
1452
+ *
1453
+ * @param {number} msFloat the number of milliseconds
1454
+ * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1455
+ *
1456
+ * Example: nanoRemainer(123.456789) -> 456789
1457
+ */
1458
+ function nanoRemainder(msFloat) {
1459
+ const modulo = 1e6;
1460
+ const remainder = (msFloat * 1e6) % modulo;
1461
+ const positiveRemainder =
1462
+ remainder < 0 ? remainder + modulo : remainder;
1463
+
1464
+ return Math.floor(positiveRemainder);
1465
+ }
1466
+
1467
+ /**
1468
+ * Used to grok the `now` parameter to createClock.
1469
+ *
1470
+ * @param {Date|number} epoch the system time
1471
+ * @returns {number}
1472
+ */
1473
+ function getEpoch(epoch) {
1474
+ if (!epoch) {
1475
+ return 0;
1476
+ }
1477
+ if (typeof epoch.getTime === "function") {
1478
+ return epoch.getTime();
1479
+ }
1480
+ if (typeof epoch === "number") {
1481
+ return epoch;
1482
+ }
1483
+ throw new TypeError("now should be milliseconds since UNIX epoch");
1484
+ }
1485
+
1486
+ /**
1487
+ * @param {number} from
1488
+ * @param {number} to
1489
+ * @param {Timer} timer
1490
+ * @returns {boolean}
1491
+ */
1492
+ function inRange(from, to, timer) {
1493
+ return timer && timer.callAt >= from && timer.callAt <= to;
1494
+ }
1495
+
1496
+ /**
1497
+ * @param {Clock} clock
1498
+ * @param {Timer} job
1499
+ */
1500
+ function getInfiniteLoopError(clock, job) {
1501
+ const infiniteLoopError = new Error(
1502
+ `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`
1503
+ );
1504
+
1505
+ if (!job.error) {
1506
+ return infiniteLoopError;
1507
+ }
1508
+
1509
+ // pattern never matched in Node
1510
+ const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1511
+ let clockMethodPattern = new RegExp(
1512
+ String(Object.keys(clock).join("|"))
1513
+ );
1514
+
1515
+ if (addTimerReturnsObject) {
1516
+ // node.js environment
1517
+ clockMethodPattern = new RegExp(
1518
+ `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`
1519
+ );
1520
+ }
1521
+
1522
+ let matchedLineIndex = -1;
1523
+ job.error.stack.split("\n").some(function (line, i) {
1524
+ // If we've matched a computed target line (e.g. setTimeout) then we
1525
+ // don't need to look any further. Return true to stop iterating.
1526
+ const matchedComputedTarget = line.match(computedTargetPattern);
1527
+ /* istanbul ignore if */
1528
+ if (matchedComputedTarget) {
1529
+ matchedLineIndex = i;
1530
+ return true;
1531
+ }
1532
+
1533
+ // If we've matched a clock method line, then there may still be
1534
+ // others further down the trace. Return false to keep iterating.
1535
+ const matchedClockMethod = line.match(clockMethodPattern);
1536
+ if (matchedClockMethod) {
1537
+ matchedLineIndex = i;
1538
+ return false;
1539
+ }
1540
+
1541
+ // If we haven't matched anything on this line, but we matched
1542
+ // previously and set the matched line index, then we can stop.
1543
+ // If we haven't matched previously, then we should keep iterating.
1544
+ return matchedLineIndex >= 0;
1545
+ });
1546
+
1547
+ const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
1548
+ job.func.name || "anonymous"
1549
+ }\n${job.error.stack
1550
+ .split("\n")
1551
+ .slice(matchedLineIndex + 1)
1552
+ .join("\n")}`;
1553
+
1554
+ try {
1555
+ Object.defineProperty(infiniteLoopError, "stack", {
1556
+ value: stack,
1557
+ });
1558
+ } catch (e) {
1559
+ // noop
1560
+ }
1561
+
1562
+ return infiniteLoopError;
1563
+ }
1564
+
1565
+ /**
1566
+ * @param {Date} target
1567
+ * @param {Date} source
1568
+ * @returns {Date} the target after modifications
1569
+ */
1570
+ function mirrorDateProperties(target, source) {
1571
+ let prop;
1572
+ for (prop in source) {
1573
+ if (source.hasOwnProperty(prop)) {
1574
+ target[prop] = source[prop];
1575
+ }
1576
+ }
1577
+
1578
+ // set special now implementation
1579
+ if (source.now) {
1580
+ target.now = function now() {
1581
+ return target.clock.now;
1582
+ };
1583
+ } else {
1584
+ delete target.now;
1585
+ }
1586
+
1587
+ // set special toSource implementation
1588
+ if (source.toSource) {
1589
+ target.toSource = function toSource() {
1590
+ return source.toSource();
1591
+ };
1592
+ } else {
1593
+ delete target.toSource;
1594
+ }
1595
+
1596
+ // set special toString implementation
1597
+ target.toString = function toString() {
1598
+ return source.toString();
1599
+ };
1600
+
1601
+ target.prototype = source.prototype;
1602
+ target.parse = source.parse;
1603
+ target.UTC = source.UTC;
1604
+ target.prototype.toUTCString = source.prototype.toUTCString;
1605
+ target.isFake = true;
1606
+
1607
+ return target;
1608
+ }
1609
+
1610
+ //eslint-disable-next-line jsdoc/require-jsdoc
1611
+ function createDate() {
1612
+ /**
1613
+ * @param {number} year
1614
+ * @param {number} month
1615
+ * @param {number} date
1616
+ * @param {number} hour
1617
+ * @param {number} minute
1618
+ * @param {number} second
1619
+ * @param {number} ms
1620
+ * @returns {Date}
1621
+ */
1622
+ function ClockDate(year, month, date, hour, minute, second, ms) {
1623
+ // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
1624
+ // This remains so in the 10th edition of 2019 as well.
1625
+ if (!(this instanceof ClockDate)) {
1626
+ return new NativeDate(ClockDate.clock.now).toString();
1627
+ }
1628
+
1629
+ // if Date is called as a constructor with 'new' keyword
1630
+ // Defensive and verbose to avoid potential harm in passing
1631
+ // explicit undefined when user does not pass argument
1632
+ switch (arguments.length) {
1633
+ case 0:
1634
+ return new NativeDate(ClockDate.clock.now);
1635
+ case 1:
1636
+ return new NativeDate(year);
1637
+ case 2:
1638
+ return new NativeDate(year, month);
1639
+ case 3:
1640
+ return new NativeDate(year, month, date);
1641
+ case 4:
1642
+ return new NativeDate(year, month, date, hour);
1643
+ case 5:
1644
+ return new NativeDate(year, month, date, hour, minute);
1645
+ case 6:
1646
+ return new NativeDate(
1647
+ year,
1648
+ month,
1649
+ date,
1650
+ hour,
1651
+ minute,
1652
+ second
1653
+ );
1654
+ default:
1655
+ return new NativeDate(
1656
+ year,
1657
+ month,
1658
+ date,
1659
+ hour,
1660
+ minute,
1661
+ second,
1662
+ ms
1663
+ );
1664
+ }
1665
+ }
1666
+
1667
+ return mirrorDateProperties(ClockDate, NativeDate);
1668
+ }
1669
+
1670
+ //eslint-disable-next-line jsdoc/require-jsdoc
1671
+ function createIntl() {
1672
+ const ClockIntl = { ...NativeIntl };
1673
+
1674
+ ClockIntl.DateTimeFormat = function (...args) {
1675
+ const realFormatter = new NativeIntl.DateTimeFormat(...args);
1676
+ const formatter = {};
1677
+
1678
+ ["formatRange", "formatRangeToParts", "resolvedOptions"].forEach(
1679
+ (method) => {
1680
+ formatter[method] =
1681
+ realFormatter[method].bind(realFormatter);
1682
+ }
1683
+ );
1684
+
1685
+ ["format", "formatToParts"].forEach((method) => {
1686
+ formatter[method] = function (date) {
1687
+ return realFormatter[method](date || ClockIntl.clock.now);
1688
+ };
1689
+ });
1690
+
1691
+ return formatter;
1692
+ };
1693
+
1694
+ ClockIntl.DateTimeFormat.prototype = Object.create(
1695
+ NativeIntl.DateTimeFormat.prototype
1696
+ );
1697
+
1698
+ ClockIntl.DateTimeFormat.supportedLocalesOf =
1699
+ NativeIntl.DateTimeFormat.supportedLocalesOf;
1700
+
1701
+ return ClockIntl;
1702
+ }
1703
+
1704
+ //eslint-disable-next-line jsdoc/require-jsdoc
1705
+ function enqueueJob(clock, job) {
1706
+ // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
1707
+ if (!clock.jobs) {
1708
+ clock.jobs = [];
1709
+ }
1710
+ clock.jobs.push(job);
1711
+ }
1712
+
1713
+ //eslint-disable-next-line jsdoc/require-jsdoc
1714
+ function runJobs(clock) {
1715
+ // runs all microtick-deferred tasks - ecma262/#sec-runjobs
1716
+ if (!clock.jobs) {
1717
+ return;
1718
+ }
1719
+ for (let i = 0; i < clock.jobs.length; i++) {
1720
+ const job = clock.jobs[i];
1721
+ job.func.apply(null, job.args);
1722
+
1723
+ checkIsNearInfiniteLimit(clock, i);
1724
+ if (clock.loopLimit && i > clock.loopLimit) {
1725
+ throw getInfiniteLoopError(clock, job);
1726
+ }
1727
+ }
1728
+ resetIsNearInfiniteLimit();
1729
+ clock.jobs = [];
1730
+ }
1731
+
1732
+ /**
1733
+ * @param {Clock} clock
1734
+ * @param {Timer} timer
1735
+ * @returns {number} id of the created timer
1736
+ */
1737
+ function addTimer(clock, timer) {
1738
+ if (timer.func === undefined) {
1739
+ throw new Error("Callback must be provided to timer calls");
1740
+ }
1741
+
1742
+ if (addTimerReturnsObject) {
1743
+ // Node.js environment
1744
+ if (typeof timer.func !== "function") {
1745
+ throw new TypeError(
1746
+ `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${
1747
+ timer.func
1748
+ } of type ${typeof timer.func}`
1749
+ );
1750
+ }
1751
+ }
1752
+
1753
+ if (isNearInfiniteLimit) {
1754
+ timer.error = new Error();
1755
+ }
1756
+
1757
+ timer.type = timer.immediate ? "Immediate" : "Timeout";
1758
+
1759
+ if (timer.hasOwnProperty("delay")) {
1760
+ if (typeof timer.delay !== "number") {
1761
+ timer.delay = parseInt(timer.delay, 10);
1762
+ }
1763
+
1764
+ if (!isNumberFinite(timer.delay)) {
1765
+ timer.delay = 0;
1766
+ }
1767
+ timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1768
+ timer.delay = Math.max(0, timer.delay);
1769
+ }
1770
+
1771
+ if (timer.hasOwnProperty("interval")) {
1772
+ timer.type = "Interval";
1773
+ timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1774
+ }
1775
+
1776
+ if (timer.hasOwnProperty("animation")) {
1777
+ timer.type = "AnimationFrame";
1778
+ timer.animation = true;
1779
+ }
1780
+
1781
+ if (timer.hasOwnProperty("idleCallback")) {
1782
+ timer.type = "IdleCallback";
1783
+ timer.idleCallback = true;
1784
+ }
1785
+
1786
+ if (!clock.timers) {
1787
+ clock.timers = {};
1788
+ }
1789
+
1790
+ timer.id = uniqueTimerId++;
1791
+ timer.createdAt = clock.now;
1792
+ timer.callAt =
1793
+ clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1794
+
1795
+ clock.timers[timer.id] = timer;
1796
+
1797
+ if (addTimerReturnsObject) {
1798
+ const res = {
1799
+ refed: true,
1800
+ ref: function () {
1801
+ this.refed = true;
1802
+ return res;
1803
+ },
1804
+ unref: function () {
1805
+ this.refed = false;
1806
+ return res;
1807
+ },
1808
+ hasRef: function () {
1809
+ return this.refed;
1810
+ },
1811
+ refresh: function () {
1812
+ timer.callAt =
1813
+ clock.now +
1814
+ (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1815
+
1816
+ // it _might_ have been removed, but if not the assignment is perfectly fine
1817
+ clock.timers[timer.id] = timer;
1818
+
1819
+ return res;
1820
+ },
1821
+ [Symbol.toPrimitive]: function () {
1822
+ return timer.id;
1823
+ },
1824
+ };
1825
+ return res;
1826
+ }
1827
+
1828
+ return timer.id;
1829
+ }
1830
+
1831
+ /* eslint consistent-return: "off" */
1832
+ /**
1833
+ * Timer comparitor
1834
+ *
1835
+ * @param {Timer} a
1836
+ * @param {Timer} b
1837
+ * @returns {number}
1838
+ */
1839
+ function compareTimers(a, b) {
1840
+ // Sort first by absolute timing
1841
+ if (a.callAt < b.callAt) {
1842
+ return -1;
1843
+ }
1844
+ if (a.callAt > b.callAt) {
1845
+ return 1;
1846
+ }
1847
+
1848
+ // Sort next by immediate, immediate timers take precedence
1849
+ if (a.immediate && !b.immediate) {
1850
+ return -1;
1851
+ }
1852
+ if (!a.immediate && b.immediate) {
1853
+ return 1;
1854
+ }
1855
+
1856
+ // Sort next by creation time, earlier-created timers take precedence
1857
+ if (a.createdAt < b.createdAt) {
1858
+ return -1;
1859
+ }
1860
+ if (a.createdAt > b.createdAt) {
1861
+ return 1;
1862
+ }
1863
+
1864
+ // Sort next by id, lower-id timers take precedence
1865
+ if (a.id < b.id) {
1866
+ return -1;
1867
+ }
1868
+ if (a.id > b.id) {
1869
+ return 1;
1870
+ }
1871
+
1872
+ // As timer ids are unique, no fallback `0` is necessary
1873
+ }
1874
+
1875
+ /**
1876
+ * @param {Clock} clock
1877
+ * @param {number} from
1878
+ * @param {number} to
1879
+ * @returns {Timer}
1880
+ */
1881
+ function firstTimerInRange(clock, from, to) {
1882
+ const timers = clock.timers;
1883
+ let timer = null;
1884
+ let id, isInRange;
1885
+
1886
+ for (id in timers) {
1887
+ if (timers.hasOwnProperty(id)) {
1888
+ isInRange = inRange(from, to, timers[id]);
1889
+
1890
+ if (
1891
+ isInRange &&
1892
+ (!timer || compareTimers(timer, timers[id]) === 1)
1893
+ ) {
1894
+ timer = timers[id];
1895
+ }
1896
+ }
1897
+ }
1898
+
1899
+ return timer;
1900
+ }
1901
+
1902
+ /**
1903
+ * @param {Clock} clock
1904
+ * @returns {Timer}
1905
+ */
1906
+ function firstTimer(clock) {
1907
+ const timers = clock.timers;
1908
+ let timer = null;
1909
+ let id;
1910
+
1911
+ for (id in timers) {
1912
+ if (timers.hasOwnProperty(id)) {
1913
+ if (!timer || compareTimers(timer, timers[id]) === 1) {
1914
+ timer = timers[id];
1915
+ }
1916
+ }
1917
+ }
1918
+
1919
+ return timer;
1920
+ }
1921
+
1922
+ /**
1923
+ * @param {Clock} clock
1924
+ * @returns {Timer}
1925
+ */
1926
+ function lastTimer(clock) {
1927
+ const timers = clock.timers;
1928
+ let timer = null;
1929
+ let id;
1930
+
1931
+ for (id in timers) {
1932
+ if (timers.hasOwnProperty(id)) {
1933
+ if (!timer || compareTimers(timer, timers[id]) === -1) {
1934
+ timer = timers[id];
1935
+ }
1936
+ }
1937
+ }
1938
+
1939
+ return timer;
1940
+ }
1941
+
1942
+ /**
1943
+ * @param {Clock} clock
1944
+ * @param {Timer} timer
1945
+ */
1946
+ function callTimer(clock, timer) {
1947
+ if (typeof timer.interval === "number") {
1948
+ clock.timers[timer.id].callAt += timer.interval;
1949
+ } else {
1950
+ delete clock.timers[timer.id];
1951
+ }
1952
+
1953
+ if (typeof timer.func === "function") {
1954
+ timer.func.apply(null, timer.args);
1955
+ } else {
1956
+ /* eslint no-eval: "off" */
1957
+ const eval2 = eval;
1958
+ (function () {
1959
+ eval2(timer.func);
1960
+ })();
1961
+ }
1962
+ }
1963
+
1964
+ /**
1965
+ * Gets clear handler name for a given timer type
1966
+ *
1967
+ * @param {string} ttype
1968
+ */
1969
+ function getClearHandler(ttype) {
1970
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1971
+ return `cancel${ttype}`;
1972
+ }
1973
+ return `clear${ttype}`;
1974
+ }
1975
+
1976
+ /**
1977
+ * Gets schedule handler name for a given timer type
1978
+ *
1979
+ * @param {string} ttype
1980
+ */
1981
+ function getScheduleHandler(ttype) {
1982
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1983
+ return `request${ttype}`;
1984
+ }
1985
+ return `set${ttype}`;
1986
+ }
1987
+
1988
+ /**
1989
+ * Creates an anonymous function to warn only once
1990
+ */
1991
+ function createWarnOnce() {
1992
+ let calls = 0;
1993
+ return function (msg) {
1994
+ // eslint-disable-next-line
1995
+ !calls++ && console.warn(msg);
1996
+ };
1997
+ }
1998
+ const warnOnce = createWarnOnce();
1999
+
2000
+ /**
2001
+ * @param {Clock} clock
2002
+ * @param {number} timerId
2003
+ * @param {string} ttype
2004
+ */
2005
+ function clearTimer(clock, timerId, ttype) {
2006
+ if (!timerId) {
2007
+ // null appears to be allowed in most browsers, and appears to be
2008
+ // relied upon by some libraries, like Bootstrap carousel
2009
+ return;
2010
+ }
2011
+
2012
+ if (!clock.timers) {
2013
+ clock.timers = {};
2014
+ }
2015
+
2016
+ // in Node, the ID is stored as the primitive value for `Timeout` objects
2017
+ // for `Immediate` objects, no ID exists, so it gets coerced to NaN
2018
+ const id = Number(timerId);
2019
+
2020
+ if (Number.isNaN(id) || id < idCounterStart) {
2021
+ const handlerName = getClearHandler(ttype);
2022
+
2023
+ if (clock.shouldClearNativeTimers === true) {
2024
+ const nativeHandler = clock[`_${handlerName}`];
2025
+ return typeof nativeHandler === "function"
2026
+ ? nativeHandler(timerId)
2027
+ : undefined;
2028
+ }
2029
+ warnOnce(
2030
+ `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` +
2031
+ "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`."
2032
+ );
2033
+ }
2034
+
2035
+ if (clock.timers.hasOwnProperty(id)) {
2036
+ // check that the ID matches a timer of the correct type
2037
+ const timer = clock.timers[id];
2038
+ if (
2039
+ timer.type === ttype ||
2040
+ (timer.type === "Timeout" && ttype === "Interval") ||
2041
+ (timer.type === "Interval" && ttype === "Timeout")
2042
+ ) {
2043
+ delete clock.timers[id];
2044
+ } else {
2045
+ const clear = getClearHandler(ttype);
2046
+ const schedule = getScheduleHandler(timer.type);
2047
+ throw new Error(
2048
+ `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`
2049
+ );
2050
+ }
2051
+ }
2052
+ }
2053
+
2054
+ /**
2055
+ * @param {Clock} clock
2056
+ * @param {Config} config
2057
+ * @returns {Timer[]}
2058
+ */
2059
+ function uninstall(clock, config) {
2060
+ let method, i, l;
2061
+ const installedHrTime = "_hrtime";
2062
+ const installedNextTick = "_nextTick";
2063
+
2064
+ for (i = 0, l = clock.methods.length; i < l; i++) {
2065
+ method = clock.methods[i];
2066
+ if (method === "hrtime" && _global.process) {
2067
+ _global.process.hrtime = clock[installedHrTime];
2068
+ } else if (method === "nextTick" && _global.process) {
2069
+ _global.process.nextTick = clock[installedNextTick];
2070
+ } else if (method === "performance") {
2071
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2072
+ clock,
2073
+ `_${method}`
2074
+ );
2075
+ if (
2076
+ originalPerfDescriptor &&
2077
+ originalPerfDescriptor.get &&
2078
+ !originalPerfDescriptor.set
2079
+ ) {
2080
+ Object.defineProperty(
2081
+ _global,
2082
+ method,
2083
+ originalPerfDescriptor
2084
+ );
2085
+ } else if (originalPerfDescriptor.configurable) {
2086
+ _global[method] = clock[`_${method}`];
2087
+ }
2088
+ } else {
2089
+ if (_global[method] && _global[method].hadOwnProperty) {
2090
+ _global[method] = clock[`_${method}`];
2091
+ } else {
2092
+ try {
2093
+ delete _global[method];
2094
+ } catch (ignore) {
2095
+ /* eslint no-empty: "off" */
2096
+ }
2097
+ }
2098
+ }
2099
+ if (clock.timersModuleMethods !== undefined) {
2100
+ for (let j = 0; j < clock.timersModuleMethods.length; j++) {
2101
+ const entry = clock.timersModuleMethods[j];
2102
+ timersModule[entry.methodName] = entry.original;
2103
+ }
2104
+ }
2105
+ }
2106
+
2107
+ if (config.shouldAdvanceTime === true) {
2108
+ _global.clearInterval(clock.attachedInterval);
2109
+ }
2110
+
2111
+ // Prevent multiple executions which will completely remove these props
2112
+ clock.methods = [];
2113
+
2114
+ // return pending timers, to enable checking what timers remained on uninstall
2115
+ if (!clock.timers) {
2116
+ return [];
2117
+ }
2118
+ return Object.keys(clock.timers).map(function mapper(key) {
2119
+ return clock.timers[key];
2120
+ });
2121
+ }
2122
+
2123
+ /**
2124
+ * @param {object} target the target containing the method to replace
2125
+ * @param {string} method the keyname of the method on the target
2126
+ * @param {Clock} clock
2127
+ */
2128
+ function hijackMethod(target, method, clock) {
2129
+ clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
2130
+ target,
2131
+ method
2132
+ );
2133
+ clock[`_${method}`] = target[method];
2134
+
2135
+ if (method === "Date") {
2136
+ const date = mirrorDateProperties(clock[method], target[method]);
2137
+ target[method] = date;
2138
+ } else if (method === "Intl") {
2139
+ target[method] = clock[method];
2140
+ } else if (method === "performance") {
2141
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2142
+ target,
2143
+ method
2144
+ );
2145
+ // JSDOM has a read only performance field so we have to save/copy it differently
2146
+ if (
2147
+ originalPerfDescriptor &&
2148
+ originalPerfDescriptor.get &&
2149
+ !originalPerfDescriptor.set
2150
+ ) {
2151
+ Object.defineProperty(
2152
+ clock,
2153
+ `_${method}`,
2154
+ originalPerfDescriptor
2155
+ );
2156
+
2157
+ const perfDescriptor = Object.getOwnPropertyDescriptor(
2158
+ clock,
2159
+ method
2160
+ );
2161
+ Object.defineProperty(target, method, perfDescriptor);
2162
+ } else {
2163
+ target[method] = clock[method];
2164
+ }
2165
+ } else {
2166
+ target[method] = function () {
2167
+ return clock[method].apply(clock, arguments);
2168
+ };
2169
+
2170
+ Object.defineProperties(
2171
+ target[method],
2172
+ Object.getOwnPropertyDescriptors(clock[method])
2173
+ );
2174
+ }
2175
+
2176
+ target[method].clock = clock;
2177
+ }
2178
+
2179
+ /**
2180
+ * @param {Clock} clock
2181
+ * @param {number} advanceTimeDelta
2182
+ */
2183
+ function doIntervalTick(clock, advanceTimeDelta) {
2184
+ clock.tick(advanceTimeDelta);
2185
+ }
2186
+
2187
+ /**
2188
+ * @typedef {object} Timers
2189
+ * @property {setTimeout} setTimeout
2190
+ * @property {clearTimeout} clearTimeout
2191
+ * @property {setInterval} setInterval
2192
+ * @property {clearInterval} clearInterval
2193
+ * @property {Date} Date
2194
+ * @property {Intl} Intl
2195
+ * @property {SetImmediate=} setImmediate
2196
+ * @property {function(NodeImmediate): void=} clearImmediate
2197
+ * @property {function(number[]):number[]=} hrtime
2198
+ * @property {NextTick=} nextTick
2199
+ * @property {Performance=} performance
2200
+ * @property {RequestAnimationFrame=} requestAnimationFrame
2201
+ * @property {boolean=} queueMicrotask
2202
+ * @property {function(number): void=} cancelAnimationFrame
2203
+ * @property {RequestIdleCallback=} requestIdleCallback
2204
+ * @property {function(number): void=} cancelIdleCallback
2205
+ */
2206
+
2207
+ /** @type {Timers} */
2208
+ const timers = {
2209
+ setTimeout: _global.setTimeout,
2210
+ clearTimeout: _global.clearTimeout,
2211
+ setInterval: _global.setInterval,
2212
+ clearInterval: _global.clearInterval,
2213
+ Date: _global.Date,
2214
+ };
2215
+
2216
+ if (setImmediatePresent) {
2217
+ timers.setImmediate = _global.setImmediate;
2218
+ timers.clearImmediate = _global.clearImmediate;
2219
+ }
2220
+
2221
+ if (hrtimePresent) {
2222
+ timers.hrtime = _global.process.hrtime;
2223
+ }
2224
+
2225
+ if (nextTickPresent) {
2226
+ timers.nextTick = _global.process.nextTick;
2227
+ }
2228
+
2229
+ if (performancePresent) {
2230
+ timers.performance = _global.performance;
2231
+ }
2232
+
2233
+ if (requestAnimationFramePresent) {
2234
+ timers.requestAnimationFrame = _global.requestAnimationFrame;
2235
+ }
2236
+
2237
+ if (queueMicrotaskPresent) {
2238
+ timers.queueMicrotask = true;
2239
+ }
2240
+
2241
+ if (cancelAnimationFramePresent) {
2242
+ timers.cancelAnimationFrame = _global.cancelAnimationFrame;
2243
+ }
2244
+
2245
+ if (requestIdleCallbackPresent) {
2246
+ timers.requestIdleCallback = _global.requestIdleCallback;
2247
+ }
2248
+
2249
+ if (cancelIdleCallbackPresent) {
2250
+ timers.cancelIdleCallback = _global.cancelIdleCallback;
2251
+ }
2252
+
2253
+ if (intlPresent) {
2254
+ timers.Intl = _global.Intl;
2255
+ }
2256
+
2257
+ const originalSetTimeout = _global.setImmediate || _global.setTimeout;
2258
+
2259
+ /**
2260
+ * @param {Date|number} [start] the system time - non-integer values are floored
2261
+ * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
2262
+ * @returns {Clock}
2263
+ */
2264
+ function createClock(start, loopLimit) {
2265
+ // eslint-disable-next-line no-param-reassign
2266
+ start = Math.floor(getEpoch(start));
2267
+ // eslint-disable-next-line no-param-reassign
2268
+ loopLimit = loopLimit || 1000;
2269
+ let nanos = 0;
2270
+ const adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
2271
+
2272
+ if (NativeDate === undefined) {
2273
+ throw new Error(
2274
+ "The global scope doesn't have a `Date` object" +
2275
+ " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
2276
+ );
2277
+ }
2278
+
2279
+ const clock = {
2280
+ now: start,
2281
+ Date: createDate(),
2282
+ loopLimit: loopLimit,
2283
+ };
2284
+
2285
+ clock.Date.clock = clock;
2286
+
2287
+ //eslint-disable-next-line jsdoc/require-jsdoc
2288
+ function getTimeToNextFrame() {
2289
+ return 16 - ((clock.now - start) % 16);
2290
+ }
2291
+
2292
+ //eslint-disable-next-line jsdoc/require-jsdoc
2293
+ function hrtime(prev) {
2294
+ const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
2295
+ const secsSinceStart = Math.floor(millisSinceStart / 1000);
2296
+ const remainderInNanos =
2297
+ (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
2298
+ nanos -
2299
+ adjustedSystemTime[1];
2300
+
2301
+ if (Array.isArray(prev)) {
2302
+ if (prev[1] > 1e9) {
2303
+ throw new TypeError(
2304
+ "Number of nanoseconds can't exceed a billion"
2305
+ );
2306
+ }
2307
+
2308
+ const oldSecs = prev[0];
2309
+ let nanoDiff = remainderInNanos - prev[1];
2310
+ let secDiff = secsSinceStart - oldSecs;
2311
+
2312
+ if (nanoDiff < 0) {
2313
+ nanoDiff += 1e9;
2314
+ secDiff -= 1;
2315
+ }
2316
+
2317
+ return [secDiff, nanoDiff];
2318
+ }
2319
+ return [secsSinceStart, remainderInNanos];
2320
+ }
2321
+
2322
+ function fakePerformanceNow() {
2323
+ const hrt = hrtime();
2324
+ const millis = hrt[0] * 1000 + hrt[1] / 1e6;
2325
+ return millis;
2326
+ }
2327
+
2328
+ if (hrtimeBigintPresent) {
2329
+ hrtime.bigint = function () {
2330
+ const parts = hrtime();
2331
+ return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
2332
+ };
2333
+ }
2334
+
2335
+ if (intlPresent) {
2336
+ clock.Intl = createIntl();
2337
+ clock.Intl.clock = clock;
2338
+ }
2339
+
2340
+ clock.requestIdleCallback = function requestIdleCallback(
2341
+ func,
2342
+ timeout
2343
+ ) {
2344
+ let timeToNextIdlePeriod = 0;
2345
+
2346
+ if (clock.countTimers() > 0) {
2347
+ timeToNextIdlePeriod = 50; // const for now
2348
+ }
2349
+
2350
+ const result = addTimer(clock, {
2351
+ func: func,
2352
+ args: Array.prototype.slice.call(arguments, 2),
2353
+ delay:
2354
+ typeof timeout === "undefined"
2355
+ ? timeToNextIdlePeriod
2356
+ : Math.min(timeout, timeToNextIdlePeriod),
2357
+ idleCallback: true,
2358
+ });
2359
+
2360
+ return Number(result);
2361
+ };
2362
+
2363
+ clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
2364
+ return clearTimer(clock, timerId, "IdleCallback");
2365
+ };
2366
+
2367
+ clock.setTimeout = function setTimeout(func, timeout) {
2368
+ return addTimer(clock, {
2369
+ func: func,
2370
+ args: Array.prototype.slice.call(arguments, 2),
2371
+ delay: timeout,
2372
+ });
2373
+ };
2374
+ if (typeof _global.Promise !== "undefined" && utilPromisify) {
2375
+ clock.setTimeout[utilPromisify.custom] =
2376
+ function promisifiedSetTimeout(timeout, arg) {
2377
+ return new _global.Promise(function setTimeoutExecutor(
2378
+ resolve
2379
+ ) {
2380
+ addTimer(clock, {
2381
+ func: resolve,
2382
+ args: [arg],
2383
+ delay: timeout,
2384
+ });
2385
+ });
2386
+ };
2387
+ }
2388
+
2389
+ clock.clearTimeout = function clearTimeout(timerId) {
2390
+ return clearTimer(clock, timerId, "Timeout");
2391
+ };
2392
+
2393
+ clock.nextTick = function nextTick(func) {
2394
+ return enqueueJob(clock, {
2395
+ func: func,
2396
+ args: Array.prototype.slice.call(arguments, 1),
2397
+ error: isNearInfiniteLimit ? new Error() : null,
2398
+ });
2399
+ };
2400
+
2401
+ clock.queueMicrotask = function queueMicrotask(func) {
2402
+ return clock.nextTick(func); // explicitly drop additional arguments
2403
+ };
2404
+
2405
+ clock.setInterval = function setInterval(func, timeout) {
2406
+ // eslint-disable-next-line no-param-reassign
2407
+ timeout = parseInt(timeout, 10);
2408
+ return addTimer(clock, {
2409
+ func: func,
2410
+ args: Array.prototype.slice.call(arguments, 2),
2411
+ delay: timeout,
2412
+ interval: timeout,
2413
+ });
2414
+ };
2415
+
2416
+ clock.clearInterval = function clearInterval(timerId) {
2417
+ return clearTimer(clock, timerId, "Interval");
2418
+ };
2419
+
2420
+ if (setImmediatePresent) {
2421
+ clock.setImmediate = function setImmediate(func) {
2422
+ return addTimer(clock, {
2423
+ func: func,
2424
+ args: Array.prototype.slice.call(arguments, 1),
2425
+ immediate: true,
2426
+ });
2427
+ };
2428
+
2429
+ if (typeof _global.Promise !== "undefined" && utilPromisify) {
2430
+ clock.setImmediate[utilPromisify.custom] =
2431
+ function promisifiedSetImmediate(arg) {
2432
+ return new _global.Promise(
2433
+ function setImmediateExecutor(resolve) {
2434
+ addTimer(clock, {
2435
+ func: resolve,
2436
+ args: [arg],
2437
+ immediate: true,
2438
+ });
2439
+ }
2440
+ );
2441
+ };
2442
+ }
2443
+
2444
+ clock.clearImmediate = function clearImmediate(timerId) {
2445
+ return clearTimer(clock, timerId, "Immediate");
2446
+ };
2447
+ }
2448
+
2449
+ clock.countTimers = function countTimers() {
2450
+ return (
2451
+ Object.keys(clock.timers || {}).length +
2452
+ (clock.jobs || []).length
2453
+ );
2454
+ };
2455
+
2456
+ clock.requestAnimationFrame = function requestAnimationFrame(func) {
2457
+ const result = addTimer(clock, {
2458
+ func: func,
2459
+ delay: getTimeToNextFrame(),
2460
+ get args() {
2461
+ return [fakePerformanceNow()];
2462
+ },
2463
+ animation: true,
2464
+ });
2465
+
2466
+ return Number(result);
2467
+ };
2468
+
2469
+ clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
2470
+ return clearTimer(clock, timerId, "AnimationFrame");
2471
+ };
2472
+
2473
+ clock.runMicrotasks = function runMicrotasks() {
2474
+ runJobs(clock);
2475
+ };
2476
+
2477
+ /**
2478
+ * @param {number|string} tickValue milliseconds or a string parseable by parseTime
2479
+ * @param {boolean} isAsync
2480
+ * @param {Function} resolve
2481
+ * @param {Function} reject
2482
+ * @returns {number|undefined} will return the new `now` value or nothing for async
2483
+ */
2484
+ function doTick(tickValue, isAsync, resolve, reject) {
2485
+ const msFloat =
2486
+ typeof tickValue === "number"
2487
+ ? tickValue
2488
+ : parseTime(tickValue);
2489
+ const ms = Math.floor(msFloat);
2490
+ const remainder = nanoRemainder(msFloat);
2491
+ let nanosTotal = nanos + remainder;
2492
+ let tickTo = clock.now + ms;
2493
+
2494
+ if (msFloat < 0) {
2495
+ throw new TypeError("Negative ticks are not supported");
2496
+ }
2497
+
2498
+ // adjust for positive overflow
2499
+ if (nanosTotal >= 1e6) {
2500
+ tickTo += 1;
2501
+ nanosTotal -= 1e6;
2502
+ }
2503
+
2504
+ nanos = nanosTotal;
2505
+ let tickFrom = clock.now;
2506
+ let previous = clock.now;
2507
+ // ESLint fails to detect this correctly
2508
+ /* eslint-disable prefer-const */
2509
+ let timer,
2510
+ firstException,
2511
+ oldNow,
2512
+ nextPromiseTick,
2513
+ compensationCheck,
2514
+ postTimerCall;
2515
+ /* eslint-enable prefer-const */
2516
+
2517
+ clock.duringTick = true;
2518
+
2519
+ // perform microtasks
2520
+ oldNow = clock.now;
2521
+ runJobs(clock);
2522
+ if (oldNow !== clock.now) {
2523
+ // compensate for any setSystemTime() call during microtask callback
2524
+ tickFrom += clock.now - oldNow;
2525
+ tickTo += clock.now - oldNow;
2526
+ }
2527
+
2528
+ //eslint-disable-next-line jsdoc/require-jsdoc
2529
+ function doTickInner() {
2530
+ // perform each timer in the requested range
2531
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
2532
+ // eslint-disable-next-line no-unmodified-loop-condition
2533
+ while (timer && tickFrom <= tickTo) {
2534
+ if (clock.timers[timer.id]) {
2535
+ tickFrom = timer.callAt;
2536
+ clock.now = timer.callAt;
2537
+ oldNow = clock.now;
2538
+ try {
2539
+ runJobs(clock);
2540
+ callTimer(clock, timer);
2541
+ } catch (e) {
2542
+ firstException = firstException || e;
2543
+ }
2544
+
2545
+ if (isAsync) {
2546
+ // finish up after native setImmediate callback to allow
2547
+ // all native es6 promises to process their callbacks after
2548
+ // each timer fires.
2549
+ originalSetTimeout(nextPromiseTick);
2550
+ return;
2551
+ }
2552
+
2553
+ compensationCheck();
2554
+ }
2555
+
2556
+ postTimerCall();
2557
+ }
2558
+
2559
+ // perform process.nextTick()s again
2560
+ oldNow = clock.now;
2561
+ runJobs(clock);
2562
+ if (oldNow !== clock.now) {
2563
+ // compensate for any setSystemTime() call during process.nextTick() callback
2564
+ tickFrom += clock.now - oldNow;
2565
+ tickTo += clock.now - oldNow;
2566
+ }
2567
+ clock.duringTick = false;
2568
+
2569
+ // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
2570
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
2571
+ if (timer) {
2572
+ try {
2573
+ clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
2574
+ } catch (e) {
2575
+ firstException = firstException || e;
2576
+ }
2577
+ } else {
2578
+ // no timers remaining in the requested range: move the clock all the way to the end
2579
+ clock.now = tickTo;
2580
+
2581
+ // update nanos
2582
+ nanos = nanosTotal;
2583
+ }
2584
+ if (firstException) {
2585
+ throw firstException;
2586
+ }
2587
+
2588
+ if (isAsync) {
2589
+ resolve(clock.now);
2590
+ } else {
2591
+ return clock.now;
2592
+ }
2593
+ }
2594
+
2595
+ nextPromiseTick =
2596
+ isAsync &&
2597
+ function () {
2598
+ try {
2599
+ compensationCheck();
2600
+ postTimerCall();
2601
+ doTickInner();
2602
+ } catch (e) {
2603
+ reject(e);
2604
+ }
2605
+ };
2606
+
2607
+ compensationCheck = function () {
2608
+ // compensate for any setSystemTime() call during timer callback
2609
+ if (oldNow !== clock.now) {
2610
+ tickFrom += clock.now - oldNow;
2611
+ tickTo += clock.now - oldNow;
2612
+ previous += clock.now - oldNow;
2613
+ }
2614
+ };
2615
+
2616
+ postTimerCall = function () {
2617
+ timer = firstTimerInRange(clock, previous, tickTo);
2618
+ previous = tickFrom;
2619
+ };
2620
+
2621
+ return doTickInner();
2622
+ }
2623
+
2624
+ /**
2625
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2626
+ * @returns {number} will return the new `now` value
2627
+ */
2628
+ clock.tick = function tick(tickValue) {
2629
+ return doTick(tickValue, false);
2630
+ };
2631
+
2632
+ if (typeof _global.Promise !== "undefined") {
2633
+ /**
2634
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2635
+ * @returns {Promise}
2636
+ */
2637
+ clock.tickAsync = function tickAsync(tickValue) {
2638
+ return new _global.Promise(function (resolve, reject) {
2639
+ originalSetTimeout(function () {
2640
+ try {
2641
+ doTick(tickValue, true, resolve, reject);
2642
+ } catch (e) {
2643
+ reject(e);
2644
+ }
2645
+ });
2646
+ });
2647
+ };
2648
+ }
2649
+
2650
+ clock.next = function next() {
2651
+ runJobs(clock);
2652
+ const timer = firstTimer(clock);
2653
+ if (!timer) {
2654
+ return clock.now;
2655
+ }
2656
+
2657
+ clock.duringTick = true;
2658
+ try {
2659
+ clock.now = timer.callAt;
2660
+ callTimer(clock, timer);
2661
+ runJobs(clock);
2662
+ return clock.now;
2663
+ } finally {
2664
+ clock.duringTick = false;
2665
+ }
2666
+ };
2667
+
2668
+ if (typeof _global.Promise !== "undefined") {
2669
+ clock.nextAsync = function nextAsync() {
2670
+ return new _global.Promise(function (resolve, reject) {
2671
+ originalSetTimeout(function () {
2672
+ try {
2673
+ const timer = firstTimer(clock);
2674
+ if (!timer) {
2675
+ resolve(clock.now);
2676
+ return;
2677
+ }
2678
+
2679
+ let err;
2680
+ clock.duringTick = true;
2681
+ clock.now = timer.callAt;
2682
+ try {
2683
+ callTimer(clock, timer);
2684
+ } catch (e) {
2685
+ err = e;
2686
+ }
2687
+ clock.duringTick = false;
2688
+
2689
+ originalSetTimeout(function () {
2690
+ if (err) {
2691
+ reject(err);
2692
+ } else {
2693
+ resolve(clock.now);
2694
+ }
2695
+ });
2696
+ } catch (e) {
2697
+ reject(e);
2698
+ }
2699
+ });
2700
+ });
2701
+ };
2702
+ }
2703
+
2704
+ clock.runAll = function runAll() {
2705
+ let numTimers, i;
2706
+ runJobs(clock);
2707
+ for (i = 0; i < clock.loopLimit; i++) {
2708
+ if (!clock.timers) {
2709
+ resetIsNearInfiniteLimit();
2710
+ return clock.now;
2711
+ }
2712
+
2713
+ numTimers = Object.keys(clock.timers).length;
2714
+ if (numTimers === 0) {
2715
+ resetIsNearInfiniteLimit();
2716
+ return clock.now;
2717
+ }
2718
+
2719
+ clock.next();
2720
+ checkIsNearInfiniteLimit(clock, i);
2721
+ }
2722
+
2723
+ const excessJob = firstTimer(clock);
2724
+ throw getInfiniteLoopError(clock, excessJob);
2725
+ };
2726
+
2727
+ clock.runToFrame = function runToFrame() {
2728
+ return clock.tick(getTimeToNextFrame());
2729
+ };
2730
+
2731
+ if (typeof _global.Promise !== "undefined") {
2732
+ clock.runAllAsync = function runAllAsync() {
2733
+ return new _global.Promise(function (resolve, reject) {
2734
+ let i = 0;
2735
+ /**
2736
+ *
2737
+ */
2738
+ function doRun() {
2739
+ originalSetTimeout(function () {
2740
+ try {
2741
+ let numTimers;
2742
+ if (i < clock.loopLimit) {
2743
+ if (!clock.timers) {
2744
+ resetIsNearInfiniteLimit();
2745
+ resolve(clock.now);
2746
+ return;
2747
+ }
2748
+
2749
+ numTimers = Object.keys(
2750
+ clock.timers
2751
+ ).length;
2752
+ if (numTimers === 0) {
2753
+ resetIsNearInfiniteLimit();
2754
+ resolve(clock.now);
2755
+ return;
2756
+ }
2757
+
2758
+ clock.next();
2759
+
2760
+ i++;
2761
+
2762
+ doRun();
2763
+ checkIsNearInfiniteLimit(clock, i);
2764
+ return;
2765
+ }
2766
+
2767
+ const excessJob = firstTimer(clock);
2768
+ reject(getInfiniteLoopError(clock, excessJob));
2769
+ } catch (e) {
2770
+ reject(e);
2771
+ }
2772
+ });
2773
+ }
2774
+ doRun();
2775
+ });
2776
+ };
2777
+ }
2778
+
2779
+ clock.runToLast = function runToLast() {
2780
+ const timer = lastTimer(clock);
2781
+ if (!timer) {
2782
+ runJobs(clock);
2783
+ return clock.now;
2784
+ }
2785
+
2786
+ return clock.tick(timer.callAt - clock.now);
2787
+ };
2788
+
2789
+ if (typeof _global.Promise !== "undefined") {
2790
+ clock.runToLastAsync = function runToLastAsync() {
2791
+ return new _global.Promise(function (resolve, reject) {
2792
+ originalSetTimeout(function () {
2793
+ try {
2794
+ const timer = lastTimer(clock);
2795
+ if (!timer) {
2796
+ resolve(clock.now);
2797
+ }
2798
+
2799
+ resolve(clock.tickAsync(timer.callAt - clock.now));
2800
+ } catch (e) {
2801
+ reject(e);
2802
+ }
2803
+ });
2804
+ });
2805
+ };
2806
+ }
2807
+
2808
+ clock.reset = function reset() {
2809
+ nanos = 0;
2810
+ clock.timers = {};
2811
+ clock.jobs = [];
2812
+ clock.now = start;
2813
+ };
2814
+
2815
+ clock.setSystemTime = function setSystemTime(systemTime) {
2816
+ // determine time difference
2817
+ const newNow = getEpoch(systemTime);
2818
+ const difference = newNow - clock.now;
2819
+ let id, timer;
2820
+
2821
+ adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
2822
+ adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
2823
+ // update 'system clock'
2824
+ clock.now = newNow;
2825
+ nanos = 0;
2826
+
2827
+ // update timers and intervals to keep them stable
2828
+ for (id in clock.timers) {
2829
+ if (clock.timers.hasOwnProperty(id)) {
2830
+ timer = clock.timers[id];
2831
+ timer.createdAt += difference;
2832
+ timer.callAt += difference;
2833
+ }
2834
+ }
2835
+ };
2836
+
2837
+ /**
2838
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2839
+ * @returns {number} will return the new `now` value
2840
+ */
2841
+ clock.jump = function jump(tickValue) {
2842
+ const msFloat =
2843
+ typeof tickValue === "number"
2844
+ ? tickValue
2845
+ : parseTime(tickValue);
2846
+ const ms = Math.floor(msFloat);
2847
+
2848
+ for (const timer of Object.values(clock.timers)) {
2849
+ if (clock.now + ms > timer.callAt) {
2850
+ timer.callAt = clock.now + ms;
2851
+ }
2852
+ }
2853
+ clock.tick(ms);
2854
+ };
2855
+
2856
+ if (performancePresent) {
2857
+ clock.performance = Object.create(null);
2858
+ clock.performance.now = fakePerformanceNow;
2859
+ }
2860
+
2861
+ if (hrtimePresent) {
2862
+ clock.hrtime = hrtime;
2863
+ }
2864
+
2865
+ return clock;
2866
+ }
2867
+
2868
+ /* eslint-disable complexity */
2869
+
2870
+ /**
2871
+ * @param {Config=} [config] Optional config
2872
+ * @returns {Clock}
2873
+ */
2874
+ function install(config) {
2875
+ if (
2876
+ arguments.length > 1 ||
2877
+ config instanceof Date ||
2878
+ Array.isArray(config) ||
2879
+ typeof config === "number"
2880
+ ) {
2881
+ throw new TypeError(
2882
+ `FakeTimers.install called with ${String(
2883
+ config
2884
+ )} install requires an object parameter`
2885
+ );
2886
+ }
2887
+
2888
+ if (_global.Date.isFake === true) {
2889
+ // Timers are already faked; this is a problem.
2890
+ // Make the user reset timers before continuing.
2891
+ throw new TypeError(
2892
+ "Can't install fake timers twice on the same global object."
2893
+ );
2894
+ }
2895
+
2896
+ // eslint-disable-next-line no-param-reassign
2897
+ config = typeof config !== "undefined" ? config : {};
2898
+ config.shouldAdvanceTime = config.shouldAdvanceTime || false;
2899
+ config.advanceTimeDelta = config.advanceTimeDelta || 20;
2900
+ config.shouldClearNativeTimers =
2901
+ config.shouldClearNativeTimers || false;
2902
+
2903
+ if (config.target) {
2904
+ throw new TypeError(
2905
+ "config.target is no longer supported. Use `withGlobal(target)` instead."
2906
+ );
2907
+ }
2908
+
2909
+ let i, l;
2910
+ const clock = createClock(config.now, config.loopLimit);
2911
+ clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
2912
+
2913
+ clock.uninstall = function () {
2914
+ return uninstall(clock, config);
2915
+ };
2916
+
2917
+ clock.methods = config.toFake || [];
2918
+
2919
+ if (clock.methods.length === 0) {
2920
+ // do not fake nextTick by default - GitHub#126
2921
+ clock.methods = Object.keys(timers).filter(function (key) {
2922
+ return key !== "nextTick" && key !== "queueMicrotask";
2923
+ });
2924
+ }
2925
+
2926
+ if (config.shouldAdvanceTime === true) {
2927
+ const intervalTick = doIntervalTick.bind(
2928
+ null,
2929
+ clock,
2930
+ config.advanceTimeDelta
2931
+ );
2932
+ const intervalId = _global.setInterval(
2933
+ intervalTick,
2934
+ config.advanceTimeDelta
2935
+ );
2936
+ clock.attachedInterval = intervalId;
2937
+ }
2938
+
2939
+ if (clock.methods.includes("performance")) {
2940
+ const proto = (() => {
2941
+ if (hasPerformanceConstructorPrototype) {
2942
+ return _global.performance.constructor.prototype;
2943
+ }
2944
+ if (hasPerformancePrototype) {
2945
+ return _global.Performance.prototype;
2946
+ }
2947
+ })();
2948
+ if (proto) {
2949
+ Object.getOwnPropertyNames(proto).forEach(function (name) {
2950
+ if (name !== "now") {
2951
+ clock.performance[name] =
2952
+ name.indexOf("getEntries") === 0
2953
+ ? NOOP_ARRAY
2954
+ : NOOP;
2955
+ }
2956
+ });
2957
+ } else if ((config.toFake || []).includes("performance")) {
2958
+ // user explicitly tried to fake performance when not present
2959
+ throw new ReferenceError(
2960
+ "non-existent performance object cannot be faked"
2961
+ );
2962
+ }
2963
+ }
2964
+ if (_global === globalObject && timersModule) {
2965
+ clock.timersModuleMethods = [];
2966
+ }
2967
+ for (i = 0, l = clock.methods.length; i < l; i++) {
2968
+ const nameOfMethodToReplace = clock.methods[i];
2969
+ if (nameOfMethodToReplace === "hrtime") {
2970
+ if (
2971
+ _global.process &&
2972
+ typeof _global.process.hrtime === "function"
2973
+ ) {
2974
+ hijackMethod(_global.process, nameOfMethodToReplace, clock);
2975
+ }
2976
+ } else if (nameOfMethodToReplace === "nextTick") {
2977
+ if (
2978
+ _global.process &&
2979
+ typeof _global.process.nextTick === "function"
2980
+ ) {
2981
+ hijackMethod(_global.process, nameOfMethodToReplace, clock);
2982
+ }
2983
+ } else {
2984
+ hijackMethod(_global, nameOfMethodToReplace, clock);
2985
+ }
2986
+ if (
2987
+ clock.timersModuleMethods !== undefined &&
2988
+ timersModule[nameOfMethodToReplace]
2989
+ ) {
2990
+ const original = timersModule[nameOfMethodToReplace];
2991
+ clock.timersModuleMethods.push({
2992
+ methodName: nameOfMethodToReplace,
2993
+ original: original,
2994
+ });
2995
+ timersModule[nameOfMethodToReplace] =
2996
+ _global[nameOfMethodToReplace];
2997
+ }
2998
+ }
2999
+
3000
+ return clock;
3001
+ }
3002
+
3003
+ /* eslint-enable complexity */
3004
+
3005
+ return {
3006
+ timers: timers,
3007
+ createClock: createClock,
3008
+ install: install,
3009
+ withGlobal: withGlobal,
3010
+ };
3011
+ }
3012
+
3013
+ /**
3014
+ * @typedef {object} FakeTimers
3015
+ * @property {Timers} timers
3016
+ * @property {createClock} createClock
3017
+ * @property {Function} install
3018
+ * @property {withGlobal} withGlobal
3019
+ */
3020
+
3021
+ /* eslint-enable complexity */
3022
+
3023
+ /** @type {FakeTimers} */
3024
+ const defaultImplementation = withGlobal(globalObject);
3025
+
3026
+ defaultImplementation.timers;
3027
+ defaultImplementation.createClock;
3028
+ defaultImplementation.install;
3029
+ var withGlobal_1 = withGlobal;
3030
+
3031
+ class FakeTimers {
3032
+ _clock;
3033
+ _fakingTime;
3034
+ _fakingDate;
3035
+ _fakeTimers;
3036
+ _userConfig;
3037
+ _now = RealDate.now;
3038
+ constructor({
3039
+ global,
3040
+ config
3041
+ }) {
3042
+ this._userConfig = config;
3043
+ this._fakingDate = false;
3044
+ this._fakingTime = false;
3045
+ this._fakeTimers = withGlobal_1(global);
3046
+ }
3047
+ clearAllTimers() {
3048
+ if (this._fakingTime)
3049
+ this._clock.reset();
3050
+ }
3051
+ dispose() {
3052
+ this.useRealTimers();
3053
+ }
3054
+ runAllTimers() {
3055
+ if (this._checkFakeTimers())
3056
+ this._clock.runAll();
3057
+ }
3058
+ async runAllTimersAsync() {
3059
+ if (this._checkFakeTimers())
3060
+ await this._clock.runAllAsync();
3061
+ }
3062
+ runOnlyPendingTimers() {
3063
+ if (this._checkFakeTimers())
3064
+ this._clock.runToLast();
3065
+ }
3066
+ async runOnlyPendingTimersAsync() {
3067
+ if (this._checkFakeTimers())
3068
+ await this._clock.runToLastAsync();
3069
+ }
3070
+ advanceTimersToNextTimer(steps = 1) {
3071
+ if (this._checkFakeTimers()) {
3072
+ for (let i = steps; i > 0; i--) {
3073
+ this._clock.next();
3074
+ this._clock.tick(0);
3075
+ if (this._clock.countTimers() === 0)
3076
+ break;
3077
+ }
3078
+ }
3079
+ }
3080
+ async advanceTimersToNextTimerAsync(steps = 1) {
3081
+ if (this._checkFakeTimers()) {
3082
+ for (let i = steps; i > 0; i--) {
3083
+ await this._clock.nextAsync();
3084
+ this._clock.tick(0);
3085
+ if (this._clock.countTimers() === 0)
3086
+ break;
3087
+ }
3088
+ }
3089
+ }
3090
+ advanceTimersByTime(msToRun) {
3091
+ if (this._checkFakeTimers())
3092
+ this._clock.tick(msToRun);
3093
+ }
3094
+ async advanceTimersByTimeAsync(msToRun) {
3095
+ if (this._checkFakeTimers())
3096
+ await this._clock.tickAsync(msToRun);
3097
+ }
3098
+ runAllTicks() {
3099
+ if (this._checkFakeTimers()) {
3100
+ this._clock.runMicrotasks();
3101
+ }
3102
+ }
3103
+ useRealTimers() {
3104
+ if (this._fakingDate) {
3105
+ resetDate();
3106
+ this._fakingDate = false;
3107
+ }
3108
+ if (this._fakingTime) {
3109
+ this._clock.uninstall();
3110
+ this._fakingTime = false;
3111
+ }
3112
+ }
3113
+ useFakeTimers() {
3114
+ var _a, _b;
3115
+ if (this._fakingDate) {
3116
+ throw new Error(
3117
+ '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.'
3118
+ );
3119
+ }
3120
+ if (!this._fakingTime) {
3121
+ const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick");
3122
+ if (((_b = (_a = this._userConfig) == null ? void 0 : _a.toFake) == null ? void 0 : _b.includes("nextTick")) && globalThis.__vitest_worker__.isChildProcess)
3123
+ throw new Error("process.nextTick cannot be mocked inside child_process");
3124
+ this._clock = this._fakeTimers.install({
3125
+ now: Date.now(),
3126
+ toFake,
3127
+ ...this._userConfig
3128
+ });
3129
+ this._fakingTime = true;
3130
+ }
3131
+ }
3132
+ reset() {
3133
+ if (this._checkFakeTimers()) {
3134
+ const { now } = this._clock;
3135
+ this._clock.reset();
3136
+ this._clock.setSystemTime(now);
3137
+ }
3138
+ }
3139
+ setSystemTime(now) {
3140
+ if (this._fakingTime) {
3141
+ this._clock.setSystemTime(now);
3142
+ } else {
3143
+ mockDate(now ?? this.getRealSystemTime());
3144
+ this._fakingDate = true;
3145
+ }
3146
+ }
3147
+ getRealSystemTime() {
3148
+ return this._now();
3149
+ }
3150
+ getTimerCount() {
3151
+ if (this._checkFakeTimers())
3152
+ return this._clock.countTimers();
3153
+ return 0;
3154
+ }
3155
+ configure(config) {
3156
+ this._userConfig = config;
3157
+ }
3158
+ isFakeTimers() {
3159
+ return this._fakingTime;
3160
+ }
3161
+ _checkFakeTimers() {
3162
+ if (!this._fakingTime) {
3163
+ throw new Error(
3164
+ 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.'
3165
+ );
3166
+ }
3167
+ return this._fakingTime;
3168
+ }
3169
+ }
3170
+
3171
+ function copyStackTrace(target, source) {
3172
+ if (source.stack !== void 0)
3173
+ target.stack = source.stack.replace(source.message, target.message);
3174
+ return target;
3175
+ }
3176
+ function waitFor(callback, options = {}) {
3177
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3178
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3179
+ const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3180
+ return new Promise((resolve, reject) => {
3181
+ let lastError;
3182
+ let promiseStatus = "idle";
3183
+ let timeoutId;
3184
+ let intervalId;
3185
+ const onResolve = (result) => {
3186
+ if (timeoutId)
3187
+ clearTimeout(timeoutId);
3188
+ if (intervalId)
3189
+ clearInterval(intervalId);
3190
+ resolve(result);
3191
+ };
3192
+ const handleTimeout = () => {
3193
+ let error = lastError;
3194
+ if (!error)
3195
+ error = copyStackTrace(new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
3196
+ reject(error);
3197
+ };
3198
+ const checkCallback = () => {
3199
+ if (vi.isFakeTimers())
3200
+ vi.advanceTimersByTime(interval);
3201
+ if (promiseStatus === "pending")
3202
+ return;
3203
+ try {
3204
+ const result = callback();
3205
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
3206
+ const thenable = result;
3207
+ promiseStatus = "pending";
3208
+ thenable.then(
3209
+ (resolvedValue) => {
3210
+ promiseStatus = "resolved";
3211
+ onResolve(resolvedValue);
3212
+ },
3213
+ (rejectedValue) => {
3214
+ promiseStatus = "rejected";
3215
+ lastError = rejectedValue;
3216
+ }
3217
+ );
3218
+ } else {
3219
+ onResolve(result);
3220
+ return true;
3221
+ }
3222
+ } catch (error) {
3223
+ lastError = error;
3224
+ }
3225
+ };
3226
+ if (checkCallback() === true)
3227
+ return;
3228
+ timeoutId = setTimeout(handleTimeout, timeout);
3229
+ intervalId = setInterval(checkCallback, interval);
3230
+ });
3231
+ }
3232
+ function waitUntil(callback, options = {}) {
3233
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3234
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3235
+ const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3236
+ return new Promise((resolve, reject) => {
3237
+ let promiseStatus = "idle";
3238
+ let timeoutId;
3239
+ let intervalId;
3240
+ const onReject = (error) => {
3241
+ if (!error)
3242
+ error = copyStackTrace(new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
3243
+ reject(error);
3244
+ };
3245
+ const onResolve = (result) => {
3246
+ if (!result)
3247
+ return;
3248
+ if (timeoutId)
3249
+ clearTimeout(timeoutId);
3250
+ if (intervalId)
3251
+ clearInterval(intervalId);
3252
+ resolve(result);
3253
+ return true;
3254
+ };
3255
+ const checkCallback = () => {
3256
+ if (vi.isFakeTimers())
3257
+ vi.advanceTimersByTime(interval);
3258
+ if (promiseStatus === "pending")
3259
+ return;
3260
+ try {
3261
+ const result = callback();
3262
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
3263
+ const thenable = result;
3264
+ promiseStatus = "pending";
3265
+ thenable.then(
3266
+ (resolvedValue) => {
3267
+ promiseStatus = "resolved";
3268
+ onResolve(resolvedValue);
3269
+ },
3270
+ (rejectedValue) => {
3271
+ promiseStatus = "rejected";
3272
+ onReject(rejectedValue);
3273
+ }
3274
+ );
3275
+ } else {
3276
+ return onResolve(result);
3277
+ }
3278
+ } catch (error) {
3279
+ onReject(error);
3280
+ }
3281
+ };
3282
+ if (checkCallback() === true)
3283
+ return;
3284
+ timeoutId = setTimeout(onReject, timeout);
3285
+ intervalId = setInterval(checkCallback, interval);
3286
+ });
3287
+ }
3288
+
3289
+ function createVitest() {
3290
+ const _mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, {
3291
+ get(_, name) {
3292
+ throw new Error(
3293
+ `Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`
3294
+ );
3295
+ }
3296
+ });
3297
+ let _mockedDate = null;
3298
+ let _config = null;
3299
+ const workerState = getWorkerState();
3300
+ if (!workerState) {
3301
+ const errorMsg = 'Vitest failed to access its internal state.\n\nOne of the following is possible:\n- "vitest" is imported directly without running "vitest" command\n- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
3302
+ throw new Error(errorMsg);
3303
+ }
3304
+ const _timers = new FakeTimers({
3305
+ global: globalThis,
3306
+ config: workerState.config.fakeTimers
3307
+ });
3308
+ const _stubsGlobal = /* @__PURE__ */ new Map();
3309
+ const _stubsEnv = /* @__PURE__ */ new Map();
3310
+ const getImporter = () => {
3311
+ const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 });
3312
+ const importerStack = stackTrace.split("\n")[4];
3313
+ const stack = parseSingleStack(importerStack);
3314
+ return (stack == null ? void 0 : stack.file) || "";
3315
+ };
3316
+ const utils = {
3317
+ useFakeTimers(config) {
3318
+ var _a, _b, _c, _d;
3319
+ const workerState2 = getWorkerState();
3320
+ if (workerState2.isChildProcess) {
3321
+ if (((_a = config == null ? void 0 : config.toFake) == null ? void 0 : _a.includes("nextTick")) || ((_d = (_c = (_b = workerState2.config) == null ? void 0 : _b.fakeTimers) == null ? void 0 : _c.toFake) == null ? void 0 : _d.includes("nextTick"))) {
3322
+ throw new Error(
3323
+ 'vi.useFakeTimers({ toFake: ["nextTick"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.'
3324
+ );
3325
+ }
3326
+ }
3327
+ if (config)
3328
+ _timers.configure({ ...workerState2.config.fakeTimers, ...config });
3329
+ else
3330
+ _timers.configure(workerState2.config.fakeTimers);
3331
+ _timers.useFakeTimers();
3332
+ return utils;
3333
+ },
3334
+ isFakeTimers() {
3335
+ return _timers.isFakeTimers();
3336
+ },
3337
+ useRealTimers() {
3338
+ _timers.useRealTimers();
3339
+ _mockedDate = null;
3340
+ return utils;
3341
+ },
3342
+ runOnlyPendingTimers() {
3343
+ _timers.runOnlyPendingTimers();
3344
+ return utils;
3345
+ },
3346
+ async runOnlyPendingTimersAsync() {
3347
+ await _timers.runOnlyPendingTimersAsync();
3348
+ return utils;
3349
+ },
3350
+ runAllTimers() {
3351
+ _timers.runAllTimers();
3352
+ return utils;
3353
+ },
3354
+ async runAllTimersAsync() {
3355
+ await _timers.runAllTimersAsync();
3356
+ return utils;
3357
+ },
3358
+ runAllTicks() {
3359
+ _timers.runAllTicks();
3360
+ return utils;
3361
+ },
3362
+ advanceTimersByTime(ms) {
3363
+ _timers.advanceTimersByTime(ms);
3364
+ return utils;
3365
+ },
3366
+ async advanceTimersByTimeAsync(ms) {
3367
+ await _timers.advanceTimersByTimeAsync(ms);
3368
+ return utils;
3369
+ },
3370
+ advanceTimersToNextTimer() {
3371
+ _timers.advanceTimersToNextTimer();
3372
+ return utils;
3373
+ },
3374
+ async advanceTimersToNextTimerAsync() {
3375
+ await _timers.advanceTimersToNextTimerAsync();
3376
+ return utils;
3377
+ },
3378
+ getTimerCount() {
3379
+ return _timers.getTimerCount();
3380
+ },
3381
+ setSystemTime(time) {
3382
+ const date = time instanceof Date ? time : new Date(time);
3383
+ _mockedDate = date;
3384
+ _timers.setSystemTime(date);
3385
+ return utils;
3386
+ },
3387
+ getMockedSystemTime() {
3388
+ return _mockedDate;
3389
+ },
3390
+ getRealSystemTime() {
3391
+ return _timers.getRealSystemTime();
3392
+ },
3393
+ clearAllTimers() {
3394
+ _timers.clearAllTimers();
3395
+ return utils;
3396
+ },
3397
+ // mocks
3398
+ spyOn,
3399
+ fn,
3400
+ waitFor,
3401
+ waitUntil,
3402
+ hoisted(factory) {
3403
+ assertTypes(factory, '"vi.hoisted" factory', ["function"]);
3404
+ return factory();
3405
+ },
3406
+ mock(path, factory) {
3407
+ const importer = getImporter();
3408
+ _mocker.queueMock(
3409
+ path,
3410
+ importer,
3411
+ factory ? () => factory(() => _mocker.importActual(path, importer)) : void 0
3412
+ );
3413
+ },
3414
+ unmock(path) {
3415
+ _mocker.queueUnmock(path, getImporter());
3416
+ },
3417
+ doMock(path, factory) {
3418
+ _mocker.queueMock(path, getImporter(), factory);
3419
+ },
3420
+ doUnmock(path) {
3421
+ _mocker.queueUnmock(path, getImporter());
3422
+ },
3423
+ async importActual(path) {
3424
+ return _mocker.importActual(path, getImporter());
3425
+ },
3426
+ async importMock(path) {
3427
+ return _mocker.importMock(path, getImporter());
3428
+ },
3429
+ mocked(item, _options = {}) {
3430
+ return item;
3431
+ },
3432
+ isMockFunction(fn2) {
3433
+ return isMockFunction(fn2);
3434
+ },
3435
+ clearAllMocks() {
3436
+ spies.forEach((spy) => spy.mockClear());
3437
+ return utils;
3438
+ },
3439
+ resetAllMocks() {
3440
+ spies.forEach((spy) => spy.mockReset());
3441
+ return utils;
3442
+ },
3443
+ restoreAllMocks() {
3444
+ spies.forEach((spy) => spy.mockRestore());
3445
+ return utils;
3446
+ },
3447
+ stubGlobal(name, value) {
3448
+ if (!_stubsGlobal.has(name))
3449
+ _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
3450
+ Object.defineProperty(globalThis, name, {
3451
+ value,
3452
+ writable: true,
3453
+ configurable: true,
3454
+ enumerable: true
3455
+ });
3456
+ return utils;
3457
+ },
3458
+ stubEnv(name, value) {
3459
+ if (!_stubsEnv.has(name))
3460
+ _stubsEnv.set(name, process.env[name]);
3461
+ process.env[name] = value;
3462
+ return utils;
3463
+ },
3464
+ unstubAllGlobals() {
3465
+ _stubsGlobal.forEach((original, name) => {
3466
+ if (!original)
3467
+ Reflect.deleteProperty(globalThis, name);
3468
+ else
3469
+ Object.defineProperty(globalThis, name, original);
3470
+ });
3471
+ _stubsGlobal.clear();
3472
+ return utils;
3473
+ },
3474
+ unstubAllEnvs() {
3475
+ _stubsEnv.forEach((original, name) => {
3476
+ if (original === void 0)
3477
+ delete process.env[name];
3478
+ else
3479
+ process.env[name] = original;
3480
+ });
3481
+ _stubsEnv.clear();
3482
+ return utils;
3483
+ },
3484
+ resetModules() {
3485
+ const state = getWorkerState();
3486
+ resetModules(state.moduleCache);
3487
+ return utils;
3488
+ },
3489
+ async dynamicImportSettled() {
3490
+ return waitForImportsToResolve();
3491
+ },
3492
+ setConfig(config) {
3493
+ const state = getWorkerState();
3494
+ if (!_config)
3495
+ _config = { ...state.config };
3496
+ Object.assign(state.config, config);
3497
+ },
3498
+ resetConfig() {
3499
+ if (_config) {
3500
+ const state = getWorkerState();
3501
+ Object.assign(state.config, _config);
3502
+ }
3503
+ }
3504
+ };
3505
+ return utils;
3506
+ }
3507
+ const vitest = createVitest();
3508
+ const vi = vitest;
3509
+
3510
+ export { globalExpect as a, vitest as b, createExpect as c, getSnapshotClient as g, resetModules as r, vi as v };