@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,966 @@
1
+ import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
2
+ import { a as automockModule, e as esmWalker } from './chunk-automock.js';
3
+ import MagicString from '../../vendor/magic-string.mjs';
4
+ import { createFilter } from '@voidzero-dev/vite-plus-core';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { join } from 'node:path/posix';
7
+ import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { findMockRedirect } from './redirect.js';
11
+ import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
12
+ import 'node:module';
13
+
14
+ function automockPlugin(options = {}) {
15
+ return {
16
+ name: "vitest:automock",
17
+ enforce: "post",
18
+ transform(code, id) {
19
+ if (id.includes("mock=automock") || id.includes("mock=autospy")) {
20
+ const mockType = id.includes("mock=automock") ? "automock" : "autospy";
21
+ const ms = automockModule(code, mockType, this.parse, options);
22
+ return {
23
+ code: ms.toString(),
24
+ map: ms.generateMap({
25
+ hires: "boundary",
26
+ source: cleanUrl(id)
27
+ })
28
+ };
29
+ }
30
+ }
31
+ };
32
+ }
33
+
34
+ const regexDynamicImport = /import\s*\(/;
35
+ function dynamicImportPlugin(options = {}) {
36
+ return {
37
+ name: "vitest:browser:esm-injector",
38
+ enforce: "post",
39
+ transform(source, id) {
40
+ // TODO: test is not called for static imports
41
+ if (!regexDynamicImport.test(source)) {
42
+ return;
43
+ }
44
+ if (options.filter && !options.filter(id)) {
45
+ return;
46
+ }
47
+ return injectDynamicImport(source, id, this.parse, options);
48
+ }
49
+ };
50
+ }
51
+ function injectDynamicImport(code, id, parse, options = {}) {
52
+ const s = new MagicString(code);
53
+ let ast;
54
+ try {
55
+ ast = parse(code);
56
+ } catch (err) {
57
+ console.error(`Cannot parse ${id}:\n${err.message}`);
58
+ return;
59
+ }
60
+ // 3. convert references to import bindings & import.meta references
61
+ esmWalker(ast, {
62
+ onImportMeta() {
63
+ // s.update(node.start, node.end, viImportMetaKey)
64
+ },
65
+ onDynamicImport(node) {
66
+ const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
67
+ const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`;
68
+ const importSubstring = code.substring(node.start, node.end);
69
+ const hasIgnore = importSubstring.includes("/* @vite-ignore */");
70
+ s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : ""));
71
+ s.overwrite(node.end - 1, node.end, "))");
72
+ }
73
+ });
74
+ return {
75
+ code: s.toString(),
76
+ map: s.generateMap({
77
+ hires: "boundary",
78
+ source: id
79
+ })
80
+ };
81
+ }
82
+
83
+ // AST walker module for ESTree compatible trees
84
+
85
+
86
+ function makeTest(test) {
87
+ if (typeof test === "string")
88
+ { return function (type) { return type === test; } }
89
+ else if (!test)
90
+ { return function () { return true; } }
91
+ else
92
+ { return test }
93
+ }
94
+
95
+ var Found = function Found(node, state) { this.node = node; this.state = state; };
96
+
97
+ // Find the innermost node of a given type that contains the given
98
+ // position. Interface similar to findNodeAt.
99
+ function findNodeAround(node, pos, test, baseVisitor, state) {
100
+ test = makeTest(test);
101
+ if (!baseVisitor) { baseVisitor = base; }
102
+ try {
103
+ (function c(node, st, override) {
104
+ var type = override || node.type;
105
+ if (node.start > pos || node.end < pos) { return }
106
+ baseVisitor[type](node, st, c);
107
+ if (test(type, node)) { throw new Found(node, st) }
108
+ })(node, state);
109
+ } catch (e) {
110
+ if (e instanceof Found) { return e }
111
+ throw e
112
+ }
113
+ }
114
+
115
+ function skipThrough(node, st, c) { c(node, st); }
116
+ function ignore(_node, _st, _c) {}
117
+
118
+ // Node walkers.
119
+
120
+ var base = {};
121
+
122
+ base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
123
+ for (var i = 0, list = node.body; i < list.length; i += 1)
124
+ {
125
+ var stmt = list[i];
126
+
127
+ c(stmt, st, "Statement");
128
+ }
129
+ };
130
+ base.Statement = skipThrough;
131
+ base.EmptyStatement = ignore;
132
+ base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
133
+ function (node, st, c) { return c(node.expression, st, "Expression"); };
134
+ base.IfStatement = function (node, st, c) {
135
+ c(node.test, st, "Expression");
136
+ c(node.consequent, st, "Statement");
137
+ if (node.alternate) { c(node.alternate, st, "Statement"); }
138
+ };
139
+ base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
140
+ base.BreakStatement = base.ContinueStatement = ignore;
141
+ base.WithStatement = function (node, st, c) {
142
+ c(node.object, st, "Expression");
143
+ c(node.body, st, "Statement");
144
+ };
145
+ base.SwitchStatement = function (node, st, c) {
146
+ c(node.discriminant, st, "Expression");
147
+ for (var i = 0, list = node.cases; i < list.length; i += 1) {
148
+ var cs = list[i];
149
+
150
+ c(cs, st);
151
+ }
152
+ };
153
+ base.SwitchCase = function (node, st, c) {
154
+ if (node.test) { c(node.test, st, "Expression"); }
155
+ for (var i = 0, list = node.consequent; i < list.length; i += 1)
156
+ {
157
+ var cons = list[i];
158
+
159
+ c(cons, st, "Statement");
160
+ }
161
+ };
162
+ base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
163
+ if (node.argument) { c(node.argument, st, "Expression"); }
164
+ };
165
+ base.ThrowStatement = base.SpreadElement =
166
+ function (node, st, c) { return c(node.argument, st, "Expression"); };
167
+ base.TryStatement = function (node, st, c) {
168
+ c(node.block, st, "Statement");
169
+ if (node.handler) { c(node.handler, st); }
170
+ if (node.finalizer) { c(node.finalizer, st, "Statement"); }
171
+ };
172
+ base.CatchClause = function (node, st, c) {
173
+ if (node.param) { c(node.param, st, "Pattern"); }
174
+ c(node.body, st, "Statement");
175
+ };
176
+ base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
177
+ c(node.test, st, "Expression");
178
+ c(node.body, st, "Statement");
179
+ };
180
+ base.ForStatement = function (node, st, c) {
181
+ if (node.init) { c(node.init, st, "ForInit"); }
182
+ if (node.test) { c(node.test, st, "Expression"); }
183
+ if (node.update) { c(node.update, st, "Expression"); }
184
+ c(node.body, st, "Statement");
185
+ };
186
+ base.ForInStatement = base.ForOfStatement = function (node, st, c) {
187
+ c(node.left, st, "ForInit");
188
+ c(node.right, st, "Expression");
189
+ c(node.body, st, "Statement");
190
+ };
191
+ base.ForInit = function (node, st, c) {
192
+ if (node.type === "VariableDeclaration") { c(node, st); }
193
+ else { c(node, st, "Expression"); }
194
+ };
195
+ base.DebuggerStatement = ignore;
196
+
197
+ base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
198
+ base.VariableDeclaration = function (node, st, c) {
199
+ for (var i = 0, list = node.declarations; i < list.length; i += 1)
200
+ {
201
+ var decl = list[i];
202
+
203
+ c(decl, st);
204
+ }
205
+ };
206
+ base.VariableDeclarator = function (node, st, c) {
207
+ c(node.id, st, "Pattern");
208
+ if (node.init) { c(node.init, st, "Expression"); }
209
+ };
210
+
211
+ base.Function = function (node, st, c) {
212
+ if (node.id) { c(node.id, st, "Pattern"); }
213
+ for (var i = 0, list = node.params; i < list.length; i += 1)
214
+ {
215
+ var param = list[i];
216
+
217
+ c(param, st, "Pattern");
218
+ }
219
+ c(node.body, st, node.expression ? "Expression" : "Statement");
220
+ };
221
+
222
+ base.Pattern = function (node, st, c) {
223
+ if (node.type === "Identifier")
224
+ { c(node, st, "VariablePattern"); }
225
+ else if (node.type === "MemberExpression")
226
+ { c(node, st, "MemberPattern"); }
227
+ else
228
+ { c(node, st); }
229
+ };
230
+ base.VariablePattern = ignore;
231
+ base.MemberPattern = skipThrough;
232
+ base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
233
+ base.ArrayPattern = function (node, st, c) {
234
+ for (var i = 0, list = node.elements; i < list.length; i += 1) {
235
+ var elt = list[i];
236
+
237
+ if (elt) { c(elt, st, "Pattern"); }
238
+ }
239
+ };
240
+ base.ObjectPattern = function (node, st, c) {
241
+ for (var i = 0, list = node.properties; i < list.length; i += 1) {
242
+ var prop = list[i];
243
+
244
+ if (prop.type === "Property") {
245
+ if (prop.computed) { c(prop.key, st, "Expression"); }
246
+ c(prop.value, st, "Pattern");
247
+ } else if (prop.type === "RestElement") {
248
+ c(prop.argument, st, "Pattern");
249
+ }
250
+ }
251
+ };
252
+
253
+ base.Expression = skipThrough;
254
+ base.ThisExpression = base.Super = base.MetaProperty = ignore;
255
+ base.ArrayExpression = function (node, st, c) {
256
+ for (var i = 0, list = node.elements; i < list.length; i += 1) {
257
+ var elt = list[i];
258
+
259
+ if (elt) { c(elt, st, "Expression"); }
260
+ }
261
+ };
262
+ base.ObjectExpression = function (node, st, c) {
263
+ for (var i = 0, list = node.properties; i < list.length; i += 1)
264
+ {
265
+ var prop = list[i];
266
+
267
+ c(prop, st);
268
+ }
269
+ };
270
+ base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
271
+ base.SequenceExpression = function (node, st, c) {
272
+ for (var i = 0, list = node.expressions; i < list.length; i += 1)
273
+ {
274
+ var expr = list[i];
275
+
276
+ c(expr, st, "Expression");
277
+ }
278
+ };
279
+ base.TemplateLiteral = function (node, st, c) {
280
+ for (var i = 0, list = node.quasis; i < list.length; i += 1)
281
+ {
282
+ var quasi = list[i];
283
+
284
+ c(quasi, st);
285
+ }
286
+
287
+ for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
288
+ {
289
+ var expr = list$1[i$1];
290
+
291
+ c(expr, st, "Expression");
292
+ }
293
+ };
294
+ base.TemplateElement = ignore;
295
+ base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
296
+ c(node.argument, st, "Expression");
297
+ };
298
+ base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
299
+ c(node.left, st, "Expression");
300
+ c(node.right, st, "Expression");
301
+ };
302
+ base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
303
+ c(node.left, st, "Pattern");
304
+ c(node.right, st, "Expression");
305
+ };
306
+ base.ConditionalExpression = function (node, st, c) {
307
+ c(node.test, st, "Expression");
308
+ c(node.consequent, st, "Expression");
309
+ c(node.alternate, st, "Expression");
310
+ };
311
+ base.NewExpression = base.CallExpression = function (node, st, c) {
312
+ c(node.callee, st, "Expression");
313
+ if (node.arguments)
314
+ { for (var i = 0, list = node.arguments; i < list.length; i += 1)
315
+ {
316
+ var arg = list[i];
317
+
318
+ c(arg, st, "Expression");
319
+ } }
320
+ };
321
+ base.MemberExpression = function (node, st, c) {
322
+ c(node.object, st, "Expression");
323
+ if (node.computed) { c(node.property, st, "Expression"); }
324
+ };
325
+ base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
326
+ if (node.declaration)
327
+ { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
328
+ if (node.source) { c(node.source, st, "Expression"); }
329
+ };
330
+ base.ExportAllDeclaration = function (node, st, c) {
331
+ if (node.exported)
332
+ { c(node.exported, st); }
333
+ c(node.source, st, "Expression");
334
+ };
335
+ base.ImportDeclaration = function (node, st, c) {
336
+ for (var i = 0, list = node.specifiers; i < list.length; i += 1)
337
+ {
338
+ var spec = list[i];
339
+
340
+ c(spec, st);
341
+ }
342
+ c(node.source, st, "Expression");
343
+ };
344
+ base.ImportExpression = function (node, st, c) {
345
+ c(node.source, st, "Expression");
346
+ };
347
+ base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
348
+
349
+ base.TaggedTemplateExpression = function (node, st, c) {
350
+ c(node.tag, st, "Expression");
351
+ c(node.quasi, st, "Expression");
352
+ };
353
+ base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
354
+ base.Class = function (node, st, c) {
355
+ if (node.id) { c(node.id, st, "Pattern"); }
356
+ if (node.superClass) { c(node.superClass, st, "Expression"); }
357
+ c(node.body, st);
358
+ };
359
+ base.ClassBody = function (node, st, c) {
360
+ for (var i = 0, list = node.body; i < list.length; i += 1)
361
+ {
362
+ var elt = list[i];
363
+
364
+ c(elt, st);
365
+ }
366
+ };
367
+ base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
368
+ if (node.computed) { c(node.key, st, "Expression"); }
369
+ if (node.value) { c(node.value, st, "Expression"); }
370
+ };
371
+
372
+ function hoistMocksPlugin(options = {}) {
373
+ const filter = options.filter || createFilter(options.include, options.exclude);
374
+ const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
375
+ "mock",
376
+ "unmock",
377
+ "doMock",
378
+ "doUnmock"
379
+ ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options;
380
+ const methods = new Set([
381
+ ...hoistableMockMethodNames,
382
+ ...hoistedMethodNames,
383
+ ...dynamicImportMockMethodNames
384
+ ]);
385
+ const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`);
386
+ return {
387
+ name: "vitest:mocks",
388
+ enforce: "post",
389
+ transform(code, id) {
390
+ if (!filter(id)) {
391
+ return;
392
+ }
393
+ return hoistMocks(code, id, this.parse, {
394
+ regexpHoistable,
395
+ hoistableMockMethodNames,
396
+ hoistedMethodNames,
397
+ utilsObjectNames,
398
+ dynamicImportMockMethodNames,
399
+ ...options
400
+ });
401
+ }
402
+ };
403
+ }
404
+ const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
405
+ You may encounter this issue when importing the mocks API from another module other than 'vitest'.
406
+ To fix this issue you can either:
407
+ - import the mocks API directly from 'vitest'
408
+ - enable the 'globals' options`;
409
+ function API_NOT_FOUND_CHECK(names) {
410
+ return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
411
+ }
412
+ function isIdentifier(node) {
413
+ return node.type === "Identifier";
414
+ }
415
+ function getNodeTail(code, node) {
416
+ let end = node.end;
417
+ if (code[node.end] === ";") {
418
+ end += 1;
419
+ }
420
+ if (code[node.end] === "\n") {
421
+ return end + 1;
422
+ }
423
+ if (code[node.end + 1] === "\n") {
424
+ end += 1;
425
+ }
426
+ return end;
427
+ }
428
+ const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
429
+ const hashbangRE = /^#!.*\n/;
430
+ // this is a fork of Vite SSR transform
431
+ function hoistMocks(code, id, parse, options = {}) {
432
+ var _hashbangRE$exec;
433
+ const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
434
+ if (!needHoisting) {
435
+ return;
436
+ }
437
+ const s = new MagicString(code);
438
+ let ast;
439
+ try {
440
+ ast = parse(code);
441
+ } catch (err) {
442
+ console.error(`Cannot parse ${id}:\n${err.message}.`);
443
+ return;
444
+ }
445
+ const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
446
+ "mock",
447
+ "unmock",
448
+ "doMock",
449
+ "doUnmock"
450
+ ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
451
+ // hoist at the start of the file, after the hashbang
452
+ let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0;
453
+ let hoistedModuleImported = false;
454
+ let uid = 0;
455
+ const idToImportMap = new Map();
456
+ const imports = [];
457
+ // this will transform import statements into dynamic ones, if there are imports
458
+ // it will keep the import as is, if we don't need to mock anything
459
+ // in browser environment it will wrap the module value with "vitest_wrap_module" function
460
+ // that returns a proxy to the module so that named exports can be mocked
461
+ function defineImport(importNode) {
462
+ const source = importNode.source.value;
463
+ // always hoist vitest import to top of the file, so
464
+ // "vi" helpers can access it
465
+ if (hoistedModule === source || source === "vite-plus/test" || source === "@voidzero-dev/vite-plus-test") {
466
+ hoistedModuleImported = true;
467
+ return;
468
+ }
469
+ const importId = `__vi_import_${uid++}__`;
470
+ imports.push({
471
+ id: importId,
472
+ node: importNode
473
+ });
474
+ return importId;
475
+ }
476
+ // 1. check all import statements and record id -> importName map
477
+ for (const node of ast.body) {
478
+ // import foo from 'foo' --> foo -> __import_foo__.default
479
+ // import { baz } from 'foo' --> baz -> __import_foo__.baz
480
+ // import * as ok from 'foo' --> ok -> __import_foo__
481
+ if (node.type === "ImportDeclaration") {
482
+ const importId = defineImport(node);
483
+ if (!importId) {
484
+ continue;
485
+ }
486
+ for (const spec of node.specifiers) {
487
+ if (spec.type === "ImportSpecifier") {
488
+ if (spec.imported.type === "Identifier") {
489
+ idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
490
+ } else {
491
+ idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
492
+ }
493
+ } else if (spec.type === "ImportDefaultSpecifier") {
494
+ idToImportMap.set(spec.local.name, `${importId}.default`);
495
+ } else {
496
+ // namespace specifier
497
+ idToImportMap.set(spec.local.name, importId);
498
+ }
499
+ }
500
+ }
501
+ }
502
+ const declaredConst = new Set();
503
+ const hoistedNodes = [];
504
+ function createSyntaxError(node, message) {
505
+ const _error = new SyntaxError(message);
506
+ Error.captureStackTrace(_error, createSyntaxError);
507
+ const serializedError = {
508
+ name: "SyntaxError",
509
+ message: _error.message,
510
+ stack: _error.stack
511
+ };
512
+ if (options.codeFrameGenerator) {
513
+ serializedError.frame = options.codeFrameGenerator(node, id, code);
514
+ }
515
+ return serializedError;
516
+ }
517
+ function assertNotDefaultExport(node, error) {
518
+ var _findNodeAround;
519
+ const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node;
520
+ if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) {
521
+ throw createSyntaxError(defaultExport, error);
522
+ }
523
+ }
524
+ function assertNotNamedExport(node, error) {
525
+ var _findNodeAround2;
526
+ const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node;
527
+ if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) {
528
+ throw createSyntaxError(nodeExported, error);
529
+ }
530
+ }
531
+ function getVariableDeclaration(node) {
532
+ var _findNodeAround3, _declarationNode$decl;
533
+ const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node;
534
+ const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init;
535
+ if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
536
+ return declarationNode;
537
+ }
538
+ }
539
+ const usedUtilityExports = new Set();
540
+ esmWalker(ast, {
541
+ onIdentifier(id, info, parentStack) {
542
+ const binding = idToImportMap.get(id.name);
543
+ if (!binding) {
544
+ return;
545
+ }
546
+ if (info.hasBindingShortcut) {
547
+ s.appendLeft(id.end, `: ${binding}`);
548
+ } else if (info.classDeclaration) {
549
+ if (!declaredConst.has(id.name)) {
550
+ declaredConst.add(id.name);
551
+ // locate the top-most node containing the class declaration
552
+ const topNode = parentStack[parentStack.length - 2];
553
+ s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
554
+ }
555
+ } else if (!info.classExpression) {
556
+ s.update(id.start, id.end, binding);
557
+ }
558
+ },
559
+ onCallExpression(node) {
560
+ if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
561
+ const methodName = node.callee.property.name;
562
+ usedUtilityExports.add(node.callee.object.name);
563
+ if (hoistableMockMethodNames.includes(methodName)) {
564
+ const method = `${node.callee.object.name}.${methodName}`;
565
+ assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
566
+ const declarationNode = getVariableDeclaration(node);
567
+ if (declarationNode) {
568
+ assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
569
+ }
570
+ // rewrite vi.mock(import('..')) into vi.mock('..')
571
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
572
+ const moduleInfo = node.arguments[0];
573
+ // vi.mock(import('./path')) -> vi.mock('./path')
574
+ if (moduleInfo.type === "ImportExpression") {
575
+ const source = moduleInfo.source;
576
+ s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
577
+ }
578
+ // vi.mock(await import('./path')) -> vi.mock('./path')
579
+ if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
580
+ const source = moduleInfo.argument.source;
581
+ s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
582
+ }
583
+ }
584
+ hoistedNodes.push(node);
585
+ } else if (dynamicImportMockMethodNames.includes(methodName)) {
586
+ const moduleInfo = node.arguments[0];
587
+ let source = null;
588
+ if (moduleInfo.type === "ImportExpression") {
589
+ source = moduleInfo.source;
590
+ }
591
+ if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
592
+ source = moduleInfo.argument.source;
593
+ }
594
+ if (source) {
595
+ s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
596
+ }
597
+ }
598
+ if (hoistedMethodNames.includes(methodName)) {
599
+ assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
600
+ const declarationNode = getVariableDeclaration(node);
601
+ if (declarationNode) {
602
+ assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
603
+ // hoist "const variable = vi.hoisted(() => {})"
604
+ hoistedNodes.push(declarationNode);
605
+ } else {
606
+ var _findNodeAround4;
607
+ const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node;
608
+ // hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
609
+ const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node;
610
+ hoistedNodes.push(moveNode);
611
+ }
612
+ }
613
+ }
614
+ }
615
+ });
616
+ function getNodeName(node) {
617
+ const callee = node.callee || {};
618
+ if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
619
+ return `${callee.object.name}.${callee.property.name}()`;
620
+ }
621
+ return "\"hoisted method\"";
622
+ }
623
+ function getNodeCall(node) {
624
+ if (node.type === "CallExpression") {
625
+ return node;
626
+ }
627
+ if (node.type === "VariableDeclaration") {
628
+ const { declarations } = node;
629
+ const init = declarations[0].init;
630
+ if (init) {
631
+ return getNodeCall(init);
632
+ }
633
+ }
634
+ if (node.type === "AwaitExpression") {
635
+ const { argument } = node;
636
+ if (argument.type === "CallExpression") {
637
+ return getNodeCall(argument);
638
+ }
639
+ }
640
+ return node;
641
+ }
642
+ function createError(outsideNode, insideNode) {
643
+ const outsideCall = getNodeCall(outsideNode);
644
+ const insideCall = getNodeCall(insideNode);
645
+ throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
646
+ }
647
+ // validate hoistedNodes doesn't have nodes inside other nodes
648
+ for (let i = 0; i < hoistedNodes.length; i++) {
649
+ const node = hoistedNodes[i];
650
+ for (let j = i + 1; j < hoistedNodes.length; j++) {
651
+ const otherNode = hoistedNodes[j];
652
+ if (node.start >= otherNode.start && node.end <= otherNode.end) {
653
+ throw createError(otherNode, node);
654
+ }
655
+ if (otherNode.start >= node.start && otherNode.end <= node.end) {
656
+ throw createError(node, otherNode);
657
+ }
658
+ }
659
+ }
660
+ // hoist vi.mock/vi.hoisted
661
+ for (const node of hoistedNodes) {
662
+ const end = getNodeTail(code, node);
663
+ // don't hoist into itself if it's already at the top
664
+ if (hoistIndex === end || hoistIndex === node.start) {
665
+ hoistIndex = end;
666
+ } else {
667
+ s.move(node.start, end, hoistIndex);
668
+ }
669
+ }
670
+ // hoist actual dynamic imports last so they are inserted after all hoisted mocks
671
+ for (const { node: importNode, id: importId } of imports) {
672
+ const source = importNode.source.value;
673
+ s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`);
674
+ if (importNode.start === hoistIndex) {
675
+ // no need to hoist, but update hoistIndex to keep the order
676
+ hoistIndex = importNode.end;
677
+ } else {
678
+ // There will be an error if the module is called before it is imported,
679
+ // so the module import statement is hoisted to the top
680
+ s.move(importNode.start, importNode.end, hoistIndex);
681
+ }
682
+ }
683
+ if (!hoistedModuleImported && hoistedNodes.length) {
684
+ const utilityImports = [...usedUtilityExports];
685
+ // "vi" or "vitest" is imported from a module other than "vitest"
686
+ if (utilityImports.some((name) => idToImportMap.has(name))) {
687
+ s.prepend(API_NOT_FOUND_CHECK(utilityImports));
688
+ } else if (utilityImports.length) {
689
+ s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
690
+ }
691
+ }
692
+ return {
693
+ code: s.toString(),
694
+ map: s.generateMap({
695
+ hires: "boundary",
696
+ source: id
697
+ })
698
+ };
699
+ }
700
+
701
+ function interceptorPlugin(options = {}) {
702
+ const registry = options.registry || new MockerRegistry();
703
+ return {
704
+ name: "vitest:mocks:interceptor",
705
+ enforce: "pre",
706
+ load: {
707
+ order: "pre",
708
+ async handler(id) {
709
+ const mock = registry.getById(id);
710
+ if (!mock) {
711
+ return;
712
+ }
713
+ if (mock.type === "manual") {
714
+ const exports$1 = Object.keys(await mock.resolve());
715
+ const accessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
716
+ return createManualModuleSource(mock.url, exports$1, accessor);
717
+ }
718
+ if (mock.type === "redirect") {
719
+ return readFile(mock.redirect, "utf-8");
720
+ }
721
+ }
722
+ },
723
+ transform: {
724
+ order: "post",
725
+ handler(code, id) {
726
+ const mock = registry.getById(id);
727
+ if (!mock) {
728
+ return;
729
+ }
730
+ if (mock.type === "automock" || mock.type === "autospy") {
731
+ const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor });
732
+ return {
733
+ code: m.toString(),
734
+ map: m.generateMap({
735
+ hires: "boundary",
736
+ source: cleanUrl(id)
737
+ })
738
+ };
739
+ }
740
+ }
741
+ },
742
+ configureServer(server) {
743
+ server.ws.on("vitest:interceptor:register", (event) => {
744
+ if (event.type === "manual") {
745
+ const module = ManualMockedModule.fromJSON(event, async () => {
746
+ const keys = await getFactoryExports(event.url);
747
+ return Object.fromEntries(keys.map((key) => [key, null]));
748
+ });
749
+ registry.add(module);
750
+ } else {
751
+ if (event.type === "redirect") {
752
+ const redirectUrl = new URL(event.redirect);
753
+ event.redirect = join(server.config.root, redirectUrl.pathname);
754
+ }
755
+ registry.register(event);
756
+ }
757
+ server.ws.send("vitest:interceptor:register:result");
758
+ });
759
+ server.ws.on("vitest:interceptor:delete", (id) => {
760
+ registry.delete(id);
761
+ server.ws.send("vitest:interceptor:delete:result");
762
+ });
763
+ server.ws.on("vitest:interceptor:invalidate", () => {
764
+ registry.clear();
765
+ server.ws.send("vitest:interceptor:invalidate:result");
766
+ });
767
+ function getFactoryExports(url) {
768
+ server.ws.send("vitest:interceptor:resolve", url);
769
+ let timeout;
770
+ return new Promise((resolve, reject) => {
771
+ timeout = setTimeout(() => {
772
+ reject(new Error(`Timeout while waiting for factory exports of ${url}`));
773
+ }, 1e4);
774
+ server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => {
775
+ if (resolvedUrl === url) {
776
+ clearTimeout(timeout);
777
+ resolve(keys);
778
+ }
779
+ });
780
+ });
781
+ }
782
+ }
783
+ };
784
+ }
785
+
786
+ const VALID_ID_PREFIX = "/@id/";
787
+ class ServerMockResolver {
788
+ constructor(server, options = {}) {
789
+ this.server = server;
790
+ this.options = options;
791
+ }
792
+ async resolveMock(rawId, importer, options) {
793
+ const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
794
+ const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
795
+ if (options.mock === "factory") {
796
+ var _manifest$fsPath;
797
+ const manifest = getViteDepsManifest(this.server.config);
798
+ const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false;
799
+ return {
800
+ mockType: "manual",
801
+ resolvedId: id,
802
+ resolvedUrl,
803
+ needsInterop
804
+ };
805
+ }
806
+ if (options.mock === "spy") {
807
+ return {
808
+ mockType: "autospy",
809
+ resolvedId: id,
810
+ resolvedUrl
811
+ };
812
+ }
813
+ const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external);
814
+ return {
815
+ mockType: redirectUrl === null ? "automock" : "redirect",
816
+ redirectUrl,
817
+ resolvedId: id,
818
+ resolvedUrl
819
+ };
820
+ }
821
+ invalidate(ids) {
822
+ ids.forEach((id) => {
823
+ const moduleGraph = this.server.moduleGraph;
824
+ const module = moduleGraph.getModuleById(id);
825
+ if (module) {
826
+ module.transformResult = null;
827
+ }
828
+ });
829
+ }
830
+ async resolveId(id, importer) {
831
+ const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false });
832
+ if (!resolved) {
833
+ return null;
834
+ }
835
+ return this.normalizeResolveIdToUrl(resolved);
836
+ }
837
+ normalizeResolveIdToUrl(resolved) {
838
+ const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir));
839
+ let url;
840
+ // normalise the URL to be acceptable by the browser
841
+ // https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103
842
+ const root = this.server.config.root;
843
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
844
+ url = resolved.id.slice(root.length);
845
+ } else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) {
846
+ url = join$1("/@fs/", resolved.id);
847
+ } else {
848
+ url = resolved.id;
849
+ }
850
+ if (url[0] !== "." && url[0] !== "/") {
851
+ url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__");
852
+ }
853
+ return {
854
+ id: resolved.id,
855
+ url,
856
+ optimized: isOptimized
857
+ };
858
+ }
859
+ async resolveMockId(rawId, importer) {
860
+ if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) {
861
+ importer = join$1(this.server.config.root, importer);
862
+ }
863
+ const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false });
864
+ return this.resolveModule(rawId, resolved);
865
+ }
866
+ resolveModule(rawId, resolved) {
867
+ const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId;
868
+ const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
869
+ return {
870
+ id,
871
+ fsPath: cleanUrl(id),
872
+ external
873
+ };
874
+ }
875
+ }
876
+ function isModuleDirectory(config, path) {
877
+ const moduleDirectories = config.moduleDirectories || ["/node_modules/"];
878
+ return moduleDirectories.some((dir) => path.includes(dir));
879
+ }
880
+ const metadata = new WeakMap();
881
+ function getViteDepsManifest(config) {
882
+ if (metadata.has(config)) {
883
+ return metadata.get(config);
884
+ }
885
+ const cacheDirPath = getDepsCacheDir(config);
886
+ const metadataPath = resolve(cacheDirPath, "_metadata.json");
887
+ if (!existsSync(metadataPath)) {
888
+ return null;
889
+ }
890
+ const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8"));
891
+ const newManifest = {};
892
+ for (const name in optimized) {
893
+ const dep = optimized[name];
894
+ const file = resolve(cacheDirPath, dep.file);
895
+ newManifest[file] = {
896
+ hash: dep.fileHash,
897
+ needsInterop: dep.needsInterop
898
+ };
899
+ }
900
+ metadata.set(config, newManifest);
901
+ return newManifest;
902
+ }
903
+ function getDepsCacheDir(config) {
904
+ return resolve(config.cacheDir, "deps");
905
+ }
906
+ function withTrailingSlash(path) {
907
+ if (path.at(-1) !== "/") {
908
+ return `${path}/`;
909
+ }
910
+ return path;
911
+ }
912
+
913
+ // this is an implementation for public usage
914
+ // vitest doesn't use this plugin directly
915
+ function mockerPlugin(options = {}) {
916
+ let server;
917
+ const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url)));
918
+ return [
919
+ {
920
+ name: "vitest:mocker:ws-rpc",
921
+ config(_, { command }) {
922
+ if (command !== "serve") {
923
+ return;
924
+ }
925
+ return {
926
+ server: { preTransformRequests: false },
927
+ optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] }
928
+ };
929
+ },
930
+ configureServer(server_) {
931
+ server = server_;
932
+ const mockResolver = new ServerMockResolver(server);
933
+ server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => {
934
+ const resolved = await mockResolver.resolveId(id, importer);
935
+ server.ws.send("vitest:mocks:resolvedId:result", resolved);
936
+ });
937
+ server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => {
938
+ const resolved = await mockResolver.resolveMock(id, importer, options);
939
+ server.ws.send("vitest:mocks:resolveMock:result", resolved);
940
+ });
941
+ server.ws.on("vitest:mocks:invalidate", async ({ ids }) => {
942
+ mockResolver.invalidate(ids);
943
+ server.ws.send("vitest:mocks:invalidate:result");
944
+ });
945
+ },
946
+ async load(id) {
947
+ if (id !== registerPath) {
948
+ return;
949
+ }
950
+ if (!server) {
951
+ // mocker doesn't work during build
952
+ return "export {}";
953
+ }
954
+ const content = await readFile(registerPath, "utf-8");
955
+ const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root));
956
+ return result;
957
+ }
958
+ },
959
+ hoistMocksPlugin(options.hoistMocks),
960
+ interceptorPlugin(options),
961
+ automockPlugin(options),
962
+ dynamicImportPlugin(options)
963
+ ];
964
+ }
965
+
966
+ export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };