@assistant-ui/react 0.8.15 → 0.8.16

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