vitest 0.32.2 → 0.32.4

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