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