@voidzero-dev/vite-plus-test 0.0.0-0bfcc90f.20260209-0731

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 (318) hide show
  1. package/LICENSE.md +691 -0
  2. package/browser/context.d.ts +4 -0
  3. package/browser/context.js +20 -0
  4. package/config.d.ts +3 -0
  5. package/coverage.d.ts +1 -0
  6. package/dist/@vitest/browser/client/.vite/manifest.json +24 -0
  7. package/dist/@vitest/browser/client/__vitest__/assets/index-BUCFJtth.js +57 -0
  8. package/dist/@vitest/browser/client/__vitest__/assets/index-DlhE0rqZ.css +1 -0
  9. package/dist/@vitest/browser/client/__vitest__/bg.png +0 -0
  10. package/dist/@vitest/browser/client/__vitest__/favicon.ico +0 -0
  11. package/dist/@vitest/browser/client/__vitest__/favicon.svg +5 -0
  12. package/dist/@vitest/browser/client/__vitest__/index.html +32 -0
  13. package/dist/@vitest/browser/client/__vitest_browser__/orchestrator-S_3e_uzt.js +345 -0
  14. package/dist/@vitest/browser/client/__vitest_browser__/tester-k74mgIRa.js +2171 -0
  15. package/dist/@vitest/browser/client/__vitest_browser__/utils-uxqdqUz8.js +223 -0
  16. package/dist/@vitest/browser/client/error-catcher.js +82 -0
  17. package/dist/@vitest/browser/client/esm-client-injector.js +67 -0
  18. package/dist/@vitest/browser/client/favicon.svg +5 -0
  19. package/dist/@vitest/browser/client/orchestrator.html +35 -0
  20. package/dist/@vitest/browser/client/tester/tester.html +13 -0
  21. package/dist/@vitest/browser/client.js +456 -0
  22. package/dist/@vitest/browser/context.d.ts +792 -0
  23. package/dist/@vitest/browser/context.js +541 -0
  24. package/dist/@vitest/browser/expect-element.js +32 -0
  25. package/dist/@vitest/browser/index-D6m36C6U.js +11 -0
  26. package/dist/@vitest/browser/index.d.ts +73 -0
  27. package/dist/@vitest/browser/index.js +3513 -0
  28. package/dist/@vitest/browser/jest-dom.d.ts +724 -0
  29. package/dist/@vitest/browser/locators.d.ts +354 -0
  30. package/dist/@vitest/browser/locators.js +1 -0
  31. package/dist/@vitest/browser/matchers.d.ts +29 -0
  32. package/dist/@vitest/browser/shared/screenshotMatcher/types.d.ts +22 -0
  33. package/dist/@vitest/browser/state.js +280 -0
  34. package/dist/@vitest/browser/types.d.ts +69 -0
  35. package/dist/@vitest/browser-playwright/context.d.ts +1 -0
  36. package/dist/@vitest/browser-playwright/index.d.ts +106 -0
  37. package/dist/@vitest/browser-playwright/index.js +1111 -0
  38. package/dist/@vitest/browser-playwright/locators.js +114 -0
  39. package/dist/@vitest/browser-preview/context.d.ts +1 -0
  40. package/dist/@vitest/browser-preview/index.d.ts +19 -0
  41. package/dist/@vitest/browser-preview/index.js +148 -0
  42. package/dist/@vitest/browser-preview/locators.js +79 -0
  43. package/dist/@vitest/browser-webdriverio/context.d.ts +1 -0
  44. package/dist/@vitest/browser-webdriverio/index.d.ts +63 -0
  45. package/dist/@vitest/browser-webdriverio/index.js +600 -0
  46. package/dist/@vitest/browser-webdriverio/locators.js +163 -0
  47. package/dist/@vitest/expect/index.d.ts +807 -0
  48. package/dist/@vitest/expect/index.js +1875 -0
  49. package/dist/@vitest/mocker/auto-register.d.ts +2 -0
  50. package/dist/@vitest/mocker/auto-register.js +9 -0
  51. package/dist/@vitest/mocker/automock.d.ts +12 -0
  52. package/dist/@vitest/mocker/automock.js +1 -0
  53. package/dist/@vitest/mocker/browser.d.ts +53 -0
  54. package/dist/@vitest/mocker/browser.js +91 -0
  55. package/dist/@vitest/mocker/chunk-automock.js +354 -0
  56. package/dist/@vitest/mocker/chunk-interceptor-native.js +15 -0
  57. package/dist/@vitest/mocker/chunk-mocker.js +521 -0
  58. package/dist/@vitest/mocker/chunk-pathe.M-eThtNZ.js +174 -0
  59. package/dist/@vitest/mocker/chunk-registry.js +185 -0
  60. package/dist/@vitest/mocker/chunk-utils.js +16 -0
  61. package/dist/@vitest/mocker/index.d-C-sLYZi-.d.ts +25 -0
  62. package/dist/@vitest/mocker/index.d.ts +2 -0
  63. package/dist/@vitest/mocker/index.js +185 -0
  64. package/dist/@vitest/mocker/mocker.d-TnKRhz7N.d.ts +81 -0
  65. package/dist/@vitest/mocker/node.d.ts +800 -0
  66. package/dist/@vitest/mocker/node.js +966 -0
  67. package/dist/@vitest/mocker/redirect.d.ts +3 -0
  68. package/dist/@vitest/mocker/redirect.js +79 -0
  69. package/dist/@vitest/mocker/register.d.ts +9 -0
  70. package/dist/@vitest/mocker/register.js +41 -0
  71. package/dist/@vitest/mocker/types.d-B8CCKmHt.d.ts +107 -0
  72. package/dist/@vitest/pretty-format/index.d.ts +124 -0
  73. package/dist/@vitest/pretty-format/index.js +1022 -0
  74. package/dist/@vitest/runner/chunk-tasks.js +340 -0
  75. package/dist/@vitest/runner/index.d.ts +180 -0
  76. package/dist/@vitest/runner/index.js +2114 -0
  77. package/dist/@vitest/runner/tasks.d-C7UxawJ9.d.ts +834 -0
  78. package/dist/@vitest/runner/types.d.ts +183 -0
  79. package/dist/@vitest/runner/types.js +1 -0
  80. package/dist/@vitest/runner/utils.d.ts +45 -0
  81. package/dist/@vitest/runner/utils.js +5 -0
  82. package/dist/@vitest/snapshot/environment.d-DHdQ1Csl.d.ts +22 -0
  83. package/dist/@vitest/snapshot/environment.d.ts +16 -0
  84. package/dist/@vitest/snapshot/environment.js +40 -0
  85. package/dist/@vitest/snapshot/index.d.ts +130 -0
  86. package/dist/@vitest/snapshot/index.js +1437 -0
  87. package/dist/@vitest/snapshot/manager.d.ts +18 -0
  88. package/dist/@vitest/snapshot/manager.js +73 -0
  89. package/dist/@vitest/snapshot/rawSnapshot.d-lFsMJFUd.d.ts +61 -0
  90. package/dist/@vitest/spy/index.d.ts +384 -0
  91. package/dist/@vitest/spy/index.js +433 -0
  92. package/dist/@vitest/utils/chunk-_commonjsHelpers.js +5 -0
  93. package/dist/@vitest/utils/chunk-pathe.M-eThtNZ.js +156 -0
  94. package/dist/@vitest/utils/constants.d.ts +21 -0
  95. package/dist/@vitest/utils/constants.js +49 -0
  96. package/dist/@vitest/utils/diff.d.ts +93 -0
  97. package/dist/@vitest/utils/diff.js +2199 -0
  98. package/dist/@vitest/utils/display.d.ts +29 -0
  99. package/dist/@vitest/utils/display.js +742 -0
  100. package/dist/@vitest/utils/error.d.ts +7 -0
  101. package/dist/@vitest/utils/error.js +42 -0
  102. package/dist/@vitest/utils/helpers.d.ts +73 -0
  103. package/dist/@vitest/utils/helpers.js +295 -0
  104. package/dist/@vitest/utils/highlight.d.ts +9 -0
  105. package/dist/@vitest/utils/highlight.js +538 -0
  106. package/dist/@vitest/utils/index.d.ts +5 -0
  107. package/dist/@vitest/utils/index.js +1 -0
  108. package/dist/@vitest/utils/offset.d.ts +5 -0
  109. package/dist/@vitest/utils/offset.js +32 -0
  110. package/dist/@vitest/utils/resolver.d.ts +7 -0
  111. package/dist/@vitest/utils/resolver.js +71 -0
  112. package/dist/@vitest/utils/serialize.d.ts +3 -0
  113. package/dist/@vitest/utils/serialize.js +118 -0
  114. package/dist/@vitest/utils/source-map.d.ts +55 -0
  115. package/dist/@vitest/utils/source-map.js +478 -0
  116. package/dist/@vitest/utils/timers.d.ts +33 -0
  117. package/dist/@vitest/utils/timers.js +49 -0
  118. package/dist/@vitest/utils/types.d-BCElaP-c.d.ts +53 -0
  119. package/dist/@vitest/utils/types.d.ts +34 -0
  120. package/dist/@vitest/utils/types.js +1 -0
  121. package/dist/browser-compat.js +3 -0
  122. package/dist/browser.d.ts +46 -0
  123. package/dist/browser.js +20 -0
  124. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +6 -0
  125. package/dist/chunks/base.CJ0Y4ePK.js +165 -0
  126. package/dist/chunks/benchmark.B3N2zMcH.js +40 -0
  127. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +24 -0
  128. package/dist/chunks/browser.d.ChKACdzH.d.ts +59 -0
  129. package/dist/chunks/cac.DVeoLl0M.js +1409 -0
  130. package/dist/chunks/cli-api.B7PN_QUv.js +13672 -0
  131. package/dist/chunks/config.d.Cy95HiCx.d.ts +210 -0
  132. package/dist/chunks/console.Cf-YriPC.js +146 -0
  133. package/dist/chunks/constants.D_Q9UYh-.js +36 -0
  134. package/dist/chunks/coverage.AVPTjMgw.js +3292 -0
  135. package/dist/chunks/coverage.D_JHT54q.js +25 -0
  136. package/dist/chunks/coverage.d.BZtK59WP.d.ts +37 -0
  137. package/dist/chunks/creator.DAmOKTvJ.js +673 -0
  138. package/dist/chunks/date.Bq6ZW5rf.js +73 -0
  139. package/dist/chunks/defaults.BOqNVLsY.js +74 -0
  140. package/dist/chunks/env.D4Lgay0q.js +8 -0
  141. package/dist/chunks/environment.d.CrsxCzP1.d.ts +29 -0
  142. package/dist/chunks/evaluatedModules.Dg1zASAC.js +17 -0
  143. package/dist/chunks/evaluatedModules.d.BxJ5omdx.d.ts +7 -0
  144. package/dist/chunks/git.Bm2pzPAa.js +71 -0
  145. package/dist/chunks/global.d.B15mdLcR.d.ts +99 -0
  146. package/dist/chunks/globals.DOayXfHP.js +30 -0
  147. package/dist/chunks/index.6Qv1eEA6.js +109 -0
  148. package/dist/chunks/index.C5r1PdPD.js +231 -0
  149. package/dist/chunks/index.Chj8NDwU.js +206 -0
  150. package/dist/chunks/index.CyBMJtT7.js +727 -0
  151. package/dist/chunks/index.D3XRDfWc.js +213 -0
  152. package/dist/chunks/index.D4KonVSU.js +6343 -0
  153. package/dist/chunks/index.M8mOzt4Y.js +3839 -0
  154. package/dist/chunks/index.Z5E_ObnR.js +37 -0
  155. package/dist/chunks/init-forks._y3TW739.js +41 -0
  156. package/dist/chunks/init-threads.DBO2kn-p.js +18 -0
  157. package/dist/chunks/init.B6MLFIaN.js +334 -0
  158. package/dist/chunks/inspector.CvyFGlXm.js +53 -0
  159. package/dist/chunks/modules.BJuCwlRJ.js +36 -0
  160. package/dist/chunks/node.Ce0vMQM7.js +14 -0
  161. package/dist/chunks/plugin.d.CtqpEehP.d.ts +38 -0
  162. package/dist/chunks/reporters.d.CWXNI2jG.d.ts +3271 -0
  163. package/dist/chunks/rpc.BoxB0q7B.js +76 -0
  164. package/dist/chunks/rpc.d.RH3apGEf.d.ts +64 -0
  165. package/dist/chunks/setup-common.Cm-kSBVi.js +60 -0
  166. package/dist/chunks/startModuleRunner.DEj0jb3e.js +861 -0
  167. package/dist/chunks/suite.d.BJWk38HB.d.ts +10 -0
  168. package/dist/chunks/test.B8ej_ZHS.js +254 -0
  169. package/dist/chunks/traces.CCmnQaNT.js +217 -0
  170. package/dist/chunks/traces.d.402V_yFI.d.ts +18 -0
  171. package/dist/chunks/utils.DvEY5TfP.js +52 -0
  172. package/dist/chunks/vi.2VT5v0um.js +3919 -0
  173. package/dist/chunks/vm.D3epNOPZ.js +744 -0
  174. package/dist/chunks/worker.d.Dyxm8DEL.d.ts +255 -0
  175. package/dist/cli.js +28 -0
  176. package/dist/client/.vite/manifest.json +24 -0
  177. package/dist/client/__vitest__/assets/index-BUCFJtth.js +57 -0
  178. package/dist/client/__vitest__/assets/index-DlhE0rqZ.css +1 -0
  179. package/dist/client/__vitest__/bg.png +0 -0
  180. package/dist/client/__vitest__/favicon.ico +0 -0
  181. package/dist/client/__vitest__/favicon.svg +5 -0
  182. package/dist/client/__vitest__/index.html +32 -0
  183. package/dist/client/__vitest_browser__/orchestrator-S_3e_uzt.js +345 -0
  184. package/dist/client/__vitest_browser__/tester-k74mgIRa.js +2171 -0
  185. package/dist/client/__vitest_browser__/utils-uxqdqUz8.js +223 -0
  186. package/dist/client/error-catcher.js +82 -0
  187. package/dist/client/esm-client-injector.js +67 -0
  188. package/dist/client/favicon.svg +5 -0
  189. package/dist/client/orchestrator.html +35 -0
  190. package/dist/client/tester/tester.html +13 -0
  191. package/dist/client.js +456 -0
  192. package/dist/config.cjs +94 -0
  193. package/dist/config.d.ts +104 -0
  194. package/dist/config.js +15 -0
  195. package/dist/context.js +541 -0
  196. package/dist/coverage.d.ts +118 -0
  197. package/dist/coverage.js +23 -0
  198. package/dist/dummy.js +2 -0
  199. package/dist/environments.d.ts +22 -0
  200. package/dist/environments.js +3 -0
  201. package/dist/expect-element.js +27 -0
  202. package/dist/index-D6m36C6U.js +6 -0
  203. package/dist/index-node.js +7 -0
  204. package/dist/index.d.ts +510 -0
  205. package/dist/index.js +19 -0
  206. package/dist/locators.d.ts +354 -0
  207. package/dist/locators.js +1 -0
  208. package/dist/mocker.d.ts +1 -0
  209. package/dist/mocker.js +1 -0
  210. package/dist/module-evaluator.d.ts +124 -0
  211. package/dist/module-evaluator.js +343 -0
  212. package/dist/module-runner-stub.js +44 -0
  213. package/dist/module-runner.js +17 -0
  214. package/dist/node.d.ts +251 -0
  215. package/dist/node.js +98 -0
  216. package/dist/path.js +7 -0
  217. package/dist/plugins/browser-client.mjs +2 -0
  218. package/dist/plugins/browser-context.mjs +2 -0
  219. package/dist/plugins/browser-locators.mjs +2 -0
  220. package/dist/plugins/browser-playwright.mjs +2 -0
  221. package/dist/plugins/browser-preview.mjs +2 -0
  222. package/dist/plugins/browser-webdriverio.mjs +2 -0
  223. package/dist/plugins/browser.mjs +2 -0
  224. package/dist/plugins/expect.mjs +2 -0
  225. package/dist/plugins/mocker-automock.mjs +2 -0
  226. package/dist/plugins/mocker-browser.mjs +2 -0
  227. package/dist/plugins/mocker-node.mjs +2 -0
  228. package/dist/plugins/mocker-redirect.mjs +2 -0
  229. package/dist/plugins/mocker-register.mjs +2 -0
  230. package/dist/plugins/mocker.mjs +2 -0
  231. package/dist/plugins/pretty-format.mjs +2 -0
  232. package/dist/plugins/runner-types.mjs +2 -0
  233. package/dist/plugins/runner-utils.mjs +2 -0
  234. package/dist/plugins/runner.mjs +2 -0
  235. package/dist/plugins/snapshot-environment.mjs +2 -0
  236. package/dist/plugins/snapshot-manager.mjs +2 -0
  237. package/dist/plugins/snapshot.mjs +2 -0
  238. package/dist/plugins/spy.mjs +2 -0
  239. package/dist/plugins/utils-constants.mjs +2 -0
  240. package/dist/plugins/utils-diff.mjs +2 -0
  241. package/dist/plugins/utils-display.mjs +2 -0
  242. package/dist/plugins/utils-error.mjs +2 -0
  243. package/dist/plugins/utils-helpers.mjs +2 -0
  244. package/dist/plugins/utils-highlight.mjs +2 -0
  245. package/dist/plugins/utils-offset.mjs +2 -0
  246. package/dist/plugins/utils-resolver.mjs +2 -0
  247. package/dist/plugins/utils-serialize.mjs +2 -0
  248. package/dist/plugins/utils-source-map.mjs +2 -0
  249. package/dist/plugins/utils-timers.mjs +2 -0
  250. package/dist/plugins/utils.mjs +2 -0
  251. package/dist/reporters.d.ts +27 -0
  252. package/dist/reporters.js +24 -0
  253. package/dist/runners.d.ts +50 -0
  254. package/dist/runners.js +19 -0
  255. package/dist/shared/screenshotMatcher/types.d.ts +22 -0
  256. package/dist/snapshot.d.ts +9 -0
  257. package/dist/snapshot.js +4 -0
  258. package/dist/spy.js +1 -0
  259. package/dist/state.js +280 -0
  260. package/dist/suite.d.ts +5 -0
  261. package/dist/suite.js +6 -0
  262. package/dist/types.d.ts +69 -0
  263. package/dist/vendor/chai.d.mts +1 -0
  264. package/dist/vendor/chai.mjs +3577 -0
  265. package/dist/vendor/es-module-lexer.d.mts +193 -0
  266. package/dist/vendor/es-module-lexer.mjs +79 -0
  267. package/dist/vendor/estree-walker.d.mts +583 -0
  268. package/dist/vendor/estree-walker.mjs +339 -0
  269. package/dist/vendor/expect-type.d.mts +1574 -0
  270. package/dist/vendor/expect-type.mjs +214 -0
  271. package/dist/vendor/magic-string.d.mts +261 -0
  272. package/dist/vendor/magic-string.mjs +1700 -0
  273. package/dist/vendor/obug.d.mts +56 -0
  274. package/dist/vendor/obug.mjs +276 -0
  275. package/dist/vendor/pathe.d.mts +46 -0
  276. package/dist/vendor/pathe.mjs +496 -0
  277. package/dist/vendor/picomatch.d.mts +1 -0
  278. package/dist/vendor/picomatch.mjs +1855 -0
  279. package/dist/vendor/shared-3g9mwCWP.mjs +31 -0
  280. package/dist/vendor/std-env.d.mts +88 -0
  281. package/dist/vendor/std-env.mjs +159 -0
  282. package/dist/vendor/tinybench.d.mts +317 -0
  283. package/dist/vendor/tinybench.mjs +504 -0
  284. package/dist/vendor/tinyexec.d.mts +72 -0
  285. package/dist/vendor/tinyexec.mjs +637 -0
  286. package/dist/vendor/tinyglobby.d.mts +157 -0
  287. package/dist/vendor/tinyglobby.mjs +832 -0
  288. package/dist/vendor/tinyrainbow.d.mts +60 -0
  289. package/dist/vendor/tinyrainbow.mjs +93 -0
  290. package/dist/vendor/vitest_browser.mjs +2 -0
  291. package/dist/vendor/vitest_internal_browser.mjs +2 -0
  292. package/dist/vendor/vitest_runner.mjs +2 -0
  293. package/dist/vendor/vitest_runners.mjs +2 -0
  294. package/dist/worker.d.ts +32 -0
  295. package/dist/worker.js +48 -0
  296. package/dist/workers/forks.js +54 -0
  297. package/dist/workers/runVmTests.js +95 -0
  298. package/dist/workers/threads.js +55 -0
  299. package/dist/workers/vmForks.js +36 -0
  300. package/dist/workers/vmThreads.js +37 -0
  301. package/environments.d.ts +1 -0
  302. package/globals.d.ts +20 -0
  303. package/import-meta.d.ts +5 -0
  304. package/importMeta.d.ts +4 -0
  305. package/index.cjs +5 -0
  306. package/index.d.cts +1 -0
  307. package/jsdom.d.ts +6 -0
  308. package/mocker.d.ts +1 -0
  309. package/node.d.ts +1 -0
  310. package/optional-types.d.ts +7 -0
  311. package/package.json +335 -0
  312. package/reporters.d.ts +1 -0
  313. package/runners.d.ts +1 -0
  314. package/snapshot.d.ts +1 -0
  315. package/suite.d.ts +1 -0
  316. package/suppress-warnings.cjs +21 -0
  317. package/vitest.mjs +2 -0
  318. package/worker.d.ts +1 -0
@@ -0,0 +1,2171 @@
1
+ import { c as resolve, m as moduleRunner, d as getWorkerState, g as getBrowserState, e as getTestName, a as getConfig } from "./utils-uxqdqUz8.js";
2
+ import { onCancel, globalChannel, channel, client } from"../../@vitest/browser/client.js";
3
+ import { userEvent, page, server } from"../../context.js";
4
+ import { getSafeTimers, DecodedMap as DecodedMap$1, getOriginalPosition as getOriginalPosition$1, loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker, browserFormat, Traces, setupCommonEnv, startCoverageInsideWorker, stopCoverageInsideWorker, startTests, collectTests, SpyModule } from"../../browser.js";
5
+ import { VitestTestRunner, NodeBenchmarkRunner } from"../../runners.js";
6
+ const scriptRel = "modulepreload";
7
+ const assetsURL = function(dep) {
8
+ return "/" + dep;
9
+ };
10
+ const seen = {};
11
+ const __vitePreload = function preload(baseModule, deps, importerUrl) {
12
+ let promise = Promise.resolve();
13
+ if (deps && deps.length > 0) {
14
+ let allSettled = function(promises$2) {
15
+ return Promise.all(promises$2.map((p) => Promise.resolve(p).then((value$1) => ({
16
+ status: "fulfilled",
17
+ value: value$1
18
+ }), (reason) => ({
19
+ status: "rejected",
20
+ reason
21
+ }))));
22
+ };
23
+ document.getElementsByTagName("link");
24
+ const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
25
+ const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
26
+ promise = allSettled(deps.map((dep) => {
27
+ dep = assetsURL(dep);
28
+ if (dep in seen) return;
29
+ seen[dep] = true;
30
+ const isCss = dep.endsWith(".css");
31
+ const cssSelector = isCss ? '[rel="stylesheet"]' : "";
32
+ if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
33
+ const link = document.createElement("link");
34
+ link.rel = isCss ? "stylesheet" : scriptRel;
35
+ if (!isCss) link.as = "script";
36
+ link.crossOrigin = "";
37
+ link.href = dep;
38
+ if (cspNonce) link.setAttribute("nonce", cspNonce);
39
+ document.head.appendChild(link);
40
+ if (isCss) return new Promise((res, rej) => {
41
+ link.addEventListener("load", res);
42
+ link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
43
+ });
44
+ }));
45
+ }
46
+ function handlePreloadError(err$2) {
47
+ const e$1 = new Event("vite:preloadError", { cancelable: true });
48
+ e$1.payload = err$2;
49
+ window.dispatchEvent(e$1);
50
+ if (!e$1.defaultPrevented) throw err$2;
51
+ }
52
+ return promise.then((res) => {
53
+ for (const item of res || []) {
54
+ if (item.status !== "rejected") continue;
55
+ handlePreloadError(item.reason);
56
+ }
57
+ return baseModule().catch(handlePreloadError);
58
+ });
59
+ };
60
+ const { parse: $parse } = JSON;
61
+ const { keys } = Object;
62
+ const Primitive = String;
63
+ const primitive = "string";
64
+ const ignore = {};
65
+ const object = "object";
66
+ const noop = (_, value) => value;
67
+ const primitives = (value) => value instanceof Primitive ? Primitive(value) : value;
68
+ const Primitives = (_, value) => typeof value === primitive ? new Primitive(value) : value;
69
+ const revive = (input, parsed, output, $) => {
70
+ const lazy = [];
71
+ for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
72
+ const k = ke[y];
73
+ const value = output[k];
74
+ if (value instanceof Primitive) {
75
+ const tmp = input[value];
76
+ if (typeof tmp === object && !parsed.has(tmp)) {
77
+ parsed.add(tmp);
78
+ output[k] = ignore;
79
+ lazy.push({ k, a: [input, parsed, tmp, $] });
80
+ } else
81
+ output[k] = $.call(output, k, tmp);
82
+ } else if (output[k] !== ignore)
83
+ output[k] = $.call(output, k, value);
84
+ }
85
+ for (let { length } = lazy, i = 0; i < length; i++) {
86
+ const { k, a } = lazy[i];
87
+ output[k] = $.call(output, k, revive.apply(null, a));
88
+ }
89
+ return output;
90
+ };
91
+ const parse = (text, reviver) => {
92
+ const input = $parse(text, Primitives).map(primitives);
93
+ const value = input[0];
94
+ const $ = noop;
95
+ const tmp = typeof value === object && value ? revive(input, /* @__PURE__ */ new Set(), value, $) : value;
96
+ return $.call({ "": tmp }, "", tmp);
97
+ };
98
+ function showPopupWarning(name, value, defaultValue) {
99
+ return (...params) => {
100
+ const formattedParams = params.map((p) => JSON.stringify(p)).join(", ");
101
+ console.warn(`Vitest encountered a \`${name}(${formattedParams})\` call that it cannot handle by default, so it returned \`${value}\`. Read more in https://vitest.dev/guide/browser/#thread-blocking-dialogs.
102
+ If needed, mock the \`${name}\` call manually like:
103
+
104
+ \`\`\`
105
+ import { expect, vi } from "vitest"
106
+
107
+ vi.spyOn(window, "${name}")${defaultValue ? `.mockReturnValue(${JSON.stringify(defaultValue)})` : ""}
108
+ ${name}(${formattedParams})
109
+ expect(${name}).toHaveBeenCalledWith(${formattedParams})
110
+ \`\`\``);
111
+ return value;
112
+ };
113
+ }
114
+ function setupDialogsSpy() {
115
+ globalThis.alert = showPopupWarning("alert", void 0);
116
+ globalThis.confirm = showPopupWarning("confirm", false, true);
117
+ globalThis.prompt = showPopupWarning("prompt", null, "your value");
118
+ }
119
+ const { get } = Reflect;
120
+ function withSafeTimers(getTimers, fn) {
121
+ const { setTimeout, clearTimeout } = getTimers();
122
+ const currentSetTimeout = globalThis.setTimeout;
123
+ const currentClearTimeout = globalThis.clearTimeout;
124
+ try {
125
+ globalThis.setTimeout = setTimeout;
126
+ globalThis.clearTimeout = clearTimeout;
127
+ const result = fn();
128
+ return result;
129
+ } finally {
130
+ globalThis.setTimeout = currentSetTimeout;
131
+ globalThis.clearTimeout = currentClearTimeout;
132
+ }
133
+ }
134
+ const promises = /* @__PURE__ */ new Set();
135
+ function createSafeRpc(client2) {
136
+ return new Proxy(client2.rpc, {
137
+ get(target, p, handler) {
138
+ if (p === "then") {
139
+ return;
140
+ }
141
+ const sendCall = get(target, p, handler);
142
+ const safeSendCall = (...args) => withSafeTimers(getSafeTimers, async () => {
143
+ const result = sendCall(...args);
144
+ promises.add(result);
145
+ try {
146
+ return await result;
147
+ } finally {
148
+ promises.delete(result);
149
+ }
150
+ });
151
+ safeSendCall.asEvent = sendCall.asEvent;
152
+ return safeSendCall;
153
+ }
154
+ });
155
+ }
156
+ function rpc$2() {
157
+ return globalThis.__vitest_worker__.rpc;
158
+ }
159
+ var comma = ",".charCodeAt(0);
160
+ var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
161
+ var intToChar$1 = new Uint8Array(64);
162
+ var charToInt$1 = new Uint8Array(128);
163
+ for (let i = 0; i < chars$1.length; i++) {
164
+ const c = chars$1.charCodeAt(i);
165
+ intToChar$1[i] = c;
166
+ charToInt$1[c] = i;
167
+ }
168
+ function decodeInteger(reader, relative) {
169
+ let value = 0;
170
+ let shift = 0;
171
+ let integer = 0;
172
+ do {
173
+ const c = reader.next();
174
+ integer = charToInt$1[c];
175
+ value |= (integer & 31) << shift;
176
+ shift += 5;
177
+ } while (integer & 32);
178
+ const shouldNegate = value & 1;
179
+ value >>>= 1;
180
+ if (shouldNegate) {
181
+ value = -2147483648 | -value;
182
+ }
183
+ return relative + value;
184
+ }
185
+ function hasMoreVlq(reader, max) {
186
+ if (reader.pos >= max) return false;
187
+ return reader.peek() !== comma;
188
+ }
189
+ var StringReader = class {
190
+ constructor(buffer) {
191
+ this.pos = 0;
192
+ this.buffer = buffer;
193
+ }
194
+ next() {
195
+ return this.buffer.charCodeAt(this.pos++);
196
+ }
197
+ peek() {
198
+ return this.buffer.charCodeAt(this.pos);
199
+ }
200
+ indexOf(char) {
201
+ const { buffer, pos } = this;
202
+ const idx = buffer.indexOf(char, pos);
203
+ return idx === -1 ? buffer.length : idx;
204
+ }
205
+ };
206
+ function decode(mappings) {
207
+ const { length } = mappings;
208
+ const reader = new StringReader(mappings);
209
+ const decoded = [];
210
+ let genColumn = 0;
211
+ let sourcesIndex = 0;
212
+ let sourceLine = 0;
213
+ let sourceColumn = 0;
214
+ let namesIndex = 0;
215
+ do {
216
+ const semi = reader.indexOf(";");
217
+ const line = [];
218
+ let sorted = true;
219
+ let lastCol = 0;
220
+ genColumn = 0;
221
+ while (reader.pos < semi) {
222
+ let seg;
223
+ genColumn = decodeInteger(reader, genColumn);
224
+ if (genColumn < lastCol) sorted = false;
225
+ lastCol = genColumn;
226
+ if (hasMoreVlq(reader, semi)) {
227
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
228
+ sourceLine = decodeInteger(reader, sourceLine);
229
+ sourceColumn = decodeInteger(reader, sourceColumn);
230
+ if (hasMoreVlq(reader, semi)) {
231
+ namesIndex = decodeInteger(reader, namesIndex);
232
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
233
+ } else {
234
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
235
+ }
236
+ } else {
237
+ seg = [genColumn];
238
+ }
239
+ line.push(seg);
240
+ reader.pos++;
241
+ }
242
+ if (!sorted) sort(line);
243
+ decoded.push(line);
244
+ reader.pos = semi + 1;
245
+ } while (reader.pos <= length);
246
+ return decoded;
247
+ }
248
+ function sort(line) {
249
+ line.sort(sortComparator);
250
+ }
251
+ function sortComparator(a, b) {
252
+ return a[0] - b[0];
253
+ }
254
+ var resolveUri_umd$1 = { exports: {} };
255
+ var resolveUri_umd = resolveUri_umd$1.exports;
256
+ var hasRequiredResolveUri_umd;
257
+ function requireResolveUri_umd() {
258
+ if (hasRequiredResolveUri_umd) return resolveUri_umd$1.exports;
259
+ hasRequiredResolveUri_umd = 1;
260
+ (function(module, exports$1) {
261
+ (function(global, factory) {
262
+ module.exports = factory();
263
+ })(resolveUri_umd, (function() {
264
+ const schemeRegex = /^[\w+.-]+:\/\//;
265
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
266
+ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
267
+ function isAbsoluteUrl(input) {
268
+ return schemeRegex.test(input);
269
+ }
270
+ function isSchemeRelativeUrl(input) {
271
+ return input.startsWith("//");
272
+ }
273
+ function isAbsolutePath(input) {
274
+ return input.startsWith("/");
275
+ }
276
+ function isFileUrl(input) {
277
+ return input.startsWith("file:");
278
+ }
279
+ function isRelative(input) {
280
+ return /^[.?#]/.test(input);
281
+ }
282
+ function parseAbsoluteUrl(input) {
283
+ const match = urlRegex.exec(input);
284
+ return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
285
+ }
286
+ function parseFileUrl(input) {
287
+ const match = fileRegex.exec(input);
288
+ const path = match[2];
289
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
290
+ }
291
+ function makeUrl(scheme, user, host, port, path, query, hash) {
292
+ return {
293
+ scheme,
294
+ user,
295
+ host,
296
+ port,
297
+ path,
298
+ query,
299
+ hash,
300
+ type: 7
301
+ };
302
+ }
303
+ function parseUrl(input) {
304
+ if (isSchemeRelativeUrl(input)) {
305
+ const url3 = parseAbsoluteUrl("http:" + input);
306
+ url3.scheme = "";
307
+ url3.type = 6;
308
+ return url3;
309
+ }
310
+ if (isAbsolutePath(input)) {
311
+ const url3 = parseAbsoluteUrl("http://foo.com" + input);
312
+ url3.scheme = "";
313
+ url3.host = "";
314
+ url3.type = 5;
315
+ return url3;
316
+ }
317
+ if (isFileUrl(input))
318
+ return parseFileUrl(input);
319
+ if (isAbsoluteUrl(input))
320
+ return parseAbsoluteUrl(input);
321
+ const url2 = parseAbsoluteUrl("http://foo.com/" + input);
322
+ url2.scheme = "";
323
+ url2.host = "";
324
+ url2.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
325
+ return url2;
326
+ }
327
+ function stripPathFilename(path) {
328
+ if (path.endsWith("/.."))
329
+ return path;
330
+ const index = path.lastIndexOf("/");
331
+ return path.slice(0, index + 1);
332
+ }
333
+ function mergePaths(url2, base) {
334
+ normalizePath(base, base.type);
335
+ if (url2.path === "/") {
336
+ url2.path = base.path;
337
+ } else {
338
+ url2.path = stripPathFilename(base.path) + url2.path;
339
+ }
340
+ }
341
+ function normalizePath(url2, type) {
342
+ const rel = type <= 4;
343
+ const pieces = url2.path.split("/");
344
+ let pointer = 1;
345
+ let positive = 0;
346
+ let addTrailingSlash = false;
347
+ for (let i = 1; i < pieces.length; i++) {
348
+ const piece = pieces[i];
349
+ if (!piece) {
350
+ addTrailingSlash = true;
351
+ continue;
352
+ }
353
+ addTrailingSlash = false;
354
+ if (piece === ".")
355
+ continue;
356
+ if (piece === "..") {
357
+ if (positive) {
358
+ addTrailingSlash = true;
359
+ positive--;
360
+ pointer--;
361
+ } else if (rel) {
362
+ pieces[pointer++] = piece;
363
+ }
364
+ continue;
365
+ }
366
+ pieces[pointer++] = piece;
367
+ positive++;
368
+ }
369
+ let path = "";
370
+ for (let i = 1; i < pointer; i++) {
371
+ path += "/" + pieces[i];
372
+ }
373
+ if (!path || addTrailingSlash && !path.endsWith("/..")) {
374
+ path += "/";
375
+ }
376
+ url2.path = path;
377
+ }
378
+ function resolve2(input, base) {
379
+ if (!input && !base)
380
+ return "";
381
+ const url2 = parseUrl(input);
382
+ let inputType = url2.type;
383
+ if (base && inputType !== 7) {
384
+ const baseUrl = parseUrl(base);
385
+ const baseType = baseUrl.type;
386
+ switch (inputType) {
387
+ case 1:
388
+ url2.hash = baseUrl.hash;
389
+ // fall through
390
+ case 2:
391
+ url2.query = baseUrl.query;
392
+ // fall through
393
+ case 3:
394
+ case 4:
395
+ mergePaths(url2, baseUrl);
396
+ // fall through
397
+ case 5:
398
+ url2.user = baseUrl.user;
399
+ url2.host = baseUrl.host;
400
+ url2.port = baseUrl.port;
401
+ // fall through
402
+ case 6:
403
+ url2.scheme = baseUrl.scheme;
404
+ }
405
+ if (baseType > inputType)
406
+ inputType = baseType;
407
+ }
408
+ normalizePath(url2, inputType);
409
+ const queryHash = url2.query + url2.hash;
410
+ switch (inputType) {
411
+ // This is impossible, because of the empty checks at the start of the function.
412
+ // case UrlType.Empty:
413
+ case 2:
414
+ case 3:
415
+ return queryHash;
416
+ case 4: {
417
+ const path = url2.path.slice(1);
418
+ if (!path)
419
+ return queryHash || ".";
420
+ if (isRelative(base || input) && !isRelative(path)) {
421
+ return "./" + path + queryHash;
422
+ }
423
+ return path + queryHash;
424
+ }
425
+ case 5:
426
+ return url2.path + queryHash;
427
+ default:
428
+ return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash;
429
+ }
430
+ }
431
+ return resolve2;
432
+ }));
433
+ })(resolveUri_umd$1);
434
+ return resolveUri_umd$1.exports;
435
+ }
436
+ requireResolveUri_umd();
437
+ var COLUMN = 0;
438
+ var SOURCES_INDEX = 1;
439
+ var SOURCE_LINE = 2;
440
+ var SOURCE_COLUMN = 3;
441
+ var NAMES_INDEX = 4;
442
+ var found = false;
443
+ function binarySearch(haystack, needle, low, high) {
444
+ while (low <= high) {
445
+ const mid = low + (high - low >> 1);
446
+ const cmp = haystack[mid][COLUMN] - needle;
447
+ if (cmp === 0) {
448
+ found = true;
449
+ return mid;
450
+ }
451
+ if (cmp < 0) {
452
+ low = mid + 1;
453
+ } else {
454
+ high = mid - 1;
455
+ }
456
+ }
457
+ found = false;
458
+ return low - 1;
459
+ }
460
+ function upperBound(haystack, needle, index) {
461
+ for (let i = index + 1; i < haystack.length; index = i++) {
462
+ if (haystack[i][COLUMN] !== needle) break;
463
+ }
464
+ return index;
465
+ }
466
+ function lowerBound(haystack, needle, index) {
467
+ for (let i = index - 1; i >= 0; index = i--) {
468
+ if (haystack[i][COLUMN] !== needle) break;
469
+ }
470
+ return index;
471
+ }
472
+ function memoizedBinarySearch(haystack, needle, state, key) {
473
+ const { lastKey, lastNeedle, lastIndex } = state;
474
+ let low = 0;
475
+ let high = haystack.length - 1;
476
+ if (key === lastKey) {
477
+ if (needle === lastNeedle) {
478
+ found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
479
+ return lastIndex;
480
+ }
481
+ if (needle >= lastNeedle) {
482
+ low = lastIndex === -1 ? 0 : lastIndex;
483
+ } else {
484
+ high = lastIndex;
485
+ }
486
+ }
487
+ state.lastKey = key;
488
+ state.lastNeedle = needle;
489
+ return state.lastIndex = binarySearch(haystack, needle, low, high);
490
+ }
491
+ var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
492
+ var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
493
+ var LEAST_UPPER_BOUND = -1;
494
+ var GREATEST_LOWER_BOUND = 1;
495
+ function cast(map) {
496
+ return map;
497
+ }
498
+ function decodedMappings(map) {
499
+ var _a;
500
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
501
+ }
502
+ function originalPositionFor(map, needle) {
503
+ let { line, column, bias } = needle;
504
+ line--;
505
+ if (line < 0) throw new Error(LINE_GTR_ZERO);
506
+ if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
507
+ const decoded = decodedMappings(map);
508
+ if (line >= decoded.length) return OMapping(null, null, null, null);
509
+ const segments = decoded[line];
510
+ const index = traceSegmentInternal(
511
+ segments,
512
+ cast(map)._decodedMemo,
513
+ line,
514
+ column,
515
+ bias || GREATEST_LOWER_BOUND
516
+ );
517
+ if (index === -1) return OMapping(null, null, null, null);
518
+ const segment = segments[index];
519
+ if (segment.length === 1) return OMapping(null, null, null, null);
520
+ const { names, resolvedSources } = map;
521
+ return OMapping(
522
+ resolvedSources[segment[SOURCES_INDEX]],
523
+ segment[SOURCE_LINE] + 1,
524
+ segment[SOURCE_COLUMN],
525
+ segment.length === 5 ? names[segment[NAMES_INDEX]] : null
526
+ );
527
+ }
528
+ function OMapping(source, line, column, name) {
529
+ return { source, line, column, name };
530
+ }
531
+ function traceSegmentInternal(segments, memo, line, column, bias) {
532
+ let index = memoizedBinarySearch(segments, column, memo, line);
533
+ if (found) {
534
+ index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
535
+ } else if (bias === LEAST_UPPER_BOUND) index++;
536
+ if (index === -1 || index === segments.length) return -1;
537
+ return index;
538
+ }
539
+ function notNullish(v) {
540
+ return v != null;
541
+ }
542
+ const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
543
+ const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
544
+ const stackIgnorePatterns = [
545
+ "node:internal",
546
+ /\/packages\/\w+\/dist\//,
547
+ /\/@vitest\/\w+\/dist\//,
548
+ "/vitest/dist/",
549
+ "/vitest/src/",
550
+ "/node_modules/chai/",
551
+ "/node_modules/tinyspy/",
552
+ "/vite/dist/node/module-runner",
553
+ "/rolldown-vite/dist/node/module-runner",
554
+ // browser related deps
555
+ "/deps/chunk-",
556
+ "/deps/@vitest",
557
+ "/deps/loupe",
558
+ "/deps/chai",
559
+ "/browser-playwright/dist/locators.js",
560
+ "/browser-webdriverio/dist/locators.js",
561
+ "/browser-preview/dist/locators.js",
562
+ /node:\w+/,
563
+ /__vitest_test__/,
564
+ /__vitest_browser__/,
565
+ /\/deps\/vitest_/
566
+ ];
567
+ function extractLocation(urlLike) {
568
+ if (!urlLike.includes(":")) {
569
+ return [urlLike];
570
+ }
571
+ const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
572
+ const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
573
+ if (!parts) {
574
+ return [urlLike];
575
+ }
576
+ let url2 = parts[1];
577
+ if (url2.startsWith("async ")) {
578
+ url2 = url2.slice(6);
579
+ }
580
+ if (url2.startsWith("http:") || url2.startsWith("https:")) {
581
+ const urlObj = new URL(url2);
582
+ urlObj.searchParams.delete("import");
583
+ urlObj.searchParams.delete("browserv");
584
+ url2 = urlObj.pathname + urlObj.hash + urlObj.search;
585
+ }
586
+ if (url2.startsWith("/@fs/")) {
587
+ const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url2);
588
+ url2 = url2.slice(isWindows ? 5 : 4);
589
+ }
590
+ return [url2, parts[2] || void 0, parts[3] || void 0];
591
+ }
592
+ function parseSingleFFOrSafariStack(raw) {
593
+ let line = raw.trim();
594
+ if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
595
+ return null;
596
+ }
597
+ if (line.includes(" > eval")) {
598
+ line = line.replace(
599
+ / line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,
600
+ ":$1"
601
+ );
602
+ }
603
+ if (!line.includes("@")) {
604
+ return null;
605
+ }
606
+ let atIndex = -1;
607
+ let locationPart = "";
608
+ let functionName;
609
+ for (let i = 0; i < line.length; i++) {
610
+ if (line[i] === "@") {
611
+ const candidateLocation = line.slice(i + 1);
612
+ if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
613
+ atIndex = i;
614
+ locationPart = candidateLocation;
615
+ functionName = i > 0 ? line.slice(0, i) : void 0;
616
+ break;
617
+ }
618
+ }
619
+ }
620
+ if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
621
+ return null;
622
+ }
623
+ const [url2, lineNumber, columnNumber] = extractLocation(locationPart);
624
+ if (!url2 || !lineNumber || !columnNumber) {
625
+ return null;
626
+ }
627
+ return {
628
+ file: url2,
629
+ method: functionName || "",
630
+ line: Number.parseInt(lineNumber),
631
+ column: Number.parseInt(columnNumber)
632
+ };
633
+ }
634
+ function parseSingleV8Stack(raw) {
635
+ let line = raw.trim();
636
+ if (!CHROME_IE_STACK_REGEXP.test(line)) {
637
+ return null;
638
+ }
639
+ if (line.includes("(eval ")) {
640
+ line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
641
+ }
642
+ let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
643
+ const location2 = sanitizedLine.match(/ (\(.+\)$)/);
644
+ sanitizedLine = location2 ? sanitizedLine.replace(location2[0], "") : sanitizedLine;
645
+ const [url2, lineNumber, columnNumber] = extractLocation(
646
+ location2 ? location2[1] : sanitizedLine
647
+ );
648
+ let method = location2 && sanitizedLine || "";
649
+ let file = url2 && ["eval", "<anonymous>"].includes(url2) ? void 0 : url2;
650
+ if (!file || !lineNumber || !columnNumber) {
651
+ return null;
652
+ }
653
+ if (method.startsWith("async ")) {
654
+ method = method.slice(6);
655
+ }
656
+ if (file.startsWith("file://")) {
657
+ file = file.slice(7);
658
+ }
659
+ file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
660
+ if (method) {
661
+ method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
662
+ }
663
+ return {
664
+ method,
665
+ file,
666
+ line: Number.parseInt(lineNumber),
667
+ column: Number.parseInt(columnNumber)
668
+ };
669
+ }
670
+ function createStackString(stacks) {
671
+ return stacks.map((stack) => {
672
+ const line = `${stack.file}:${stack.line}:${stack.column}`;
673
+ if (stack.method) {
674
+ return ` at ${stack.method}(${line})`;
675
+ }
676
+ return ` at ${line}`;
677
+ }).join("\n");
678
+ }
679
+ function parseStacktrace(stack, options = {}) {
680
+ const { ignoreStackEntries = stackIgnorePatterns } = options;
681
+ const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
682
+ return stacks.map((stack2) => {
683
+ var _a;
684
+ if (options.getUrlId) {
685
+ stack2.file = options.getUrlId(stack2.file);
686
+ }
687
+ const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file);
688
+ if (!map || typeof map !== "object" || !map.version) {
689
+ return shouldFilter(ignoreStackEntries, stack2.file) ? null : stack2;
690
+ }
691
+ const traceMap = new DecodedMap(map, stack2.file);
692
+ const position = getOriginalPosition(traceMap, stack2);
693
+ if (!position) {
694
+ return stack2;
695
+ }
696
+ const { line, column, source, name } = position;
697
+ let file = source || stack2.file;
698
+ if (file.match(/\/\w:\//)) {
699
+ file = file.slice(1);
700
+ }
701
+ if (shouldFilter(ignoreStackEntries, file)) {
702
+ return null;
703
+ }
704
+ if (line != null && column != null) {
705
+ return {
706
+ line,
707
+ column,
708
+ file,
709
+ method: name || stack2.method
710
+ };
711
+ }
712
+ return stack2;
713
+ }).filter((s) => s != null);
714
+ }
715
+ function shouldFilter(ignoreStackEntries, file) {
716
+ return ignoreStackEntries.some((p) => file.match(p));
717
+ }
718
+ function parseFFOrSafariStackTrace(stack) {
719
+ return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
720
+ }
721
+ function parseV8Stacktrace(stack) {
722
+ return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
723
+ }
724
+ class DecodedMap {
725
+ constructor(map, from) {
726
+ this.map = map;
727
+ const { mappings, names, sources } = map;
728
+ this.version = map.version;
729
+ this.names = names || [];
730
+ this._encoded = mappings || "";
731
+ this._decodedMemo = memoizedState();
732
+ this.url = from;
733
+ this.resolvedSources = (sources || []).map(
734
+ (s) => resolve(s || "", from)
735
+ );
736
+ }
737
+ _encoded;
738
+ _decoded;
739
+ _decodedMemo;
740
+ url;
741
+ version;
742
+ names = [];
743
+ resolvedSources;
744
+ }
745
+ function memoizedState() {
746
+ return {
747
+ lastKey: -1,
748
+ lastNeedle: -1,
749
+ lastIndex: -1
750
+ };
751
+ }
752
+ function getOriginalPosition(map, needle) {
753
+ const result = originalPositionFor(map, needle);
754
+ if (result.column == null) {
755
+ return null;
756
+ }
757
+ return result;
758
+ }
759
+ class VitestBrowserSnapshotEnvironment {
760
+ sourceMaps = /* @__PURE__ */ new Map();
761
+ traceMaps = /* @__PURE__ */ new Map();
762
+ addSourceMap(filepath, map) {
763
+ this.sourceMaps.set(filepath, map);
764
+ }
765
+ getVersion() {
766
+ return "1";
767
+ }
768
+ getHeader() {
769
+ return `// Vitest Snapshot v${this.getVersion()}, https://vitest.dev/guide/snapshot.html`;
770
+ }
771
+ readSnapshotFile(filepath) {
772
+ return rpc$1().readSnapshotFile(filepath);
773
+ }
774
+ saveSnapshotFile(filepath, snapshot) {
775
+ return rpc$1().saveSnapshotFile(filepath, snapshot);
776
+ }
777
+ resolvePath(filepath) {
778
+ return rpc$1().resolveSnapshotPath(filepath);
779
+ }
780
+ resolveRawPath(testPath, rawPath) {
781
+ return rpc$1().resolveSnapshotRawPath(testPath, rawPath);
782
+ }
783
+ removeSnapshotFile(filepath) {
784
+ return rpc$1().removeSnapshotFile(filepath);
785
+ }
786
+ processStackTrace(stack) {
787
+ const map = this.sourceMaps.get(stack.file);
788
+ if (!map) {
789
+ return stack;
790
+ }
791
+ let traceMap = this.traceMaps.get(stack.file);
792
+ if (!traceMap) {
793
+ traceMap = new DecodedMap$1(map, stack.file);
794
+ this.traceMaps.set(stack.file, traceMap);
795
+ }
796
+ const position = getOriginalPosition$1(traceMap, stack);
797
+ if (position) {
798
+ return { ...stack, line: position.line, column: position.column };
799
+ }
800
+ return stack;
801
+ }
802
+ }
803
+ function rpc$1() {
804
+ return globalThis.__vitest_worker__.rpc;
805
+ }
806
+ const browserHashMap = /* @__PURE__ */ new Map();
807
+ function createBrowserRunner(runnerClass, mocker, state, coverageModule) {
808
+ return class BrowserTestRunner extends runnerClass {
809
+ config;
810
+ hashMap = browserHashMap;
811
+ sourceMapCache = /* @__PURE__ */ new Map();
812
+ method = "run";
813
+ commands;
814
+ _otel;
815
+ constructor(options) {
816
+ super(options.config);
817
+ this.config = options.config;
818
+ this.commands = getBrowserState().commands;
819
+ this.viteEnvironment = "__browser__";
820
+ this._otel = getBrowserState().traces;
821
+ }
822
+ setMethod(method) {
823
+ this.method = method;
824
+ }
825
+ traces = /* @__PURE__ */ new Map();
826
+ onBeforeTryTask = async (...args) => {
827
+ var _a;
828
+ await userEvent.cleanup();
829
+ await ((_a = super.onBeforeTryTask) == null ? void 0 : _a.call(this, ...args));
830
+ const trace = this.config.browser.trace;
831
+ const test = args[0];
832
+ if (trace === "off") {
833
+ return;
834
+ }
835
+ const { retry, repeats } = args[1];
836
+ if (trace === "on-all-retries" && retry === 0) {
837
+ return;
838
+ }
839
+ if (trace === "on-first-retry" && retry !== 1) {
840
+ return;
841
+ }
842
+ let title = getTestName(test);
843
+ if (retry) {
844
+ title += ` (retry x${retry})`;
845
+ }
846
+ if (repeats) {
847
+ title += ` (repeat x${repeats})`;
848
+ }
849
+ const name = getTraceName(test, retry, repeats);
850
+ await this.commands.triggerCommand(
851
+ "__vitest_startChunkTrace",
852
+ [{ name, title }]
853
+ );
854
+ };
855
+ onAfterRetryTask = async (test, { retry, repeats }) => {
856
+ const trace = this.config.browser.trace;
857
+ if (trace === "off") {
858
+ return;
859
+ }
860
+ if (trace === "on-all-retries" && retry === 0) {
861
+ return;
862
+ }
863
+ if (trace === "on-first-retry" && retry !== 1) {
864
+ return;
865
+ }
866
+ const name = getTraceName(test, retry, repeats);
867
+ if (!this.traces.has(test.id)) {
868
+ this.traces.set(test.id, []);
869
+ }
870
+ const traces2 = this.traces.get(test.id);
871
+ const { tracePath } = await this.commands.triggerCommand(
872
+ "__vitest_stopChunkTrace",
873
+ [{ name }]
874
+ );
875
+ traces2.push(tracePath);
876
+ };
877
+ onAfterRunTask = async (task) => {
878
+ var _a, _b, _c;
879
+ await ((_a = super.onAfterRunTask) == null ? void 0 : _a.call(this, task));
880
+ const trace = this.config.browser.trace;
881
+ const traces2 = this.traces.get(task.id) || [];
882
+ if (traces2.length) {
883
+ if (trace === "retain-on-failure" && ((_b = task.result) == null ? void 0 : _b.state) === "pass") {
884
+ await this.commands.triggerCommand(
885
+ "__vitest_deleteTracing",
886
+ [{ traces: traces2 }]
887
+ );
888
+ } else {
889
+ await this.commands.triggerCommand(
890
+ "__vitest_annotateTraces",
891
+ [{ testId: task.id, traces: traces2 }]
892
+ );
893
+ }
894
+ }
895
+ if (this.config.bail && ((_c = task.result) == null ? void 0 : _c.state) === "fail") {
896
+ const previousFailures = await rpc$2().getCountOfFailedTests();
897
+ const currentFailures = 1 + previousFailures;
898
+ if (currentFailures >= this.config.bail) {
899
+ rpc$2().cancelCurrentRun("test-failure");
900
+ this.cancel("test-failure");
901
+ }
902
+ }
903
+ };
904
+ onTaskFinished = async (task) => {
905
+ var _a, _b;
906
+ if (this.config.browser.screenshotFailures && document.body.clientHeight > 0 && ((_a = task.result) == null ? void 0 : _a.state) === "fail") {
907
+ const screenshot = await page.screenshot(
908
+ {
909
+ timeout: ((_b = this.config.browser.providerOptions) == null ? void 0 : _b.actionTimeout) ?? 5e3
910
+ }
911
+ /** TODO */
912
+ ).catch((err) => {
913
+ console.error("[vitest] Failed to take a screenshot", err);
914
+ });
915
+ if (screenshot) {
916
+ task.meta.failScreenshotPath = screenshot;
917
+ }
918
+ }
919
+ };
920
+ cancel = (reason) => {
921
+ var _a;
922
+ (_a = super.cancel) == null ? void 0 : _a.call(this, reason);
923
+ globalChannel.postMessage({ type: "cancel", reason });
924
+ };
925
+ onBeforeRunSuite = async (suite) => {
926
+ var _a;
927
+ await Promise.all([
928
+ (_a = super.onBeforeRunSuite) == null ? void 0 : _a.call(this, suite),
929
+ (async () => {
930
+ if (!("filepath" in suite)) {
931
+ return;
932
+ }
933
+ const map = await rpc$2().getBrowserFileSourceMap(suite.filepath);
934
+ this.sourceMapCache.set(suite.filepath, map);
935
+ const snapshotEnvironment = this.config.snapshotOptions.snapshotEnvironment;
936
+ if (snapshotEnvironment instanceof VitestBrowserSnapshotEnvironment) {
937
+ snapshotEnvironment.addSourceMap(suite.filepath, map);
938
+ }
939
+ })()
940
+ ]);
941
+ };
942
+ onAfterRunFiles = async (files) => {
943
+ var _a, _b;
944
+ const [coverage] = await Promise.all([
945
+ (_a = coverageModule == null ? void 0 : coverageModule.takeCoverage) == null ? void 0 : _a.call(coverageModule),
946
+ mocker.invalidate(),
947
+ (_b = super.onAfterRunFiles) == null ? void 0 : _b.call(this, files)
948
+ ]);
949
+ if (coverage) {
950
+ await rpc$2().onAfterSuiteRun({
951
+ coverage,
952
+ testFiles: files.map((file) => file.name),
953
+ environment: "__browser__",
954
+ projectName: this.config.name
955
+ });
956
+ }
957
+ };
958
+ onCollectStart = (file) => {
959
+ return rpc$2().onQueued(this.method, file);
960
+ };
961
+ onCollected = async (files) => {
962
+ files.forEach((file) => {
963
+ file.prepareDuration = state.durations.prepare;
964
+ file.environmentLoad = state.durations.environment;
965
+ state.durations.prepare = 0;
966
+ state.durations.environment = 0;
967
+ });
968
+ if (this.config.includeTaskLocation) {
969
+ try {
970
+ await updateTestFilesLocations(files, this.sourceMapCache);
971
+ } catch {
972
+ }
973
+ }
974
+ return rpc$2().onCollected(this.method, files);
975
+ };
976
+ onTestAnnotate = (test, annotation) => {
977
+ const artifact = { type: "internal:annotation", annotation, location: annotation.location };
978
+ return this.onTestArtifactRecord(test, artifact).then(({ annotation: annotation2 }) => annotation2);
979
+ };
980
+ onTestArtifactRecord = (test, artifact) => {
981
+ if (artifact.location) {
982
+ const map = this.sourceMapCache.get(artifact.location.file);
983
+ if (!map) {
984
+ return rpc$2().onTaskArtifactRecord(test.id, artifact);
985
+ }
986
+ const traceMap = new DecodedMap$1(map, artifact.location.file);
987
+ const position = getOriginalPosition$1(traceMap, artifact.location);
988
+ if (position) {
989
+ const { source, column, line } = position;
990
+ const file = source || artifact.location.file;
991
+ artifact.location = {
992
+ line,
993
+ column: column + 1,
994
+ // if the file path is on windows, we need to remove the starting slash
995
+ file: file.match(/\/\w:\//) ? file.slice(1) : file
996
+ };
997
+ if (artifact.type === "internal:annotation") {
998
+ artifact.annotation.location = artifact.location;
999
+ }
1000
+ }
1001
+ }
1002
+ return rpc$2().onTaskArtifactRecord(test.id, artifact);
1003
+ };
1004
+ onTaskUpdate = (task, events) => {
1005
+ return rpc$2().onTaskUpdate(this.method, task, events);
1006
+ };
1007
+ importFile = async (filepath, mode) => {
1008
+ let hash = this.hashMap.get(filepath);
1009
+ if (mode === "setup" || !hash) {
1010
+ hash = Date.now().toString();
1011
+ this.hashMap.set(filepath, hash);
1012
+ }
1013
+ const prefix = `/${/^\w:/.test(filepath) ? "@fs/" : ""}`;
1014
+ const query = `browserv=${hash}`;
1015
+ const importpath = `${prefix}${filepath}?${query}`.replace(/\/+/g, "/");
1016
+ const trace = this.config.browser.trace;
1017
+ if (mode === "collect" && trace !== "off") {
1018
+ await this.commands.triggerCommand("__vitest_startTracing", []);
1019
+ }
1020
+ try {
1021
+ await import(
1022
+ /* @vite-ignore */
1023
+ importpath
1024
+ );
1025
+ } catch (err) {
1026
+ throw new Error(`Failed to import test file ${filepath}`, { cause: err });
1027
+ }
1028
+ };
1029
+ trace = (name, attributes, cb) => {
1030
+ const options = typeof attributes === "object" ? { attributes } : {};
1031
+ return this._otel.$(`vitest.test.runner.${name}`, options, cb || attributes);
1032
+ };
1033
+ };
1034
+ }
1035
+ let cachedRunner = null;
1036
+ function getBrowserRunner() {
1037
+ return cachedRunner;
1038
+ }
1039
+ async function initiateRunner(state, mocker, config) {
1040
+ if (cachedRunner) {
1041
+ return cachedRunner;
1042
+ }
1043
+ const runnerClass = config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
1044
+ const BrowserRunner = createBrowserRunner(runnerClass, mocker, state, {
1045
+ takeCoverage: () => takeCoverageInsideWorker(config.coverage, moduleRunner)
1046
+ });
1047
+ if (!config.snapshotOptions.snapshotEnvironment) {
1048
+ config.snapshotOptions.snapshotEnvironment = new VitestBrowserSnapshotEnvironment();
1049
+ }
1050
+ const runner = new BrowserRunner({
1051
+ config
1052
+ });
1053
+ cachedRunner = runner;
1054
+ onCancel((reason) => {
1055
+ var _a;
1056
+ (_a = runner.cancel) == null ? void 0 : _a.call(runner, reason);
1057
+ });
1058
+ const [diffOptions] = await Promise.all([
1059
+ loadDiffConfig(config, moduleRunner),
1060
+ loadSnapshotSerializers(config, moduleRunner)
1061
+ ]);
1062
+ runner.config.diffOptions = diffOptions;
1063
+ getWorkerState().onFilterStackTrace = (stack) => {
1064
+ const stacks = parseStacktrace(stack, {
1065
+ getSourceMap(file) {
1066
+ return runner.sourceMapCache.get(file);
1067
+ }
1068
+ });
1069
+ return createStackString(stacks);
1070
+ };
1071
+ return runner;
1072
+ }
1073
+ async function getTraceMap(file, sourceMaps) {
1074
+ const result = sourceMaps.get(file) || await rpc$2().getBrowserFileSourceMap(file).then((map) => {
1075
+ sourceMaps.set(file, map);
1076
+ return map;
1077
+ });
1078
+ if (!result) {
1079
+ return null;
1080
+ }
1081
+ return new DecodedMap$1(result, file);
1082
+ }
1083
+ async function updateTestFilesLocations(files, sourceMaps) {
1084
+ const promises2 = files.map(async (file) => {
1085
+ const traceMap = await getTraceMap(file.filepath, sourceMaps);
1086
+ if (!traceMap) {
1087
+ return null;
1088
+ }
1089
+ const updateLocation = (task) => {
1090
+ if (task.location) {
1091
+ const position = getOriginalPosition$1(traceMap, task.location);
1092
+ if (position) {
1093
+ const { line, column } = position;
1094
+ task.location = { line, column: task.each ? column : column + 1 };
1095
+ }
1096
+ }
1097
+ if ("tasks" in task) {
1098
+ task.tasks.forEach(updateLocation);
1099
+ }
1100
+ };
1101
+ file.tasks.forEach(updateLocation);
1102
+ return null;
1103
+ });
1104
+ await Promise.all(promises2);
1105
+ }
1106
+ function getTraceName(task, retryCount, repeatsCount) {
1107
+ const name = getTestName(task, "-").replace(/[^a-z0-9]/gi, "-");
1108
+ return `${name}-${repeatsCount}-${retryCount}`;
1109
+ }
1110
+ const { Date: Date$1, console: console$1, performance: performance$1 } = globalThis;
1111
+ function setupConsoleLogSpy() {
1112
+ const {
1113
+ log,
1114
+ info,
1115
+ error,
1116
+ dir,
1117
+ dirxml,
1118
+ trace,
1119
+ time,
1120
+ timeEnd,
1121
+ timeLog,
1122
+ warn,
1123
+ debug: debug2,
1124
+ count,
1125
+ countReset
1126
+ } = console$1;
1127
+ console$1.log = stdout(log);
1128
+ console$1.debug = stdout(debug2);
1129
+ console$1.info = stdout(info);
1130
+ console$1.error = stderr(error);
1131
+ console$1.warn = stderr(warn);
1132
+ console$1.dir = (item, options) => {
1133
+ dir(item, options);
1134
+ sendLog("stdout", browserFormat(item));
1135
+ };
1136
+ console$1.dirxml = (...args) => {
1137
+ dirxml(...args);
1138
+ sendLog("stdout", processLog(args));
1139
+ };
1140
+ console$1.trace = (...args) => {
1141
+ var _a;
1142
+ trace(...args);
1143
+ const content = processLog(args);
1144
+ const error2 = new Error("$$Trace");
1145
+ const processor = ((_a = globalThis.__vitest_worker__) == null ? void 0 : _a.onFilterStackTrace) || ((s) => s || "");
1146
+ const stack = processor(error2.stack || "");
1147
+ sendLog("stderr", `${content}
1148
+ ${stack}`, true);
1149
+ };
1150
+ const timeLabels = {};
1151
+ console$1.time = (label = "default") => {
1152
+ time(label);
1153
+ const now2 = performance$1.now();
1154
+ timeLabels[label] = now2;
1155
+ };
1156
+ console$1.timeLog = (label = "default") => {
1157
+ timeLog(label);
1158
+ if (!(label in timeLabels)) {
1159
+ sendLog("stderr", `Timer "${label}" does not exist`);
1160
+ } else {
1161
+ sendLog("stdout", `${label}: ${timeLabels[label]} ms`);
1162
+ }
1163
+ };
1164
+ console$1.timeEnd = (label = "default") => {
1165
+ timeEnd(label);
1166
+ const end = performance$1.now();
1167
+ const start = timeLabels[label];
1168
+ if (!(label in timeLabels)) {
1169
+ sendLog("stderr", `Timer "${label}" does not exist`);
1170
+ } else if (typeof start !== "undefined") {
1171
+ const duration = end - start;
1172
+ sendLog("stdout", `${label}: ${duration} ms`);
1173
+ }
1174
+ };
1175
+ const countLabels = {};
1176
+ console$1.count = (label = "default") => {
1177
+ count(label);
1178
+ const counter = (countLabels[label] ?? 0) + 1;
1179
+ countLabels[label] = counter;
1180
+ sendLog("stdout", `${label}: ${counter}`);
1181
+ };
1182
+ console$1.countReset = (label = "default") => {
1183
+ countReset(label);
1184
+ countLabels[label] = 0;
1185
+ };
1186
+ }
1187
+ function stdout(base) {
1188
+ return (...args) => {
1189
+ base(...args);
1190
+ if (args[0] === "[WDIO]") {
1191
+ if (args[1] === "newShadowRoot" || args[1] === "removeShadowRoot") {
1192
+ return;
1193
+ }
1194
+ }
1195
+ sendLog("stdout", processLog(args));
1196
+ };
1197
+ }
1198
+ function stderr(base) {
1199
+ return (...args) => {
1200
+ base(...args);
1201
+ sendLog("stderr", processLog(args));
1202
+ };
1203
+ }
1204
+ function processLog(args) {
1205
+ return browserFormat(...args);
1206
+ }
1207
+ function sendLog(type, content, disableStack) {
1208
+ var _a, _b, _c;
1209
+ if (content.startsWith("[vite]")) {
1210
+ return;
1211
+ }
1212
+ const unknownTestId = "__vitest__unknown_test__";
1213
+ const taskId = ((_b = (_a = globalThis.__vitest_worker__) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
1214
+ const origin = getConfig().printConsoleTrace && !disableStack ? (_c = new Error("STACK_TRACE").stack) == null ? void 0 : _c.split("\n").slice(1).join("\n") : void 0;
1215
+ const runner = getBrowserRunner();
1216
+ rpc$2().sendLog((runner == null ? void 0 : runner.method) || "run", {
1217
+ origin,
1218
+ content,
1219
+ browser: true,
1220
+ time: Date$1.now(),
1221
+ taskId,
1222
+ type,
1223
+ size: content.length
1224
+ });
1225
+ }
1226
+ class MockerRegistry {
1227
+ registryByUrl = /* @__PURE__ */ new Map();
1228
+ registryById = /* @__PURE__ */ new Map();
1229
+ clear() {
1230
+ this.registryByUrl.clear();
1231
+ this.registryById.clear();
1232
+ }
1233
+ keys() {
1234
+ return this.registryByUrl.keys();
1235
+ }
1236
+ add(mock) {
1237
+ this.registryByUrl.set(mock.url, mock);
1238
+ this.registryById.set(mock.id, mock);
1239
+ }
1240
+ register(typeOrEvent, raw, id, url2, factoryOrRedirect) {
1241
+ const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent;
1242
+ if (typeof typeOrEvent === "object") {
1243
+ const event = typeOrEvent;
1244
+ if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) {
1245
+ throw new TypeError(`[vitest] Cannot register a mock that is already defined. Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". Use "registry.add()" to update a mock instead.`);
1246
+ }
1247
+ if (event.type === "automock") {
1248
+ const module = AutomockedModule.fromJSON(event);
1249
+ this.add(module);
1250
+ return module;
1251
+ } else if (event.type === "autospy") {
1252
+ const module = AutospiedModule.fromJSON(event);
1253
+ this.add(module);
1254
+ return module;
1255
+ } else if (event.type === "redirect") {
1256
+ const module = RedirectedModule.fromJSON(event);
1257
+ this.add(module);
1258
+ return module;
1259
+ } else if (event.type === "manual") {
1260
+ throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`);
1261
+ } else {
1262
+ throw new Error(`Unknown mock type: ${event.type}`);
1263
+ }
1264
+ }
1265
+ if (typeof raw !== "string") {
1266
+ throw new TypeError("[vitest] Mocks require a raw string.");
1267
+ }
1268
+ if (typeof url2 !== "string") {
1269
+ throw new TypeError("[vitest] Mocks require a url string.");
1270
+ }
1271
+ if (typeof id !== "string") {
1272
+ throw new TypeError("[vitest] Mocks require an id string.");
1273
+ }
1274
+ if (type === "manual") {
1275
+ if (typeof factoryOrRedirect !== "function") {
1276
+ throw new TypeError("[vitest] Manual mocks require a factory function.");
1277
+ }
1278
+ const mock = new ManualMockedModule(raw, id, url2, factoryOrRedirect);
1279
+ this.add(mock);
1280
+ return mock;
1281
+ } else if (type === "automock" || type === "autospy") {
1282
+ const mock = type === "automock" ? new AutomockedModule(raw, id, url2) : new AutospiedModule(raw, id, url2);
1283
+ this.add(mock);
1284
+ return mock;
1285
+ } else if (type === "redirect") {
1286
+ if (typeof factoryOrRedirect !== "string") {
1287
+ throw new TypeError("[vitest] Redirect mocks require a redirect string.");
1288
+ }
1289
+ const mock = new RedirectedModule(raw, id, url2, factoryOrRedirect);
1290
+ this.add(mock);
1291
+ return mock;
1292
+ } else {
1293
+ throw new Error(`[vitest] Unknown mock type: ${type}`);
1294
+ }
1295
+ }
1296
+ delete(id) {
1297
+ this.registryByUrl.delete(id);
1298
+ }
1299
+ deleteById(id) {
1300
+ this.registryById.delete(id);
1301
+ }
1302
+ get(id) {
1303
+ return this.registryByUrl.get(id);
1304
+ }
1305
+ getById(id) {
1306
+ return this.registryById.get(id);
1307
+ }
1308
+ has(id) {
1309
+ return this.registryByUrl.has(id);
1310
+ }
1311
+ }
1312
+ class AutomockedModule {
1313
+ type = "automock";
1314
+ constructor(raw, id, url2) {
1315
+ this.raw = raw;
1316
+ this.id = id;
1317
+ this.url = url2;
1318
+ }
1319
+ static fromJSON(data) {
1320
+ return new AutospiedModule(data.raw, data.id, data.url);
1321
+ }
1322
+ toJSON() {
1323
+ return {
1324
+ type: this.type,
1325
+ url: this.url,
1326
+ raw: this.raw,
1327
+ id: this.id
1328
+ };
1329
+ }
1330
+ }
1331
+ class AutospiedModule {
1332
+ type = "autospy";
1333
+ constructor(raw, id, url2) {
1334
+ this.raw = raw;
1335
+ this.id = id;
1336
+ this.url = url2;
1337
+ }
1338
+ static fromJSON(data) {
1339
+ return new AutospiedModule(data.raw, data.id, data.url);
1340
+ }
1341
+ toJSON() {
1342
+ return {
1343
+ type: this.type,
1344
+ url: this.url,
1345
+ id: this.id,
1346
+ raw: this.raw
1347
+ };
1348
+ }
1349
+ }
1350
+ class RedirectedModule {
1351
+ type = "redirect";
1352
+ constructor(raw, id, url2, redirect) {
1353
+ this.raw = raw;
1354
+ this.id = id;
1355
+ this.url = url2;
1356
+ this.redirect = redirect;
1357
+ }
1358
+ static fromJSON(data) {
1359
+ return new RedirectedModule(data.raw, data.id, data.url, data.redirect);
1360
+ }
1361
+ toJSON() {
1362
+ return {
1363
+ type: this.type,
1364
+ url: this.url,
1365
+ raw: this.raw,
1366
+ id: this.id,
1367
+ redirect: this.redirect
1368
+ };
1369
+ }
1370
+ }
1371
+ class ManualMockedModule {
1372
+ cache;
1373
+ type = "manual";
1374
+ constructor(raw, id, url2, factory) {
1375
+ this.raw = raw;
1376
+ this.id = id;
1377
+ this.url = url2;
1378
+ this.factory = factory;
1379
+ }
1380
+ async resolve() {
1381
+ if (this.cache) {
1382
+ return this.cache;
1383
+ }
1384
+ let exports$1;
1385
+ try {
1386
+ exports$1 = await this.factory();
1387
+ } catch (err) {
1388
+ const vitestError = new Error('[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock');
1389
+ vitestError.cause = err;
1390
+ throw vitestError;
1391
+ }
1392
+ if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
1393
+ throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
1394
+ }
1395
+ return this.cache = exports$1;
1396
+ }
1397
+ static fromJSON(data, factory) {
1398
+ return new ManualMockedModule(data.raw, data.id, data.url, factory);
1399
+ }
1400
+ toJSON() {
1401
+ return {
1402
+ type: this.type,
1403
+ url: this.url,
1404
+ id: this.id,
1405
+ raw: this.raw
1406
+ };
1407
+ }
1408
+ }
1409
+ function mockObject(options, object2, mockExports = {}) {
1410
+ const finalizers = new Array();
1411
+ const refs = new RefTracker();
1412
+ const define = (container, key, value) => {
1413
+ try {
1414
+ container[key] = value;
1415
+ return true;
1416
+ } catch {
1417
+ return false;
1418
+ }
1419
+ };
1420
+ const createMock = (currentValue) => {
1421
+ if (!options.createMockInstance) {
1422
+ throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
1423
+ }
1424
+ const createMockInstance = options.createMockInstance;
1425
+ const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
1426
+ return createMockInstance({
1427
+ name: currentValue.name,
1428
+ prototypeMembers,
1429
+ originalImplementation: options.type === "autospy" ? currentValue : void 0,
1430
+ keepMembersImplementation: options.type === "autospy"
1431
+ });
1432
+ };
1433
+ const mockPropertiesOf = (container, newContainer) => {
1434
+ const containerType = getType(container);
1435
+ const isModule = containerType === "Module" || !!container.__esModule;
1436
+ for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
1437
+ if (!isModule && descriptor.get) {
1438
+ try {
1439
+ if (options.type === "autospy") {
1440
+ Object.defineProperty(newContainer, property, descriptor);
1441
+ } else {
1442
+ Object.defineProperty(newContainer, property, {
1443
+ configurable: descriptor.configurable,
1444
+ enumerable: descriptor.enumerable,
1445
+ get: () => {
1446
+ },
1447
+ set: descriptor.set ? () => {
1448
+ } : void 0
1449
+ });
1450
+ }
1451
+ } catch {
1452
+ }
1453
+ continue;
1454
+ }
1455
+ if (isReadonlyProp(container[property], property)) {
1456
+ continue;
1457
+ }
1458
+ const value = container[property];
1459
+ const refId = refs.getId(value);
1460
+ if (refId !== void 0) {
1461
+ finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
1462
+ continue;
1463
+ }
1464
+ const type = getType(value);
1465
+ if (Array.isArray(value)) {
1466
+ if (options.type === "automock") {
1467
+ define(newContainer, property, []);
1468
+ } else {
1469
+ const array = value.map((value2) => {
1470
+ if (value2 && typeof value2 === "object") {
1471
+ const newObject = {};
1472
+ mockPropertiesOf(value2, newObject);
1473
+ return newObject;
1474
+ }
1475
+ if (typeof value2 === "function") {
1476
+ return createMock(value2);
1477
+ }
1478
+ return value2;
1479
+ });
1480
+ define(newContainer, property, array);
1481
+ }
1482
+ continue;
1483
+ }
1484
+ const isFunction = type.includes("Function") && typeof value === "function";
1485
+ if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
1486
+ define(newContainer, property, value);
1487
+ continue;
1488
+ }
1489
+ if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
1490
+ continue;
1491
+ }
1492
+ if (isFunction) {
1493
+ const mock = createMock(newContainer[property]);
1494
+ newContainer[property] = mock;
1495
+ }
1496
+ refs.track(value, newContainer[property]);
1497
+ mockPropertiesOf(value, newContainer[property]);
1498
+ }
1499
+ };
1500
+ const mockedObject = mockExports;
1501
+ mockPropertiesOf(object2, mockedObject);
1502
+ for (const finalizer of finalizers) {
1503
+ finalizer();
1504
+ }
1505
+ return mockedObject;
1506
+ }
1507
+ class RefTracker {
1508
+ idMap = /* @__PURE__ */ new Map();
1509
+ mockedValueMap = /* @__PURE__ */ new Map();
1510
+ getId(value) {
1511
+ return this.idMap.get(value);
1512
+ }
1513
+ getMockedValue(id) {
1514
+ return this.mockedValueMap.get(id);
1515
+ }
1516
+ track(originalValue, mockedValue) {
1517
+ const newId = this.idMap.size;
1518
+ this.idMap.set(originalValue, newId);
1519
+ this.mockedValueMap.set(newId, mockedValue);
1520
+ return newId;
1521
+ }
1522
+ }
1523
+ function getType(value) {
1524
+ return Object.prototype.toString.apply(value).slice(8, -1);
1525
+ }
1526
+ function isReadonlyProp(object2, prop) {
1527
+ if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
1528
+ const typeName = getType(object2);
1529
+ return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
1530
+ }
1531
+ if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
1532
+ return getType(object2) === "RegExp";
1533
+ }
1534
+ return false;
1535
+ }
1536
+ function getAllMockableProperties(obj, isModule, constructors) {
1537
+ const { Map: Map2, Object: Object2, Function: Function2, RegExp: RegExp2, Array: Array2 } = constructors;
1538
+ const allProps = new Map2();
1539
+ let curr = obj;
1540
+ do {
1541
+ if (curr === Object2.prototype || curr === Function2.prototype || curr === RegExp2.prototype) {
1542
+ break;
1543
+ }
1544
+ collectOwnProperties(curr, (key) => {
1545
+ const descriptor = Object2.getOwnPropertyDescriptor(curr, key);
1546
+ if (descriptor) {
1547
+ allProps.set(key, {
1548
+ key,
1549
+ descriptor
1550
+ });
1551
+ }
1552
+ });
1553
+ } while (curr = Object2.getPrototypeOf(curr));
1554
+ if (isModule && !allProps.has("default") && "default" in obj) {
1555
+ const descriptor = Object2.getOwnPropertyDescriptor(obj, "default");
1556
+ if (descriptor) {
1557
+ allProps.set("default", {
1558
+ key: "default",
1559
+ descriptor
1560
+ });
1561
+ }
1562
+ }
1563
+ return Array2.from(allProps.values());
1564
+ }
1565
+ function collectOwnProperties(obj, collector) {
1566
+ const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
1567
+ Object.getOwnPropertyNames(obj).forEach(collect);
1568
+ Object.getOwnPropertySymbols(obj).forEach(collect);
1569
+ }
1570
+ function collectFunctionProperties(prototype) {
1571
+ const properties = /* @__PURE__ */ new Set();
1572
+ collectOwnProperties(prototype, (prop) => {
1573
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
1574
+ if (!descriptor || descriptor.get) {
1575
+ return;
1576
+ }
1577
+ const type = getType(descriptor.value);
1578
+ if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
1579
+ properties.add(prop);
1580
+ }
1581
+ });
1582
+ return Array.from(properties);
1583
+ }
1584
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1585
+ function normalizeWindowsPath(input = "") {
1586
+ if (!input) {
1587
+ return input;
1588
+ }
1589
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1590
+ }
1591
+ const _UNC_REGEX = /^[/\\]{2}/;
1592
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1593
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
1594
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
1595
+ const normalize = function(path) {
1596
+ if (path.length === 0) {
1597
+ return ".";
1598
+ }
1599
+ path = normalizeWindowsPath(path);
1600
+ const isUNCPath = path.match(_UNC_REGEX);
1601
+ const isPathAbsolute = isAbsolute(path);
1602
+ const trailingSeparator = path[path.length - 1] === "/";
1603
+ path = normalizeString(path, !isPathAbsolute);
1604
+ if (path.length === 0) {
1605
+ if (isPathAbsolute) {
1606
+ return "/";
1607
+ }
1608
+ return trailingSeparator ? "./" : ".";
1609
+ }
1610
+ if (trailingSeparator) {
1611
+ path += "/";
1612
+ }
1613
+ if (_DRIVE_LETTER_RE.test(path)) {
1614
+ path += "/";
1615
+ }
1616
+ if (isUNCPath) {
1617
+ if (!isPathAbsolute) {
1618
+ return `//./${path}`;
1619
+ }
1620
+ return `//${path}`;
1621
+ }
1622
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
1623
+ };
1624
+ const join = function(...segments) {
1625
+ let path = "";
1626
+ for (const seg of segments) {
1627
+ if (!seg) {
1628
+ continue;
1629
+ }
1630
+ if (path.length > 0) {
1631
+ const pathTrailing = path[path.length - 1] === "/";
1632
+ const segLeading = seg[0] === "/";
1633
+ const both = pathTrailing && segLeading;
1634
+ if (both) {
1635
+ path += seg.slice(1);
1636
+ } else {
1637
+ path += pathTrailing || segLeading ? seg : `/${seg}`;
1638
+ }
1639
+ } else {
1640
+ path += seg;
1641
+ }
1642
+ }
1643
+ return normalize(path);
1644
+ };
1645
+ function normalizeString(path, allowAboveRoot) {
1646
+ let res = "";
1647
+ let lastSegmentLength = 0;
1648
+ let lastSlash = -1;
1649
+ let dots = 0;
1650
+ let char = null;
1651
+ for (let index = 0; index <= path.length; ++index) {
1652
+ if (index < path.length) {
1653
+ char = path[index];
1654
+ } else if (char === "/") {
1655
+ break;
1656
+ } else {
1657
+ char = "/";
1658
+ }
1659
+ if (char === "/") {
1660
+ if (lastSlash === index - 1 || dots === 1) ;
1661
+ else if (dots === 2) {
1662
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1663
+ if (res.length > 2) {
1664
+ const lastSlashIndex = res.lastIndexOf("/");
1665
+ if (lastSlashIndex === -1) {
1666
+ res = "";
1667
+ lastSegmentLength = 0;
1668
+ } else {
1669
+ res = res.slice(0, lastSlashIndex);
1670
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1671
+ }
1672
+ lastSlash = index;
1673
+ dots = 0;
1674
+ continue;
1675
+ } else if (res.length > 0) {
1676
+ res = "";
1677
+ lastSegmentLength = 0;
1678
+ lastSlash = index;
1679
+ dots = 0;
1680
+ continue;
1681
+ }
1682
+ }
1683
+ if (allowAboveRoot) {
1684
+ res += res.length > 0 ? "/.." : "..";
1685
+ lastSegmentLength = 2;
1686
+ }
1687
+ } else {
1688
+ if (res.length > 0) {
1689
+ res += `/${path.slice(lastSlash + 1, index)}`;
1690
+ } else {
1691
+ res = path.slice(lastSlash + 1, index);
1692
+ }
1693
+ lastSegmentLength = index - lastSlash - 1;
1694
+ }
1695
+ lastSlash = index;
1696
+ dots = 0;
1697
+ } else if (char === "." && dots !== -1) {
1698
+ ++dots;
1699
+ } else {
1700
+ dots = -1;
1701
+ }
1702
+ }
1703
+ return res;
1704
+ }
1705
+ const isAbsolute = function(p) {
1706
+ return _IS_ABSOLUTE_RE.test(p);
1707
+ };
1708
+ const extname = function(p) {
1709
+ if (p === "..") return "";
1710
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
1711
+ return match && match[1] || "";
1712
+ };
1713
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1714
+ var intToChar = new Uint8Array(64);
1715
+ var charToInt = new Uint8Array(128);
1716
+ for (let i = 0; i < chars.length; i++) {
1717
+ const c = chars.charCodeAt(i);
1718
+ intToChar[i] = c;
1719
+ charToInt[c] = i;
1720
+ }
1721
+ const { now } = Date;
1722
+ class ModuleMocker {
1723
+ registry = new MockerRegistry();
1724
+ queue = /* @__PURE__ */ new Set();
1725
+ mockedIds = /* @__PURE__ */ new Set();
1726
+ constructor(interceptor, rpc2, createMockInstance, config) {
1727
+ this.interceptor = interceptor;
1728
+ this.rpc = rpc2;
1729
+ this.createMockInstance = createMockInstance;
1730
+ this.config = config;
1731
+ }
1732
+ async prepare() {
1733
+ if (!this.queue.size) {
1734
+ return;
1735
+ }
1736
+ await Promise.all([...this.queue.values()]);
1737
+ }
1738
+ async resolveFactoryModule(id) {
1739
+ const mock = this.registry.get(id);
1740
+ if (!mock || mock.type !== "manual") {
1741
+ throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
1742
+ }
1743
+ const result = await mock.resolve();
1744
+ return result;
1745
+ }
1746
+ getFactoryModule(id) {
1747
+ const mock = this.registry.get(id);
1748
+ if (!mock || mock.type !== "manual") {
1749
+ throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
1750
+ }
1751
+ if (!mock.cache) {
1752
+ throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`);
1753
+ }
1754
+ return mock.cache;
1755
+ }
1756
+ async invalidate() {
1757
+ const ids = Array.from(this.mockedIds);
1758
+ if (!ids.length) {
1759
+ return;
1760
+ }
1761
+ await this.rpc.invalidate(ids);
1762
+ await this.interceptor.invalidate();
1763
+ this.registry.clear();
1764
+ }
1765
+ async importActual(id, importer) {
1766
+ const resolved = await this.rpc.resolveId(id, importer);
1767
+ if (resolved == null) {
1768
+ throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
1769
+ }
1770
+ const ext = extname(resolved.id);
1771
+ const url2 = new URL(resolved.url, location.href);
1772
+ const query = `_vitest_original&ext${ext}`;
1773
+ const actualUrl = `${url2.pathname}${url2.search ? `${url2.search}&${query}` : `?${query}`}${url2.hash}`;
1774
+ return this.wrapDynamicImport(() => import(
1775
+ /* @vite-ignore */
1776
+ actualUrl
1777
+ )).then((mod) => {
1778
+ if (!resolved.optimized || typeof mod.default === "undefined") {
1779
+ return mod;
1780
+ }
1781
+ const m = mod.default;
1782
+ return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : {
1783
+ ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
1784
+ default: m
1785
+ };
1786
+ });
1787
+ }
1788
+ async importMock(rawId, importer) {
1789
+ await this.prepare();
1790
+ const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
1791
+ const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
1792
+ let mock = this.registry.get(mockUrl);
1793
+ if (!mock) {
1794
+ if (redirectUrl) {
1795
+ const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
1796
+ mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
1797
+ } else {
1798
+ mock = new AutomockedModule(rawId, resolvedId, mockUrl);
1799
+ }
1800
+ }
1801
+ if (mock.type === "manual") {
1802
+ return await mock.resolve();
1803
+ }
1804
+ if (mock.type === "automock" || mock.type === "autospy") {
1805
+ const url2 = new URL(`/@id/${resolvedId}`, location.href);
1806
+ const query = url2.search ? `${url2.search}&t=${now()}` : `?t=${now()}`;
1807
+ const moduleObject = await __vitePreload(() => import(
1808
+ /* @vite-ignore */
1809
+ `${url2.pathname}${query}&mock=${mock.type}${url2.hash}`
1810
+ ), true ? [] : void 0);
1811
+ return this.mockObject(moduleObject, mock.type);
1812
+ }
1813
+ return import(
1814
+ /* @vite-ignore */
1815
+ mock.redirect
1816
+ );
1817
+ }
1818
+ mockObject(object2, moduleType = "automock") {
1819
+ return mockObject({
1820
+ globalConstructors: {
1821
+ Object,
1822
+ Function,
1823
+ Array,
1824
+ Map,
1825
+ RegExp
1826
+ },
1827
+ createMockInstance: this.createMockInstance,
1828
+ type: moduleType
1829
+ }, object2);
1830
+ }
1831
+ queueMock(rawId, importer, factoryOrOptions) {
1832
+ const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
1833
+ const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
1834
+ this.mockedIds.add(resolvedId);
1835
+ const factory = typeof factoryOrOptions === "function" ? async () => {
1836
+ const data = await factoryOrOptions();
1837
+ return needsInterop ? { default: data } : data;
1838
+ } : void 0;
1839
+ const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null;
1840
+ let module;
1841
+ if (mockType === "manual") {
1842
+ module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
1843
+ } else if (mockType === "autospy") {
1844
+ module = this.registry.register("autospy", rawId, resolvedId, mockUrl);
1845
+ } else if (mockType === "redirect") {
1846
+ module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect);
1847
+ } else {
1848
+ module = this.registry.register("automock", rawId, resolvedId, mockUrl);
1849
+ }
1850
+ await this.interceptor.register(module);
1851
+ }).finally(() => {
1852
+ this.queue.delete(promise);
1853
+ });
1854
+ this.queue.add(promise);
1855
+ }
1856
+ queueUnmock(id, importer) {
1857
+ const promise = this.rpc.resolveId(id, importer).then(async (resolved) => {
1858
+ if (!resolved) {
1859
+ return;
1860
+ }
1861
+ const mockUrl = this.resolveMockPath(cleanVersion(resolved.url));
1862
+ this.mockedIds.add(resolved.id);
1863
+ this.registry.delete(mockUrl);
1864
+ await this.interceptor.delete(mockUrl);
1865
+ }).finally(() => {
1866
+ this.queue.delete(promise);
1867
+ });
1868
+ this.queue.add(promise);
1869
+ }
1870
+ // We need to await mock registration before importing the actual module
1871
+ // In case there is a mocked module in the import chain
1872
+ wrapDynamicImport(moduleFactory) {
1873
+ if (typeof moduleFactory === "function") {
1874
+ const promise = new Promise((resolve2, reject) => {
1875
+ this.prepare().finally(() => {
1876
+ moduleFactory().then(resolve2, reject);
1877
+ });
1878
+ });
1879
+ return promise;
1880
+ }
1881
+ return moduleFactory;
1882
+ }
1883
+ resolveMockPath(path) {
1884
+ const config = this.config;
1885
+ const fsRoot = join("/@fs/", config.root);
1886
+ if (path.startsWith(config.root)) {
1887
+ return path.slice(config.root.length);
1888
+ }
1889
+ if (path.startsWith(fsRoot)) {
1890
+ return path.slice(fsRoot.length);
1891
+ }
1892
+ return path;
1893
+ }
1894
+ }
1895
+ const versionRegexp = /(\?|&)v=\w{8}/;
1896
+ function cleanVersion(url2) {
1897
+ return url2.replace(versionRegexp, "");
1898
+ }
1899
+ class VitestBrowserClientMocker extends ModuleMocker {
1900
+ // default "vi" utility tries to access mock context to avoid circular dependencies
1901
+ getMockContext() {
1902
+ return { callstack: null };
1903
+ }
1904
+ wrapDynamicImport(moduleFactory) {
1905
+ return getBrowserState().wrapModule(moduleFactory);
1906
+ }
1907
+ }
1908
+ function createModuleMockerInterceptor() {
1909
+ return {
1910
+ async register(module) {
1911
+ const state = getBrowserState();
1912
+ await rpc().registerMock(state.sessionId, module.toJSON());
1913
+ },
1914
+ async delete(id) {
1915
+ const state = getBrowserState();
1916
+ await rpc().unregisterMock(state.sessionId, id);
1917
+ },
1918
+ async invalidate() {
1919
+ const state = getBrowserState();
1920
+ await rpc().clearMocks(state.sessionId);
1921
+ }
1922
+ };
1923
+ }
1924
+ function rpc() {
1925
+ return getWorkerState().rpc;
1926
+ }
1927
+ getBrowserState().provider;
1928
+ class CommandsManager {
1929
+ _listeners = [];
1930
+ onCommand(listener) {
1931
+ this._listeners.push(listener);
1932
+ }
1933
+ async triggerCommand(command, args, clientError = new Error("empty")) {
1934
+ var _a, _b;
1935
+ const state = getWorkerState();
1936
+ const rpc2 = state.rpc;
1937
+ const { sessionId, traces: traces2 } = getBrowserState();
1938
+ const filepath = state.filepath || ((_b = (_a = state.current) == null ? void 0 : _a.file) == null ? void 0 : _b.filepath);
1939
+ args = args.filter((arg) => arg !== void 0);
1940
+ if (this._listeners.length) {
1941
+ await Promise.all(this._listeners.map((listener) => listener(command, args)));
1942
+ }
1943
+ return traces2.$(
1944
+ "vitest.browser.tester.command",
1945
+ {
1946
+ attributes: {
1947
+ "vitest.browser.command": command,
1948
+ "code.file.path": filepath
1949
+ }
1950
+ },
1951
+ () => rpc2.triggerCommand(sessionId, command, filepath, args).catch((err) => {
1952
+ var _a2;
1953
+ clientError.message = err.message;
1954
+ clientError.name = err.name;
1955
+ clientError.stack = (_a2 = clientError.stack) == null ? void 0 : _a2.replace(clientError.message, err.message);
1956
+ throw clientError;
1957
+ })
1958
+ );
1959
+ }
1960
+ }
1961
+ const debugVar = getConfig().env.VITEST_BROWSER_DEBUG;
1962
+ const debug = debugVar && debugVar !== "false" ? (...args) => {
1963
+ var _a, _b;
1964
+ return (_b = (_a = client.rpc).debug) == null ? void 0 : _b.call(_a, ...args.map(String));
1965
+ } : void 0;
1966
+ const otelConfig = getConfig().experimental.openTelemetry;
1967
+ const traces = new Traces({
1968
+ enabled: !!((otelConfig == null ? void 0 : otelConfig.enabled) && (otelConfig == null ? void 0 : otelConfig.browserSdkPath)),
1969
+ sdkPath: `/@fs/${otelConfig == null ? void 0 : otelConfig.browserSdkPath}`
1970
+ });
1971
+ let rootTesterSpan;
1972
+ getBrowserState().traces = traces;
1973
+ channel.addEventListener("message", async (e) => {
1974
+ await client.waitForConnection();
1975
+ const data = e.data;
1976
+ debug == null ? void 0 : debug("event from orchestrator", JSON.stringify(e.data));
1977
+ if (!isEvent(data)) {
1978
+ const error = new Error(`Unknown message: ${JSON.stringify(e.data)}`);
1979
+ unhandledError(error, "Unknown Iframe Message");
1980
+ return;
1981
+ }
1982
+ if (!("iframeId" in data) || data.iframeId !== getBrowserState().iframeId) {
1983
+ return;
1984
+ }
1985
+ switch (data.event) {
1986
+ case "execute": {
1987
+ const { method, files, context } = data;
1988
+ const state = getWorkerState();
1989
+ const parsedContext = parse(context);
1990
+ state.ctx.providedContext = parsedContext;
1991
+ state.providedContext = parsedContext;
1992
+ if (method === "collect") {
1993
+ await executeTests("collect", files).catch((err) => unhandledError(err, "Collect Error"));
1994
+ } else {
1995
+ await executeTests("run", files).catch((err) => unhandledError(err, "Run Error"));
1996
+ }
1997
+ break;
1998
+ }
1999
+ case "cleanup": {
2000
+ await cleanup().catch((err) => unhandledError(err, "Cleanup Error"));
2001
+ rootTesterSpan == null ? void 0 : rootTesterSpan.span.end();
2002
+ await traces.finish();
2003
+ break;
2004
+ }
2005
+ case "prepare": {
2006
+ await traces.waitInit();
2007
+ const tracesContext = traces.getContextFromCarrier(data.otelCarrier);
2008
+ traces.recordInitSpan(tracesContext);
2009
+ rootTesterSpan = traces.startContextSpan(
2010
+ `vitest.browser.tester.run`,
2011
+ tracesContext
2012
+ );
2013
+ traces.bind(rootTesterSpan.context);
2014
+ await prepare(data).catch((err) => unhandledError(err, "Prepare Error"));
2015
+ break;
2016
+ }
2017
+ case "viewport:done":
2018
+ case "viewport:fail":
2019
+ case "viewport": {
2020
+ break;
2021
+ }
2022
+ default: {
2023
+ const error = new Error(`Unknown event: ${data.event}`);
2024
+ unhandledError(error, "Unknown Event");
2025
+ }
2026
+ }
2027
+ channel.postMessage({
2028
+ event: `response:${data.event}`,
2029
+ iframeId: getBrowserState().iframeId
2030
+ });
2031
+ });
2032
+ const url = new URL(location.href);
2033
+ const iframeId = url.searchParams.get("iframeId");
2034
+ const commands = new CommandsManager();
2035
+ getBrowserState().commands = commands;
2036
+ getBrowserState().iframeId = iframeId;
2037
+ let contextSwitched = false;
2038
+ async function prepareTestEnvironment(options) {
2039
+ debug == null ? void 0 : debug("trying to resolve the runner");
2040
+ const config = getConfig();
2041
+ const rpc2 = createSafeRpc(client);
2042
+ const state = getWorkerState();
2043
+ state.metaEnv = __vitest_browser_import_meta_env_init__;
2044
+ state.onCancel = onCancel;
2045
+ state.ctx.rpc = rpc2;
2046
+ state.rpc = rpc2;
2047
+ const interceptor = createModuleMockerInterceptor();
2048
+ const mocker = new VitestBrowserClientMocker(
2049
+ interceptor,
2050
+ rpc2,
2051
+ SpyModule.createMockInstance,
2052
+ {
2053
+ root: getBrowserState().viteConfig.root
2054
+ }
2055
+ );
2056
+ globalThis.__vitest_mocker__ = mocker;
2057
+ setupConsoleLogSpy();
2058
+ setupDialogsSpy();
2059
+ const runner = await initiateRunner(state, mocker, config);
2060
+ getBrowserState().runner = runner;
2061
+ if (server.provider === "webdriverio") {
2062
+ let switchPromise = null;
2063
+ commands.onCommand(async () => {
2064
+ if (switchPromise) {
2065
+ await switchPromise;
2066
+ }
2067
+ if (!contextSwitched) {
2068
+ switchPromise = rpc2.wdioSwitchContext("iframe").finally(() => {
2069
+ switchPromise = null;
2070
+ contextSwitched = true;
2071
+ });
2072
+ await switchPromise;
2073
+ }
2074
+ });
2075
+ }
2076
+ state.durations.prepare = performance.now() - options.startTime;
2077
+ return {
2078
+ runner,
2079
+ config,
2080
+ state
2081
+ };
2082
+ }
2083
+ let preparedData;
2084
+ async function executeTests(method, specifications) {
2085
+ if (!preparedData) {
2086
+ throw new Error(`Data was not properly initialized. This is a bug in Vitest. Please, open a new issue with reproduction.`);
2087
+ }
2088
+ debug == null ? void 0 : debug("runner resolved successfully");
2089
+ const { runner, state } = preparedData;
2090
+ state.ctx.files = specifications;
2091
+ runner.setMethod(method);
2092
+ const version = url.searchParams.get("browserv") || "";
2093
+ specifications.forEach(({ filepath }) => {
2094
+ const currentVersion = browserHashMap.get(filepath);
2095
+ if (!currentVersion || currentVersion[1] !== version) {
2096
+ browserHashMap.set(filepath, version);
2097
+ }
2098
+ });
2099
+ for (const file of specifications) {
2100
+ state.filepath = file.filepath;
2101
+ debug == null ? void 0 : debug("running test file", file.filepath);
2102
+ await traces.$(
2103
+ `vitest.test.runner.${method}.module`,
2104
+ {
2105
+ attributes: { "code.file.path": file.filepath }
2106
+ },
2107
+ async () => {
2108
+ if (method === "run") {
2109
+ await startTests([file], runner);
2110
+ } else {
2111
+ await collectTests([file], runner);
2112
+ }
2113
+ }
2114
+ );
2115
+ }
2116
+ }
2117
+ async function prepare(options) {
2118
+ preparedData = await prepareTestEnvironment(options);
2119
+ debug == null ? void 0 : debug("runner resolved successfully");
2120
+ const { config, state } = preparedData;
2121
+ state.durations.prepare = performance.now() - state.durations.prepare;
2122
+ debug == null ? void 0 : debug("prepare time", state.durations.prepare, "ms");
2123
+ await Promise.all([
2124
+ setupCommonEnv(config),
2125
+ startCoverageInsideWorker(config.coverage, moduleRunner, { isolate: config.browser.isolate }),
2126
+ (async () => {
2127
+ const VitestIndex = await __vitePreload(() => import("vitest"), true ? [] : void 0);
2128
+ Object.defineProperty(window, "__vitest_index__", {
2129
+ value: VitestIndex,
2130
+ enumerable: false
2131
+ });
2132
+ })()
2133
+ ]);
2134
+ if (!config.browser.trackUnhandledErrors) {
2135
+ getBrowserState().disposeExceptionTracker();
2136
+ }
2137
+ }
2138
+ async function cleanup() {
2139
+ const state = getWorkerState();
2140
+ const config = getConfig();
2141
+ const rpc2 = state.rpc;
2142
+ const cleanupSymbol = Symbol.for("vitest:component-cleanup");
2143
+ if (cleanupSymbol in page) {
2144
+ try {
2145
+ await page[cleanupSymbol]();
2146
+ } catch (error) {
2147
+ await unhandledError(error, "Cleanup Error");
2148
+ }
2149
+ }
2150
+ await userEvent.cleanup().catch((error) => unhandledError(error, "Cleanup Error"));
2151
+ await Promise.all(
2152
+ getBrowserState().cleanups.map((fn) => fn())
2153
+ ).catch((error) => unhandledError(error, "Cleanup Error"));
2154
+ if (contextSwitched) {
2155
+ await rpc2.wdioSwitchContext("parent").catch((error) => unhandledError(error, "Cleanup Error"));
2156
+ }
2157
+ await stopCoverageInsideWorker(config.coverage, moduleRunner, { isolate: config.browser.isolate }).catch((error) => {
2158
+ return unhandledError(error, "Coverage Error");
2159
+ });
2160
+ }
2161
+ function unhandledError(e, type) {
2162
+ return client.rpc.onUnhandledError({
2163
+ name: e.name,
2164
+ message: e.message,
2165
+ stack: e.stack
2166
+ }, type).catch(() => {
2167
+ });
2168
+ }
2169
+ function isEvent(data) {
2170
+ return typeof data === "object" && !!data && "event" in data;
2171
+ }