@farming-labs/theme 0.0.24 → 0.0.26

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 (53) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +26 -1
  2. package/dist/docs-api.mjs +3 -1
  3. package/dist/docs-layout.mjs +9 -4
  4. package/dist/get-app-dir.d.mts +9 -0
  5. package/dist/get-app-dir.mjs +16 -0
  6. package/dist/get-app-dir.test.d.mts +1 -0
  7. package/dist/get-app-dir.test.mjs +41 -0
  8. package/dist/node_modules/.pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs +77 -0
  9. package/dist/node_modules/.pnpm/@vitest_expect@3.2.4/node_modules/@vitest/expect/dist/index.mjs +1356 -0
  10. package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.mjs +1119 -0
  11. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.mjs +1091 -0
  12. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.mjs +4 -0
  13. package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/utils.mjs +3 -0
  14. package/dist/node_modules/.pnpm/@vitest_snapshot@3.2.4/node_modules/@vitest/snapshot/dist/index.mjs +1821 -0
  15. package/dist/node_modules/.pnpm/@vitest_spy@3.2.4/node_modules/@vitest/spy/dist/index.mjs +171 -0
  16. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.mjs +124 -0
  17. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/diff.mjs +1334 -0
  18. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/error.mjs +105 -0
  19. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.mjs +118 -0
  20. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.mjs +455 -0
  21. package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.mjs +168 -0
  22. package/dist/node_modules/.pnpm/chai@5.3.3/node_modules/chai/index.mjs +3087 -0
  23. package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.mjs +384 -0
  24. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.mjs +11 -0
  25. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.mjs +16 -0
  26. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.mjs +11 -0
  27. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.mjs +15 -0
  28. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.mjs +13 -0
  29. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.mjs +34 -0
  30. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.mjs +12 -0
  31. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.mjs +122 -0
  32. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.mjs +39 -0
  33. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.mjs +99 -0
  34. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.mjs +25 -0
  35. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.mjs +14 -0
  36. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.mjs +21 -0
  37. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.mjs +5 -0
  38. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.mjs +12 -0
  39. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.mjs +18 -0
  40. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.mjs +25 -0
  41. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.mjs +8 -0
  42. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.mjs +30 -0
  43. package/dist/node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs +939 -0
  44. package/dist/node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs +81 -0
  45. package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs +51 -0
  46. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.mjs +81 -0
  47. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.mjs +9 -0
  48. package/dist/node_modules/.pnpm/tinyspy@4.0.4/node_modules/tinyspy/dist/index.mjs +125 -0
  49. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/_commonjsHelpers.BFTU3MAI.mjs +8 -0
  50. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.mjs +50 -0
  51. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/utils.XdZDrNZV.mjs +48 -0
  52. package/dist/node_modules/.pnpm/vitest@3.2.4_@types_debug@4.1.12_@types_node@22.19.11_jiti@2.6.1_lightningcss@1.30.2_terser@5.46.0_yaml@2.8.2/node_modules/vitest/dist/chunks/vi.bdSIJ99Y.mjs +2613 -0
  53. package/package.json +6 -3
@@ -0,0 +1,1091 @@
1
+ import { format, objDisplay } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.mjs";
2
+ import { assertTypes, createDefer, isNegativeNaN, isObject, objectAttr, toArray } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.mjs";
3
+ import { getSafeTimers } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.mjs";
4
+ import { parseSingleStack } from "../../../../../@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.mjs";
5
+ import { stripLiteral } from "../../../../../strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs";
6
+
7
+ //#region ../../node_modules/.pnpm/@vitest+runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js
8
+ var PendingError = class extends Error {
9
+ code = "VITEST_PENDING";
10
+ taskId;
11
+ constructor(message, task, note) {
12
+ super(message);
13
+ this.message = message;
14
+ this.note = note;
15
+ this.taskId = task.id;
16
+ }
17
+ };
18
+ const fnMap = /* @__PURE__ */ new WeakMap();
19
+ const testFixtureMap = /* @__PURE__ */ new WeakMap();
20
+ const hooksMap = /* @__PURE__ */ new WeakMap();
21
+ function setFn(key, fn) {
22
+ fnMap.set(key, fn);
23
+ }
24
+ function setTestFixture(key, fixture) {
25
+ testFixtureMap.set(key, fixture);
26
+ }
27
+ function getTestFixture(key) {
28
+ return testFixtureMap.get(key);
29
+ }
30
+ function setHooks(key, hooks) {
31
+ hooksMap.set(key, hooks);
32
+ }
33
+ function getHooks(key) {
34
+ return hooksMap.get(key);
35
+ }
36
+ function mergeScopedFixtures(testFixtures, scopedFixtures) {
37
+ const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
38
+ map[fixture.prop] = fixture;
39
+ return map;
40
+ }, {});
41
+ const newFixtures = {};
42
+ testFixtures.forEach((fixture) => {
43
+ const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
44
+ newFixtures[useFixture.prop] = useFixture;
45
+ });
46
+ for (const fixtureKep in newFixtures) {
47
+ var _fixture$deps;
48
+ const fixture = newFixtures[fixtureKep];
49
+ fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
50
+ }
51
+ return Object.values(newFixtures);
52
+ }
53
+ function mergeContextFixtures(fixtures, context, runner) {
54
+ const fixtureOptionKeys = [
55
+ "auto",
56
+ "injected",
57
+ "scope"
58
+ ];
59
+ const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
60
+ const fixtureItem = { value };
61
+ if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
62
+ var _runner$injectValue;
63
+ Object.assign(fixtureItem, value[1]);
64
+ const userValue = value[0];
65
+ fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner, prop)) ?? userValue : userValue;
66
+ }
67
+ fixtureItem.scope = fixtureItem.scope || "test";
68
+ if (fixtureItem.scope === "worker" && !runner.getWorkerContext) fixtureItem.scope = "file";
69
+ fixtureItem.prop = prop;
70
+ fixtureItem.isFn = typeof fixtureItem.value === "function";
71
+ return fixtureItem;
72
+ });
73
+ if (Array.isArray(context.fixtures)) context.fixtures = context.fixtures.concat(fixtureArray);
74
+ else context.fixtures = fixtureArray;
75
+ fixtureArray.forEach((fixture) => {
76
+ if (fixture.isFn) {
77
+ const usedProps = getUsedProps(fixture.value);
78
+ if (usedProps.length) fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
79
+ if (fixture.scope !== "test") {
80
+ var _fixture$deps2;
81
+ (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 || _fixture$deps2.forEach((dep) => {
82
+ if (!dep.isFn) return;
83
+ if (fixture.scope === "worker" && dep.scope === "worker") return;
84
+ if (fixture.scope === "file" && dep.scope !== "test") return;
85
+ throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`);
86
+ });
87
+ }
88
+ }
89
+ });
90
+ return context;
91
+ }
92
+ const fixtureValueMaps = /* @__PURE__ */ new Map();
93
+ const cleanupFnArrayMap = /* @__PURE__ */ new Map();
94
+ function withFixtures(runner, fn, testContext) {
95
+ return (hookContext) => {
96
+ const context = hookContext || testContext;
97
+ if (!context) return fn({});
98
+ const fixtures = getTestFixture(context);
99
+ if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) return fn(context);
100
+ const usedProps = getUsedProps(fn);
101
+ const hasAutoFixture = fixtures.some(({ auto }) => auto);
102
+ if (!usedProps.length && !hasAutoFixture) return fn(context);
103
+ if (!fixtureValueMaps.get(context)) fixtureValueMaps.set(context, /* @__PURE__ */ new Map());
104
+ const fixtureValueMap = fixtureValueMaps.get(context);
105
+ if (!cleanupFnArrayMap.has(context)) cleanupFnArrayMap.set(context, []);
106
+ const cleanupFnArray = cleanupFnArrayMap.get(context);
107
+ const pendingFixtures = resolveDeps(fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop)));
108
+ if (!pendingFixtures.length) return fn(context);
109
+ async function resolveFixtures() {
110
+ for (const fixture of pendingFixtures) {
111
+ if (fixtureValueMap.has(fixture)) continue;
112
+ const resolvedValue = await resolveFixtureValue(runner, fixture, context, cleanupFnArray);
113
+ context[fixture.prop] = resolvedValue;
114
+ fixtureValueMap.set(fixture, resolvedValue);
115
+ if (fixture.scope === "test") cleanupFnArray.unshift(() => {
116
+ fixtureValueMap.delete(fixture);
117
+ });
118
+ }
119
+ }
120
+ return resolveFixtures().then(() => fn(context));
121
+ };
122
+ }
123
+ const globalFixturePromise = /* @__PURE__ */ new WeakMap();
124
+ function resolveFixtureValue(runner, fixture, context, cleanupFnArray) {
125
+ var _runner$getWorkerCont;
126
+ const fileContext = getFileContext(context.task.file);
127
+ const workerContext = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner);
128
+ if (!fixture.isFn) {
129
+ var _fixture$prop;
130
+ fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value);
131
+ if (workerContext) {
132
+ var _fixture$prop2;
133
+ workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value);
134
+ }
135
+ return fixture.value;
136
+ }
137
+ if (fixture.scope === "test") return resolveFixtureFunction(fixture.value, context, cleanupFnArray);
138
+ if (globalFixturePromise.has(fixture)) return globalFixturePromise.get(fixture);
139
+ let fixtureContext;
140
+ if (fixture.scope === "worker") {
141
+ if (!workerContext) throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.");
142
+ fixtureContext = workerContext;
143
+ } else fixtureContext = fileContext;
144
+ if (fixture.prop in fixtureContext) return fixtureContext[fixture.prop];
145
+ if (!cleanupFnArrayMap.has(fixtureContext)) cleanupFnArrayMap.set(fixtureContext, []);
146
+ const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
147
+ const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => {
148
+ fixtureContext[fixture.prop] = value;
149
+ globalFixturePromise.delete(fixture);
150
+ return value;
151
+ });
152
+ globalFixturePromise.set(fixture, promise);
153
+ return promise;
154
+ }
155
+ async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
156
+ const useFnArgPromise = createDefer();
157
+ let isUseFnArgResolved = false;
158
+ const fixtureReturn = fixtureFn(context, async (useFnArg) => {
159
+ isUseFnArgResolved = true;
160
+ useFnArgPromise.resolve(useFnArg);
161
+ const useReturnPromise = createDefer();
162
+ cleanupFnArray.push(async () => {
163
+ useReturnPromise.resolve();
164
+ await fixtureReturn;
165
+ });
166
+ await useReturnPromise;
167
+ }).catch((e) => {
168
+ if (!isUseFnArgResolved) {
169
+ useFnArgPromise.reject(e);
170
+ return;
171
+ }
172
+ throw e;
173
+ });
174
+ return useFnArgPromise;
175
+ }
176
+ function resolveDeps(fixtures, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
177
+ fixtures.forEach((fixture) => {
178
+ if (pendingFixtures.includes(fixture)) return;
179
+ if (!fixture.isFn || !fixture.deps) {
180
+ pendingFixtures.push(fixture);
181
+ return;
182
+ }
183
+ if (depSet.has(fixture)) throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
184
+ depSet.add(fixture);
185
+ resolveDeps(fixture.deps, depSet, pendingFixtures);
186
+ pendingFixtures.push(fixture);
187
+ depSet.clear();
188
+ });
189
+ return pendingFixtures;
190
+ }
191
+ function getUsedProps(fn) {
192
+ let fnString = stripLiteral(fn.toString());
193
+ if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) fnString = fnString.split(/__async\((?:this|null),/)[1];
194
+ const match = fnString.match(/[^(]*\(([^)]*)/);
195
+ if (!match) return [];
196
+ const args = splitByComma(match[1]);
197
+ if (!args.length) return [];
198
+ let first = args[0];
199
+ if ("__VITEST_FIXTURE_INDEX__" in fn) {
200
+ first = args[fn.__VITEST_FIXTURE_INDEX__];
201
+ if (!first) return [];
202
+ }
203
+ if (!(first.startsWith("{") && first.endsWith("}"))) throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
204
+ const props = splitByComma(first.slice(1, -1).replace(/\s/g, "")).map((prop) => {
205
+ return prop.replace(/:.*|=.*/g, "");
206
+ });
207
+ const last = props.at(-1);
208
+ if (last && last.startsWith("...")) throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
209
+ return props;
210
+ }
211
+ function splitByComma(s) {
212
+ const result = [];
213
+ const stack = [];
214
+ let start = 0;
215
+ for (let i = 0; i < s.length; i++) if (s[i] === "{" || s[i] === "[") stack.push(s[i] === "{" ? "}" : "]");
216
+ else if (s[i] === stack[stack.length - 1]) stack.pop();
217
+ else if (!stack.length && s[i] === ",") {
218
+ const token = s.substring(start, i).trim();
219
+ if (token) result.push(token);
220
+ start = i + 1;
221
+ }
222
+ const lastToken = s.substring(start).trim();
223
+ if (lastToken) result.push(lastToken);
224
+ return result;
225
+ }
226
+ let _test;
227
+ function getCurrentTest() {
228
+ return _test;
229
+ }
230
+ function createChainable(keys, fn) {
231
+ function create(context) {
232
+ const chain = function(...args) {
233
+ return fn.apply(context, args);
234
+ };
235
+ Object.assign(chain, fn);
236
+ chain.withContext = () => chain.bind(context);
237
+ chain.setContext = (key, value) => {
238
+ context[key] = value;
239
+ };
240
+ chain.mergeContext = (ctx) => {
241
+ Object.assign(context, ctx);
242
+ };
243
+ for (const key of keys) Object.defineProperty(chain, key, { get() {
244
+ return create({
245
+ ...context,
246
+ [key]: true
247
+ });
248
+ } });
249
+ return chain;
250
+ }
251
+ const chain = create({});
252
+ chain.fn = fn;
253
+ return chain;
254
+ }
255
+ /**
256
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
257
+ * Suites can contain both tests and other suites, enabling complex test structures.
258
+ *
259
+ * @param {string} name - The name of the suite, used for identification and reporting.
260
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
261
+ * @example
262
+ * ```ts
263
+ * // Define a suite with two tests
264
+ * suite('Math operations', () => {
265
+ * test('should add two numbers', () => {
266
+ * expect(add(1, 2)).toBe(3);
267
+ * });
268
+ *
269
+ * test('should subtract two numbers', () => {
270
+ * expect(subtract(5, 2)).toBe(3);
271
+ * });
272
+ * });
273
+ * ```
274
+ * @example
275
+ * ```ts
276
+ * // Define nested suites
277
+ * suite('String operations', () => {
278
+ * suite('Trimming', () => {
279
+ * test('should trim whitespace from start and end', () => {
280
+ * expect(' hello '.trim()).toBe('hello');
281
+ * });
282
+ * });
283
+ *
284
+ * suite('Concatenation', () => {
285
+ * test('should concatenate two strings', () => {
286
+ * expect('hello' + ' ' + 'world').toBe('hello world');
287
+ * });
288
+ * });
289
+ * });
290
+ * ```
291
+ */
292
+ const suite = createSuite();
293
+ /**
294
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
295
+ *
296
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
297
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
298
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
299
+ * @throws {Error} If called inside another test function.
300
+ * @example
301
+ * ```ts
302
+ * // Define a simple test
303
+ * test('should add two numbers', () => {
304
+ * expect(add(1, 2)).toBe(3);
305
+ * });
306
+ * ```
307
+ * @example
308
+ * ```ts
309
+ * // Define a test with options
310
+ * test('should subtract two numbers', { retry: 3 }, () => {
311
+ * expect(subtract(5, 2)).toBe(3);
312
+ * });
313
+ * ```
314
+ */
315
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
316
+ if (getCurrentTest()) throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected.");
317
+ getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
318
+ });
319
+ /**
320
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
321
+ * Suites can contain both tests and other suites, enabling complex test structures.
322
+ *
323
+ * @param {string} name - The name of the suite, used for identification and reporting.
324
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
325
+ * @example
326
+ * ```ts
327
+ * // Define a suite with two tests
328
+ * describe('Math operations', () => {
329
+ * test('should add two numbers', () => {
330
+ * expect(add(1, 2)).toBe(3);
331
+ * });
332
+ *
333
+ * test('should subtract two numbers', () => {
334
+ * expect(subtract(5, 2)).toBe(3);
335
+ * });
336
+ * });
337
+ * ```
338
+ * @example
339
+ * ```ts
340
+ * // Define nested suites
341
+ * describe('String operations', () => {
342
+ * describe('Trimming', () => {
343
+ * test('should trim whitespace from start and end', () => {
344
+ * expect(' hello '.trim()).toBe('hello');
345
+ * });
346
+ * });
347
+ *
348
+ * describe('Concatenation', () => {
349
+ * test('should concatenate two strings', () => {
350
+ * expect('hello' + ' ' + 'world').toBe('hello world');
351
+ * });
352
+ * });
353
+ * });
354
+ * ```
355
+ */
356
+ const describe = suite;
357
+ /**
358
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
359
+ *
360
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
361
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
362
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
363
+ * @throws {Error} If called inside another test function.
364
+ * @example
365
+ * ```ts
366
+ * // Define a simple test
367
+ * it('adds two numbers', () => {
368
+ * expect(add(1, 2)).toBe(3);
369
+ * });
370
+ * ```
371
+ * @example
372
+ * ```ts
373
+ * // Define a test with options
374
+ * it('subtracts two numbers', { retry: 3 }, () => {
375
+ * expect(subtract(5, 2)).toBe(3);
376
+ * });
377
+ * ```
378
+ */
379
+ const it = test;
380
+ let runner;
381
+ let defaultSuite;
382
+ let currentTestFilepath;
383
+ function assert(condition, message) {
384
+ if (!condition) throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`);
385
+ }
386
+ function getTestFilepath() {
387
+ return currentTestFilepath;
388
+ }
389
+ function getRunner() {
390
+ assert(runner, "the runner");
391
+ return runner;
392
+ }
393
+ function getCurrentSuite() {
394
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
395
+ assert(currentSuite, "the current suite");
396
+ return currentSuite;
397
+ }
398
+ function createSuiteHooks() {
399
+ return {
400
+ beforeAll: [],
401
+ afterAll: [],
402
+ beforeEach: [],
403
+ afterEach: []
404
+ };
405
+ }
406
+ function parseArguments(optionsOrFn, optionsOrTest) {
407
+ let options = {};
408
+ let fn = () => {};
409
+ if (typeof optionsOrTest === "object") {
410
+ if (typeof optionsOrFn === "object") throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order.");
411
+ console.warn("Using an object as a third argument is deprecated. Vitest 4 will throw an error if the third argument is not a timeout number. Please use the second argument for options. See more at https://vitest.dev/guide/migration");
412
+ options = optionsOrTest;
413
+ } else if (typeof optionsOrTest === "number") options = { timeout: optionsOrTest };
414
+ else if (typeof optionsOrFn === "object") options = optionsOrFn;
415
+ if (typeof optionsOrFn === "function") {
416
+ if (typeof optionsOrTest === "function") throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
417
+ fn = optionsOrFn;
418
+ } else if (typeof optionsOrTest === "function") fn = optionsOrTest;
419
+ return {
420
+ options,
421
+ handler: fn
422
+ };
423
+ }
424
+ function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) {
425
+ const tasks = [];
426
+ let suite;
427
+ initSuite(true);
428
+ const task = function(name = "", options = {}) {
429
+ var _collectorContext$cur;
430
+ const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
431
+ const task = {
432
+ id: "",
433
+ name,
434
+ suite: (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite,
435
+ each: options.each,
436
+ fails: options.fails,
437
+ context: void 0,
438
+ type: "test",
439
+ file: void 0,
440
+ timeout,
441
+ retry: options.retry ?? runner.config.retry,
442
+ repeats: options.repeats,
443
+ mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
444
+ meta: options.meta ?? Object.create(null),
445
+ annotations: []
446
+ };
447
+ const handler = options.handler;
448
+ if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) task.concurrent = true;
449
+ task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
450
+ const context = createTestContext(task, runner);
451
+ Object.defineProperty(task, "context", {
452
+ value: context,
453
+ enumerable: false
454
+ });
455
+ setTestFixture(context, options.fixtures);
456
+ const limit = Error.stackTraceLimit;
457
+ Error.stackTraceLimit = 15;
458
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
459
+ Error.stackTraceLimit = limit;
460
+ if (handler) setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
461
+ if (runner.config.includeTaskLocation) {
462
+ const error = stackTraceError.stack;
463
+ const stack = findTestFileStackTrace(error);
464
+ if (stack) task.location = stack;
465
+ }
466
+ tasks.push(task);
467
+ return task;
468
+ };
469
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
470
+ let { options, handler } = parseArguments(optionsOrFn, optionsOrTest);
471
+ if (typeof suiteOptions === "object") options = Object.assign({}, suiteOptions, options);
472
+ options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
473
+ options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
474
+ const test = task(formatName(name), {
475
+ ...this,
476
+ ...options,
477
+ handler
478
+ });
479
+ test.type = "test";
480
+ });
481
+ let collectorFixtures = parentCollectorFixtures;
482
+ const collector = {
483
+ type: "collector",
484
+ name,
485
+ mode,
486
+ suite,
487
+ options: suiteOptions,
488
+ test,
489
+ tasks,
490
+ collect,
491
+ task,
492
+ clear,
493
+ on: addHook,
494
+ fixtures() {
495
+ return collectorFixtures;
496
+ },
497
+ scoped(fixtures) {
498
+ const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner);
499
+ if (parsed.fixtures) collectorFixtures = parsed.fixtures;
500
+ }
501
+ };
502
+ function addHook(name, ...fn) {
503
+ getHooks(suite)[name].push(...fn);
504
+ }
505
+ function initSuite(includeLocation) {
506
+ var _collectorContext$cur2;
507
+ if (typeof suiteOptions === "number") suiteOptions = { timeout: suiteOptions };
508
+ suite = {
509
+ id: "",
510
+ type: "suite",
511
+ name,
512
+ suite: (_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.suite,
513
+ mode,
514
+ each,
515
+ file: void 0,
516
+ shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
517
+ tasks: [],
518
+ meta: Object.create(null),
519
+ concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
520
+ };
521
+ if (runner && includeLocation && runner.config.includeTaskLocation) {
522
+ const limit = Error.stackTraceLimit;
523
+ Error.stackTraceLimit = 15;
524
+ const error = (/* @__PURE__ */ new Error("stacktrace")).stack;
525
+ Error.stackTraceLimit = limit;
526
+ const stack = findTestFileStackTrace(error);
527
+ if (stack) suite.location = stack;
528
+ }
529
+ setHooks(suite, createSuiteHooks());
530
+ }
531
+ function clear() {
532
+ tasks.length = 0;
533
+ initSuite(false);
534
+ }
535
+ async function collect(file) {
536
+ if (!file) throw new TypeError("File is required to collect tasks.");
537
+ if (factory) await runWithSuite(collector, () => factory(test));
538
+ const allChildren = [];
539
+ for (const i of tasks) allChildren.push(i.type === "collector" ? await i.collect(file) : i);
540
+ suite.file = file;
541
+ suite.tasks = allChildren;
542
+ allChildren.forEach((task) => {
543
+ task.file = file;
544
+ });
545
+ return suite;
546
+ }
547
+ collectTask(collector);
548
+ return collector;
549
+ }
550
+ function withAwaitAsyncAssertions(fn, task) {
551
+ return async (...args) => {
552
+ const fnResult = await fn(...args);
553
+ if (task.promises) {
554
+ const errors = (await Promise.allSettled(task.promises)).map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
555
+ if (errors.length) throw errors;
556
+ }
557
+ return fnResult;
558
+ };
559
+ }
560
+ function createSuite() {
561
+ function suiteFn(name, factoryOrOptions, optionsOrFactory) {
562
+ var _currentSuite$options;
563
+ const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
564
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
565
+ let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
566
+ const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
567
+ const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
568
+ options = {
569
+ ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
570
+ ...options,
571
+ shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle)
572
+ };
573
+ const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
574
+ const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
575
+ options.concurrent = isConcurrent && !isSequential;
576
+ options.sequential = isSequential && !isConcurrent;
577
+ return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
578
+ }
579
+ suiteFn.each = function(cases, ...args) {
580
+ const suite = this.withContext();
581
+ this.setContext("each", true);
582
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
583
+ return (name, optionsOrFn, fnOrOptions) => {
584
+ const _name = formatName(name);
585
+ const arrayOnlyCases = cases.every(Array.isArray);
586
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
587
+ const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
588
+ cases.forEach((i, idx) => {
589
+ const items = Array.isArray(i) ? i : [i];
590
+ if (fnFirst) if (arrayOnlyCases) suite(formatTitle(_name, items, idx), () => handler(...items), options);
591
+ else suite(formatTitle(_name, items, idx), () => handler(i), options);
592
+ else if (arrayOnlyCases) suite(formatTitle(_name, items, idx), options, () => handler(...items));
593
+ else suite(formatTitle(_name, items, idx), options, () => handler(i));
594
+ });
595
+ this.setContext("each", void 0);
596
+ };
597
+ };
598
+ suiteFn.for = function(cases, ...args) {
599
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
600
+ return (name, optionsOrFn, fnOrOptions) => {
601
+ const name_ = formatName(name);
602
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
603
+ cases.forEach((item, idx) => {
604
+ suite(formatTitle(name_, toArray(item), idx), options, () => handler(item));
605
+ });
606
+ };
607
+ };
608
+ suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
609
+ suiteFn.runIf = (condition) => condition ? suite : suite.skip;
610
+ return createChainable([
611
+ "concurrent",
612
+ "sequential",
613
+ "shuffle",
614
+ "skip",
615
+ "only",
616
+ "todo"
617
+ ], suiteFn);
618
+ }
619
+ function createTaskCollector(fn, context) {
620
+ const taskFn = fn;
621
+ taskFn.each = function(cases, ...args) {
622
+ const test = this.withContext();
623
+ this.setContext("each", true);
624
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
625
+ return (name, optionsOrFn, fnOrOptions) => {
626
+ const _name = formatName(name);
627
+ const arrayOnlyCases = cases.every(Array.isArray);
628
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
629
+ const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
630
+ cases.forEach((i, idx) => {
631
+ const items = Array.isArray(i) ? i : [i];
632
+ if (fnFirst) if (arrayOnlyCases) test(formatTitle(_name, items, idx), () => handler(...items), options);
633
+ else test(formatTitle(_name, items, idx), () => handler(i), options);
634
+ else if (arrayOnlyCases) test(formatTitle(_name, items, idx), options, () => handler(...items));
635
+ else test(formatTitle(_name, items, idx), options, () => handler(i));
636
+ });
637
+ this.setContext("each", void 0);
638
+ };
639
+ };
640
+ taskFn.for = function(cases, ...args) {
641
+ const test = this.withContext();
642
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
643
+ return (name, optionsOrFn, fnOrOptions) => {
644
+ const _name = formatName(name);
645
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
646
+ cases.forEach((item, idx) => {
647
+ const handlerWrapper = (ctx) => handler(item, ctx);
648
+ handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
649
+ handlerWrapper.toString = () => handler.toString();
650
+ test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
651
+ });
652
+ };
653
+ };
654
+ taskFn.skipIf = function(condition) {
655
+ return condition ? this.skip : this;
656
+ };
657
+ taskFn.runIf = function(condition) {
658
+ return condition ? this : this.skip;
659
+ };
660
+ taskFn.scoped = function(fixtures) {
661
+ getCurrentSuite().scoped(fixtures);
662
+ };
663
+ taskFn.extend = function(fixtures) {
664
+ const _context = mergeContextFixtures(fixtures, context || {}, runner);
665
+ const originalWrapper = fn;
666
+ return createTest(function(name, optionsOrFn, optionsOrTest) {
667
+ const scopedFixtures = getCurrentSuite().fixtures();
668
+ const context = { ...this };
669
+ if (scopedFixtures) context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures);
670
+ const { handler, options } = parseArguments(optionsOrFn, optionsOrTest);
671
+ const timeout = options.timeout ?? (runner === null || runner === void 0 ? void 0 : runner.config.testTimeout);
672
+ originalWrapper.call(context, formatName(name), handler, timeout);
673
+ }, _context);
674
+ };
675
+ const _test = createChainable([
676
+ "concurrent",
677
+ "sequential",
678
+ "skip",
679
+ "only",
680
+ "todo",
681
+ "fails"
682
+ ], taskFn);
683
+ if (context) _test.mergeContext(context);
684
+ return _test;
685
+ }
686
+ function createTest(fn, context) {
687
+ return createTaskCollector(fn, context);
688
+ }
689
+ function formatName(name) {
690
+ return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
691
+ }
692
+ function formatTitle(template, items, idx) {
693
+ if (template.includes("%#") || template.includes("%$")) template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
694
+ const count = template.split("%").length - 1;
695
+ if (template.includes("%f")) (template.match(/%f/g) || []).forEach((_, i) => {
696
+ if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
697
+ let occurrence = 0;
698
+ template = template.replace(/%f/g, (match) => {
699
+ occurrence++;
700
+ return occurrence === i + 1 ? "-%f" : match;
701
+ });
702
+ }
703
+ });
704
+ let formatted = format(template, ...items.slice(0, count));
705
+ const isObjectItem = isObject(items[0]);
706
+ formatted = formatted.replace(/\$([$\w.]+)/g, (_, key) => {
707
+ var _runner$config;
708
+ const isArrayKey = /^\d+$/.test(key);
709
+ if (!isObjectItem && !isArrayKey) return `$${key}`;
710
+ const arrayElement = isArrayKey ? objectAttr(items, key) : void 0;
711
+ return objDisplay(isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold });
712
+ });
713
+ return formatted;
714
+ }
715
+ function formatTemplateString(cases, args) {
716
+ const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
717
+ const res = [];
718
+ for (let i = 0; i < Math.floor(args.length / header.length); i++) {
719
+ const oneCase = {};
720
+ for (let j = 0; j < header.length; j++) oneCase[header[j]] = args[i * header.length + j];
721
+ res.push(oneCase);
722
+ }
723
+ return res;
724
+ }
725
+ function findTestFileStackTrace(error) {
726
+ const testFilePath = getTestFilepath();
727
+ const lines = error.split("\n").slice(1);
728
+ for (const line of lines) {
729
+ const stack = parseSingleStack(line);
730
+ if (stack && stack.file === testFilePath) return {
731
+ line: stack.line,
732
+ column: stack.column
733
+ };
734
+ }
735
+ }
736
+ const now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
737
+ function getNames(task) {
738
+ const names = [task.name];
739
+ let current = task;
740
+ while (current === null || current === void 0 ? void 0 : current.suite) {
741
+ current = current.suite;
742
+ if (current === null || current === void 0 ? void 0 : current.name) names.unshift(current.name);
743
+ }
744
+ if (current !== task.file) names.unshift(task.file.name);
745
+ return names;
746
+ }
747
+ function getTestName(task, separator = " > ") {
748
+ return getNames(task).slice(1).join(separator);
749
+ }
750
+ const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
751
+ const unixNow = Date.now;
752
+ const { clearTimeout, setTimeout } = getSafeTimers();
753
+ const packs = /* @__PURE__ */ new Map();
754
+ const eventsPacks = [];
755
+ const pendingTasksUpdates = [];
756
+ function sendTasksUpdate(runner) {
757
+ if (packs.size) {
758
+ var _runner$onTaskUpdate;
759
+ const taskPacks = Array.from(packs).map(([id, task]) => {
760
+ return [
761
+ id,
762
+ task[0],
763
+ task[1]
764
+ ];
765
+ });
766
+ const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks);
767
+ if (p) {
768
+ pendingTasksUpdates.push(p);
769
+ p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
770
+ }
771
+ eventsPacks.length = 0;
772
+ packs.clear();
773
+ }
774
+ }
775
+ async function finishSendTasksUpdate(runner) {
776
+ sendTasksUpdate(runner);
777
+ await Promise.all(pendingTasksUpdates);
778
+ }
779
+ function throttle(fn, ms) {
780
+ let last = 0;
781
+ let pendingCall;
782
+ return function call(...args) {
783
+ const now = unixNow();
784
+ if (now - last > ms) {
785
+ last = now;
786
+ clearTimeout(pendingCall);
787
+ pendingCall = void 0;
788
+ return fn.apply(this, args);
789
+ }
790
+ pendingCall ?? (pendingCall = setTimeout(() => call.bind(this)(...args), ms));
791
+ };
792
+ }
793
+ const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
794
+ const now = Date.now;
795
+ const collectorContext = {
796
+ tasks: [],
797
+ currentSuite: null
798
+ };
799
+ function collectTask(task) {
800
+ var _collectorContext$cur;
801
+ (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 || _collectorContext$cur.tasks.push(task);
802
+ }
803
+ async function runWithSuite(suite, fn) {
804
+ const prev = collectorContext.currentSuite;
805
+ collectorContext.currentSuite = suite;
806
+ await fn();
807
+ collectorContext.currentSuite = prev;
808
+ }
809
+ function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
810
+ if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) return fn;
811
+ const { setTimeout, clearTimeout } = getSafeTimers();
812
+ return function runWithTimeout(...args) {
813
+ const startTime = now();
814
+ const runner = getRunner();
815
+ runner._currentTaskStartTime = startTime;
816
+ runner._currentTaskTimeout = timeout;
817
+ return new Promise((resolve_, reject_) => {
818
+ var _timer$unref;
819
+ const timer = setTimeout(() => {
820
+ clearTimeout(timer);
821
+ rejectTimeoutError();
822
+ }, timeout);
823
+ (_timer$unref = timer.unref) === null || _timer$unref === void 0 || _timer$unref.call(timer);
824
+ function rejectTimeoutError() {
825
+ const error = makeTimeoutError(isHook, timeout, stackTraceError);
826
+ onTimeout === null || onTimeout === void 0 || onTimeout(args, error);
827
+ reject_(error);
828
+ }
829
+ function resolve(result) {
830
+ runner._currentTaskStartTime = void 0;
831
+ runner._currentTaskTimeout = void 0;
832
+ clearTimeout(timer);
833
+ if (now() - startTime >= timeout) {
834
+ rejectTimeoutError();
835
+ return;
836
+ }
837
+ resolve_(result);
838
+ }
839
+ function reject(error) {
840
+ runner._currentTaskStartTime = void 0;
841
+ runner._currentTaskTimeout = void 0;
842
+ clearTimeout(timer);
843
+ reject_(error);
844
+ }
845
+ try {
846
+ const result = fn(...args);
847
+ if (typeof result === "object" && result != null && typeof result.then === "function") result.then(resolve, reject);
848
+ else resolve(result);
849
+ } catch (error) {
850
+ reject(error);
851
+ }
852
+ });
853
+ };
854
+ }
855
+ const abortControllers = /* @__PURE__ */ new WeakMap();
856
+ function abortIfTimeout([context], error) {
857
+ if (context) abortContextSignal(context, error);
858
+ }
859
+ function abortContextSignal(context, error) {
860
+ const abortController = abortControllers.get(context);
861
+ abortController === null || abortController === void 0 || abortController.abort(error);
862
+ }
863
+ function createTestContext(test, runner) {
864
+ var _runner$extendTaskCon;
865
+ const context = function() {
866
+ throw new Error("done() callback is deprecated, use promise instead");
867
+ };
868
+ let abortController = abortControllers.get(context);
869
+ if (!abortController) {
870
+ abortController = new AbortController();
871
+ abortControllers.set(context, abortController);
872
+ }
873
+ context.signal = abortController.signal;
874
+ context.task = test;
875
+ context.skip = (condition, note) => {
876
+ if (condition === false) return;
877
+ test.result ?? (test.result = { state: "skip" });
878
+ test.result.pending = true;
879
+ throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
880
+ };
881
+ async function annotate(message, location, type, attachment) {
882
+ const annotation = {
883
+ message,
884
+ type: type || "notice"
885
+ };
886
+ if (attachment) {
887
+ if (!attachment.body && !attachment.path) throw new TypeError(`Test attachment requires body or path to be set. Both are missing.`);
888
+ if (attachment.body && attachment.path) throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
889
+ annotation.attachment = attachment;
890
+ if (attachment.body instanceof Uint8Array) attachment.body = encodeUint8Array(attachment.body);
891
+ }
892
+ if (location) annotation.location = location;
893
+ if (!runner.onTestAnnotate) throw new Error(`Test runner doesn't support test annotations.`);
894
+ await finishSendTasksUpdate(runner);
895
+ const resolvedAnnotation = await runner.onTestAnnotate(test, annotation);
896
+ test.annotations.push(resolvedAnnotation);
897
+ return resolvedAnnotation;
898
+ }
899
+ context.annotate = (message, type, attachment) => {
900
+ if (test.result && test.result.state !== "run") throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`);
901
+ let location;
902
+ const stack = (/* @__PURE__ */ new Error("STACK_TRACE")).stack;
903
+ const index = stack.includes("STACK_TRACE") ? 2 : 1;
904
+ const stackLine = stack.split("\n")[index];
905
+ const parsed = parseSingleStack(stackLine);
906
+ if (parsed) location = {
907
+ file: parsed.file,
908
+ line: parsed.line,
909
+ column: parsed.column
910
+ };
911
+ if (typeof type === "object") return recordAsyncAnnotation(test, annotate(message, location, void 0, type));
912
+ else return recordAsyncAnnotation(test, annotate(message, location, type, attachment));
913
+ };
914
+ context.onTestFailed = (handler, timeout) => {
915
+ test.onFailed || (test.onFailed = []);
916
+ test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
917
+ };
918
+ context.onTestFinished = (handler, timeout) => {
919
+ test.onFinished || (test.onFinished = []);
920
+ test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
921
+ };
922
+ return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context;
923
+ }
924
+ function makeTimeoutError(isHook, timeout, stackTraceError) {
925
+ const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
926
+ const error = new Error(message);
927
+ if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
928
+ return error;
929
+ }
930
+ const fileContexts = /* @__PURE__ */ new WeakMap();
931
+ function getFileContext(file) {
932
+ const context = fileContexts.get(file);
933
+ if (!context) throw new Error(`Cannot find file context for ${file.name}`);
934
+ return context;
935
+ }
936
+ const table = [];
937
+ for (let i = 65; i < 91; i++) table.push(String.fromCharCode(i));
938
+ for (let i = 97; i < 123; i++) table.push(String.fromCharCode(i));
939
+ for (let i = 0; i < 10; i++) table.push(i.toString(10));
940
+ function encodeUint8Array(bytes) {
941
+ let base64 = "";
942
+ const len = bytes.byteLength;
943
+ for (let i = 0; i < len; i += 3) if (len === i + 1) {
944
+ const a = (bytes[i] & 252) >> 2;
945
+ const b = (bytes[i] & 3) << 4;
946
+ base64 += table[a];
947
+ base64 += table[b];
948
+ base64 += "==";
949
+ } else if (len === i + 2) {
950
+ const a = (bytes[i] & 252) >> 2;
951
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
952
+ const c = (bytes[i + 1] & 15) << 2;
953
+ base64 += table[a];
954
+ base64 += table[b];
955
+ base64 += table[c];
956
+ base64 += "=";
957
+ } else {
958
+ const a = (bytes[i] & 252) >> 2;
959
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
960
+ const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
961
+ const d = bytes[i + 2] & 63;
962
+ base64 += table[a];
963
+ base64 += table[b];
964
+ base64 += table[c];
965
+ base64 += table[d];
966
+ }
967
+ return base64;
968
+ }
969
+ function recordAsyncAnnotation(test, promise) {
970
+ promise = promise.finally(() => {
971
+ if (!test.promises) return;
972
+ const index = test.promises.indexOf(promise);
973
+ if (index !== -1) test.promises.splice(index, 1);
974
+ });
975
+ if (!test.promises) test.promises = [];
976
+ test.promises.push(promise);
977
+ return promise;
978
+ }
979
+ function getDefaultHookTimeout() {
980
+ return getRunner().config.hookTimeout;
981
+ }
982
+ const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
983
+ const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
984
+ /**
985
+ * Registers a callback function to be executed before each test within the current suite.
986
+ * This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
987
+ *
988
+ * **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
989
+ *
990
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
991
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
992
+ * @returns {void}
993
+ * @example
994
+ * ```ts
995
+ * // Example of using beforeEach to reset a database state
996
+ * beforeEach(async () => {
997
+ * await database.reset();
998
+ * });
999
+ * ```
1000
+ */
1001
+ function beforeEach(fn, timeout = getDefaultHookTimeout()) {
1002
+ assertTypes(fn, "\"beforeEach\" callback", ["function"]);
1003
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
1004
+ const runner = getRunner();
1005
+ return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
1006
+ [CLEANUP_TIMEOUT_KEY]: timeout,
1007
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
1008
+ }));
1009
+ }
1010
+ /**
1011
+ * Registers a callback function to be executed after each test within the current suite has completed.
1012
+ * This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
1013
+ *
1014
+ * **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1015
+ *
1016
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
1017
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1018
+ * @returns {void}
1019
+ * @example
1020
+ * ```ts
1021
+ * // Example of using afterEach to delete temporary files created during a test
1022
+ * afterEach(async () => {
1023
+ * await fileSystem.deleteTempFiles();
1024
+ * });
1025
+ * ```
1026
+ */
1027
+ function afterEach(fn, timeout) {
1028
+ assertTypes(fn, "\"afterEach\" callback", ["function"]);
1029
+ const runner = getRunner();
1030
+ return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1031
+ }
1032
+ /**
1033
+ * Registers a callback function to be executed when a test fails within the current suite.
1034
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
1035
+ *
1036
+ * **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1037
+ *
1038
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
1039
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1040
+ * @throws {Error} Throws an error if the function is not called within a test.
1041
+ * @returns {void}
1042
+ * @example
1043
+ * ```ts
1044
+ * // Example of using onTestFailed to log failure details
1045
+ * onTestFailed(({ errors }) => {
1046
+ * console.log(`Test failed: ${test.name}`, errors);
1047
+ * });
1048
+ * ```
1049
+ */
1050
+ const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => {
1051
+ test.onFailed || (test.onFailed = []);
1052
+ test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1053
+ });
1054
+ /**
1055
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
1056
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
1057
+ *
1058
+ * This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
1059
+ *
1060
+ * **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1061
+ *
1062
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
1063
+ *
1064
+ * @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
1065
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1066
+ * @throws {Error} Throws an error if the function is not called within a test.
1067
+ * @returns {void}
1068
+ * @example
1069
+ * ```ts
1070
+ * // Example of using onTestFinished for cleanup
1071
+ * const db = await connectToDatabase();
1072
+ * onTestFinished(async () => {
1073
+ * await db.disconnect();
1074
+ * });
1075
+ * ```
1076
+ */
1077
+ const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => {
1078
+ test.onFinished || (test.onFinished = []);
1079
+ test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1080
+ });
1081
+ function createTestHook(name, handler) {
1082
+ return (fn, timeout) => {
1083
+ assertTypes(fn, `"${name}" callback`, ["function"]);
1084
+ const current = getCurrentTest();
1085
+ if (!current) throw new Error(`Hook ${name}() can only be called inside a test`);
1086
+ return handler(current, fn, timeout);
1087
+ };
1088
+ }
1089
+
1090
+ //#endregion
1091
+ export { afterEach, beforeEach, createChainable, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getHooks, getNames, getTestName, it, setFn, setHooks, suite, test };