@powerlines/plugin-react 0.1.636 → 0.1.638

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