@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,3292 @@
1
+ import fs, { statSync, realpathSync, existsSync, promises, readdirSync, writeFileSync } from 'node:fs';
2
+ import path, { win32, dirname, join } from 'node:path';
3
+ import { slash, shuffle, toArray } from '../@vitest/utils/helpers.js';
4
+ import { isAbsolute, resolve, relative, normalize } from '../vendor/pathe.mjs';
5
+ import pm from '../vendor/picomatch.mjs';
6
+ import { glob } from '../vendor/tinyglobby.mjs';
7
+ import c from '../vendor/tinyrainbow.mjs';
8
+ import { c as configDefaults, e as benchmarkConfigDefaults, a as coverageConfigDefaults } from './defaults.BOqNVLsY.js';
9
+ import crypto from 'node:crypto';
10
+ import { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$1 } from 'node:url';
11
+ import { builtinModules, createRequire } from 'node:module';
12
+ import process$1 from 'node:process';
13
+ import fs$1 from 'node:fs/promises';
14
+ import assert from 'node:assert';
15
+ import v8 from 'node:v8';
16
+ import { format, inspect } from 'node:util';
17
+ import { mergeConfig } from '@voidzero-dev/vite-plus-core';
18
+ import { c as configFiles, d as defaultBrowserPort, b as defaultInspectPort, a as defaultPort } from './constants.D_Q9UYh-.js';
19
+ import './env.D4Lgay0q.js';
20
+ import nodeos__default from 'node:os';
21
+ import { isCI, provider } from '../vendor/std-env.mjs';
22
+ import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
23
+
24
+ const hash = crypto.hash ?? ((algorithm, data, outputEncoding) => crypto.createHash(algorithm).update(data).digest(outputEncoding));
25
+
26
+ const JOIN_LEADING_SLASH_RE = /^\.?\//;
27
+ function withTrailingSlash(input = "", respectQueryAndFragment) {
28
+ {
29
+ return input.endsWith("/") ? input : input + "/";
30
+ }
31
+ }
32
+ function isNonEmptyURL(url) {
33
+ return url && url !== "/";
34
+ }
35
+ function joinURL(base, ...input) {
36
+ let url = base || "";
37
+ for (const segment of input.filter((url2) => isNonEmptyURL(url2))) {
38
+ if (url) {
39
+ const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
40
+ url = withTrailingSlash(url) + _segment;
41
+ } else {
42
+ url = segment;
43
+ }
44
+ }
45
+ return url;
46
+ }
47
+
48
+ const BUILTIN_MODULES = new Set(builtinModules);
49
+ function normalizeSlash(path) {
50
+ return path.replace(/\\/g, "/");
51
+ }
52
+
53
+ /**
54
+ * @typedef ErrnoExceptionFields
55
+ * @property {number | undefined} [errnode]
56
+ * @property {string | undefined} [code]
57
+ * @property {string | undefined} [path]
58
+ * @property {string | undefined} [syscall]
59
+ * @property {string | undefined} [url]
60
+ *
61
+ * @typedef {Error & ErrnoExceptionFields} ErrnoException
62
+ */
63
+
64
+
65
+ const own$1 = {}.hasOwnProperty;
66
+
67
+ const classRegExp = /^([A-Z][a-z\d]*)+$/;
68
+ // Sorted by a rough estimate on most frequently used entries.
69
+ const kTypes = new Set([
70
+ 'string',
71
+ 'function',
72
+ 'number',
73
+ 'object',
74
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
75
+ 'Function',
76
+ 'Object',
77
+ 'boolean',
78
+ 'bigint',
79
+ 'symbol'
80
+ ]);
81
+
82
+ const codes = {};
83
+
84
+ /**
85
+ * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
86
+ * We cannot use Intl.ListFormat because it's not available in
87
+ * --without-intl builds.
88
+ *
89
+ * @param {Array<string>} array
90
+ * An array of strings.
91
+ * @param {string} [type]
92
+ * The list type to be inserted before the last element.
93
+ * @returns {string}
94
+ */
95
+ function formatList(array, type = 'and') {
96
+ return array.length < 3
97
+ ? array.join(` ${type} `)
98
+ : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
99
+ }
100
+
101
+ /** @type {Map<string, MessageFunction | string>} */
102
+ const messages = new Map();
103
+ const nodeInternalPrefix = '__node_internal_';
104
+ /** @type {number} */
105
+ let userStackTraceLimit;
106
+
107
+ codes.ERR_INVALID_ARG_TYPE = createError(
108
+ 'ERR_INVALID_ARG_TYPE',
109
+ /**
110
+ * @param {string} name
111
+ * @param {Array<string> | string} expected
112
+ * @param {unknown} actual
113
+ */
114
+ (name, expected, actual) => {
115
+ assert(typeof name === 'string', "'name' must be a string");
116
+ if (!Array.isArray(expected)) {
117
+ expected = [expected];
118
+ }
119
+
120
+ let message = 'The ';
121
+ if (name.endsWith(' argument')) {
122
+ // For cases like 'first argument'
123
+ message += `${name} `;
124
+ } else {
125
+ const type = name.includes('.') ? 'property' : 'argument';
126
+ message += `"${name}" ${type} `;
127
+ }
128
+
129
+ message += 'must be ';
130
+
131
+ /** @type {Array<string>} */
132
+ const types = [];
133
+ /** @type {Array<string>} */
134
+ const instances = [];
135
+ /** @type {Array<string>} */
136
+ const other = [];
137
+
138
+ for (const value of expected) {
139
+ assert(
140
+ typeof value === 'string',
141
+ 'All expected entries have to be of type string'
142
+ );
143
+
144
+ if (kTypes.has(value)) {
145
+ types.push(value.toLowerCase());
146
+ } else if (classRegExp.exec(value) === null) {
147
+ assert(
148
+ value !== 'object',
149
+ 'The value "object" should be written as "Object"'
150
+ );
151
+ other.push(value);
152
+ } else {
153
+ instances.push(value);
154
+ }
155
+ }
156
+
157
+ // Special handle `object` in case other instances are allowed to outline
158
+ // the differences between each other.
159
+ if (instances.length > 0) {
160
+ const pos = types.indexOf('object');
161
+ if (pos !== -1) {
162
+ types.slice(pos, 1);
163
+ instances.push('Object');
164
+ }
165
+ }
166
+
167
+ if (types.length > 0) {
168
+ message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
169
+ types,
170
+ 'or'
171
+ )}`;
172
+ if (instances.length > 0 || other.length > 0) message += ' or ';
173
+ }
174
+
175
+ if (instances.length > 0) {
176
+ message += `an instance of ${formatList(instances, 'or')}`;
177
+ if (other.length > 0) message += ' or ';
178
+ }
179
+
180
+ if (other.length > 0) {
181
+ if (other.length > 1) {
182
+ message += `one of ${formatList(other, 'or')}`;
183
+ } else {
184
+ if (other[0].toLowerCase() !== other[0]) message += 'an ';
185
+ message += `${other[0]}`;
186
+ }
187
+ }
188
+
189
+ message += `. Received ${determineSpecificType(actual)}`;
190
+
191
+ return message
192
+ },
193
+ TypeError
194
+ );
195
+
196
+ codes.ERR_INVALID_MODULE_SPECIFIER = createError(
197
+ 'ERR_INVALID_MODULE_SPECIFIER',
198
+ /**
199
+ * @param {string} request
200
+ * @param {string} reason
201
+ * @param {string} [base]
202
+ */
203
+ (request, reason, base = undefined) => {
204
+ return `Invalid module "${request}" ${reason}${
205
+ base ? ` imported from ${base}` : ''
206
+ }`
207
+ },
208
+ TypeError
209
+ );
210
+
211
+ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
212
+ 'ERR_INVALID_PACKAGE_CONFIG',
213
+ /**
214
+ * @param {string} path
215
+ * @param {string} [base]
216
+ * @param {string} [message]
217
+ */
218
+ (path, base, message) => {
219
+ return `Invalid package config ${path}${
220
+ base ? ` while importing ${base}` : ''
221
+ }${message ? `. ${message}` : ''}`
222
+ },
223
+ Error
224
+ );
225
+
226
+ codes.ERR_INVALID_PACKAGE_TARGET = createError(
227
+ 'ERR_INVALID_PACKAGE_TARGET',
228
+ /**
229
+ * @param {string} packagePath
230
+ * @param {string} key
231
+ * @param {unknown} target
232
+ * @param {boolean} [isImport=false]
233
+ * @param {string} [base]
234
+ */
235
+ (packagePath, key, target, isImport = false, base = undefined) => {
236
+ const relatedError =
237
+ typeof target === 'string' &&
238
+ !isImport &&
239
+ target.length > 0 &&
240
+ !target.startsWith('./');
241
+ if (key === '.') {
242
+ assert(isImport === false);
243
+ return (
244
+ `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
245
+ `in the package config ${packagePath}package.json${
246
+ base ? ` imported from ${base}` : ''
247
+ }${relatedError ? '; targets must start with "./"' : ''}`
248
+ )
249
+ }
250
+
251
+ return `Invalid "${
252
+ isImport ? 'imports' : 'exports'
253
+ }" target ${JSON.stringify(
254
+ target
255
+ )} defined for '${key}' in the package config ${packagePath}package.json${
256
+ base ? ` imported from ${base}` : ''
257
+ }${relatedError ? '; targets must start with "./"' : ''}`
258
+ },
259
+ Error
260
+ );
261
+
262
+ codes.ERR_MODULE_NOT_FOUND = createError(
263
+ 'ERR_MODULE_NOT_FOUND',
264
+ /**
265
+ * @param {string} path
266
+ * @param {string} base
267
+ * @param {boolean} [exactUrl]
268
+ */
269
+ (path, base, exactUrl = false) => {
270
+ return `Cannot find ${
271
+ exactUrl ? 'module' : 'package'
272
+ } '${path}' imported from ${base}`
273
+ },
274
+ Error
275
+ );
276
+
277
+ codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
278
+ 'ERR_NETWORK_IMPORT_DISALLOWED',
279
+ "import of '%s' by %s is not supported: %s",
280
+ Error
281
+ );
282
+
283
+ codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
284
+ 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
285
+ /**
286
+ * @param {string} specifier
287
+ * @param {string} packagePath
288
+ * @param {string} base
289
+ */
290
+ (specifier, packagePath, base) => {
291
+ return `Package import specifier "${specifier}" is not defined${
292
+ packagePath ? ` in package ${packagePath}package.json` : ''
293
+ } imported from ${base}`
294
+ },
295
+ TypeError
296
+ );
297
+
298
+ codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
299
+ 'ERR_PACKAGE_PATH_NOT_EXPORTED',
300
+ /**
301
+ * @param {string} packagePath
302
+ * @param {string} subpath
303
+ * @param {string} [base]
304
+ */
305
+ (packagePath, subpath, base = undefined) => {
306
+ if (subpath === '.')
307
+ return `No "exports" main defined in ${packagePath}package.json${
308
+ base ? ` imported from ${base}` : ''
309
+ }`
310
+ return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
311
+ base ? ` imported from ${base}` : ''
312
+ }`
313
+ },
314
+ Error
315
+ );
316
+
317
+ codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
318
+ 'ERR_UNSUPPORTED_DIR_IMPORT',
319
+ "Directory import '%s' is not supported " +
320
+ 'resolving ES modules imported from %s',
321
+ Error
322
+ );
323
+
324
+ codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
325
+ 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
326
+ 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
327
+ TypeError
328
+ );
329
+
330
+ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
331
+ 'ERR_UNKNOWN_FILE_EXTENSION',
332
+ /**
333
+ * @param {string} extension
334
+ * @param {string} path
335
+ */
336
+ (extension, path) => {
337
+ return `Unknown file extension "${extension}" for ${path}`
338
+ },
339
+ TypeError
340
+ );
341
+
342
+ codes.ERR_INVALID_ARG_VALUE = createError(
343
+ 'ERR_INVALID_ARG_VALUE',
344
+ /**
345
+ * @param {string} name
346
+ * @param {unknown} value
347
+ * @param {string} [reason='is invalid']
348
+ */
349
+ (name, value, reason = 'is invalid') => {
350
+ let inspected = inspect(value);
351
+
352
+ if (inspected.length > 128) {
353
+ inspected = `${inspected.slice(0, 128)}...`;
354
+ }
355
+
356
+ const type = name.includes('.') ? 'property' : 'argument';
357
+
358
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`
359
+ },
360
+ TypeError
361
+ // Note: extra classes have been shaken out.
362
+ // , RangeError
363
+ );
364
+
365
+ /**
366
+ * Utility function for registering the error codes. Only used here. Exported
367
+ * *only* to allow for testing.
368
+ * @param {string} sym
369
+ * @param {MessageFunction | string} value
370
+ * @param {ErrorConstructor} constructor
371
+ * @returns {new (...parameters: Array<any>) => Error}
372
+ */
373
+ function createError(sym, value, constructor) {
374
+ // Special case for SystemError that formats the error message differently
375
+ // The SystemErrors only have SystemError as their base classes.
376
+ messages.set(sym, value);
377
+
378
+ return makeNodeErrorWithCode(constructor, sym)
379
+ }
380
+
381
+ /**
382
+ * @param {ErrorConstructor} Base
383
+ * @param {string} key
384
+ * @returns {ErrorConstructor}
385
+ */
386
+ function makeNodeErrorWithCode(Base, key) {
387
+ // @ts-expect-error It’s a Node error.
388
+ return NodeError
389
+ /**
390
+ * @param {Array<unknown>} parameters
391
+ */
392
+ function NodeError(...parameters) {
393
+ const limit = Error.stackTraceLimit;
394
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
395
+ const error = new Base();
396
+ // Reset the limit and setting the name property.
397
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
398
+ const message = getMessage(key, parameters, error);
399
+ Object.defineProperties(error, {
400
+ // Note: no need to implement `kIsNodeError` symbol, would be hard,
401
+ // probably.
402
+ message: {
403
+ value: message,
404
+ enumerable: false,
405
+ writable: true,
406
+ configurable: true
407
+ },
408
+ toString: {
409
+ /** @this {Error} */
410
+ value() {
411
+ return `${this.name} [${key}]: ${this.message}`
412
+ },
413
+ enumerable: false,
414
+ writable: true,
415
+ configurable: true
416
+ }
417
+ });
418
+
419
+ captureLargerStackTrace(error);
420
+ // @ts-expect-error It’s a Node error.
421
+ error.code = key;
422
+ return error
423
+ }
424
+ }
425
+
426
+ /**
427
+ * @returns {boolean}
428
+ */
429
+ function isErrorStackTraceLimitWritable() {
430
+ // Do no touch Error.stackTraceLimit as V8 would attempt to install
431
+ // it again during deserialization.
432
+ try {
433
+ if (v8.startupSnapshot.isBuildingSnapshot()) {
434
+ return false
435
+ }
436
+ } catch {}
437
+
438
+ const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
439
+ if (desc === undefined) {
440
+ return Object.isExtensible(Error)
441
+ }
442
+
443
+ return own$1.call(desc, 'writable') && desc.writable !== undefined
444
+ ? desc.writable
445
+ : desc.set !== undefined
446
+ }
447
+
448
+ /**
449
+ * This function removes unnecessary frames from Node.js core errors.
450
+ * @template {(...parameters: unknown[]) => unknown} T
451
+ * @param {T} wrappedFunction
452
+ * @returns {T}
453
+ */
454
+ function hideStackFrames(wrappedFunction) {
455
+ // We rename the functions that will be hidden to cut off the stacktrace
456
+ // at the outermost one
457
+ const hidden = nodeInternalPrefix + wrappedFunction.name;
458
+ Object.defineProperty(wrappedFunction, 'name', {value: hidden});
459
+ return wrappedFunction
460
+ }
461
+
462
+ const captureLargerStackTrace = hideStackFrames(
463
+ /**
464
+ * @param {Error} error
465
+ * @returns {Error}
466
+ */
467
+ // @ts-expect-error: fine
468
+ function (error) {
469
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
470
+ if (stackTraceLimitIsWritable) {
471
+ userStackTraceLimit = Error.stackTraceLimit;
472
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
473
+ }
474
+
475
+ Error.captureStackTrace(error);
476
+
477
+ // Reset the limit
478
+ if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
479
+
480
+ return error
481
+ }
482
+ );
483
+
484
+ /**
485
+ * @param {string} key
486
+ * @param {Array<unknown>} parameters
487
+ * @param {Error} self
488
+ * @returns {string}
489
+ */
490
+ function getMessage(key, parameters, self) {
491
+ const message = messages.get(key);
492
+ assert(message !== undefined, 'expected `message` to be found');
493
+
494
+ if (typeof message === 'function') {
495
+ assert(
496
+ message.length <= parameters.length, // Default options do not count.
497
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
498
+ `match the required ones (${message.length}).`
499
+ );
500
+ return Reflect.apply(message, self, parameters)
501
+ }
502
+
503
+ const regex = /%[dfijoOs]/g;
504
+ let expectedLength = 0;
505
+ while (regex.exec(message) !== null) expectedLength++;
506
+ assert(
507
+ expectedLength === parameters.length,
508
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
509
+ `match the required ones (${expectedLength}).`
510
+ );
511
+ if (parameters.length === 0) return message
512
+
513
+ parameters.unshift(message);
514
+ return Reflect.apply(format, null, parameters)
515
+ }
516
+
517
+ /**
518
+ * Determine the specific type of a value for type-mismatch errors.
519
+ * @param {unknown} value
520
+ * @returns {string}
521
+ */
522
+ function determineSpecificType(value) {
523
+ if (value === null || value === undefined) {
524
+ return String(value)
525
+ }
526
+
527
+ if (typeof value === 'function' && value.name) {
528
+ return `function ${value.name}`
529
+ }
530
+
531
+ if (typeof value === 'object') {
532
+ if (value.constructor && value.constructor.name) {
533
+ return `an instance of ${value.constructor.name}`
534
+ }
535
+
536
+ return `${inspect(value, {depth: -1})}`
537
+ }
538
+
539
+ let inspected = inspect(value, {colors: false});
540
+
541
+ if (inspected.length > 28) {
542
+ inspected = `${inspected.slice(0, 25)}...`;
543
+ }
544
+
545
+ return `type ${typeof value} (${inspected})`
546
+ }
547
+
548
+ // Manually “tree shaken” from:
549
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
550
+ // Last checked on: Apr 29, 2023.
551
+ // Removed the native dependency.
552
+ // Also: no need to cache, we do that in resolve already.
553
+
554
+
555
+ const hasOwnProperty$1 = {}.hasOwnProperty;
556
+
557
+ const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
558
+
559
+ /** @type {Map<string, PackageConfig>} */
560
+ const cache = new Map();
561
+
562
+ /**
563
+ * @param {string} jsonPath
564
+ * @param {{specifier: URL | string, base?: URL}} options
565
+ * @returns {PackageConfig}
566
+ */
567
+ function read(jsonPath, {base, specifier}) {
568
+ const existing = cache.get(jsonPath);
569
+
570
+ if (existing) {
571
+ return existing
572
+ }
573
+
574
+ /** @type {string | undefined} */
575
+ let string;
576
+
577
+ try {
578
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8');
579
+ } catch (error) {
580
+ const exception = /** @type {ErrnoException} */ (error);
581
+
582
+ if (exception.code !== 'ENOENT') {
583
+ throw exception
584
+ }
585
+ }
586
+
587
+ /** @type {PackageConfig} */
588
+ const result = {
589
+ exists: false,
590
+ pjsonPath: jsonPath,
591
+ main: undefined,
592
+ name: undefined,
593
+ type: 'none', // Ignore unknown types for forwards compatibility
594
+ exports: undefined,
595
+ imports: undefined
596
+ };
597
+
598
+ if (string !== undefined) {
599
+ /** @type {Record<string, unknown>} */
600
+ let parsed;
601
+
602
+ try {
603
+ parsed = JSON.parse(string);
604
+ } catch (error_) {
605
+ const cause = /** @type {ErrnoException} */ (error_);
606
+ const error = new ERR_INVALID_PACKAGE_CONFIG$1(
607
+ jsonPath,
608
+ (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier),
609
+ cause.message
610
+ );
611
+ error.cause = cause;
612
+ throw error
613
+ }
614
+
615
+ result.exists = true;
616
+
617
+ if (
618
+ hasOwnProperty$1.call(parsed, 'name') &&
619
+ typeof parsed.name === 'string'
620
+ ) {
621
+ result.name = parsed.name;
622
+ }
623
+
624
+ if (
625
+ hasOwnProperty$1.call(parsed, 'main') &&
626
+ typeof parsed.main === 'string'
627
+ ) {
628
+ result.main = parsed.main;
629
+ }
630
+
631
+ if (hasOwnProperty$1.call(parsed, 'exports')) {
632
+ // @ts-expect-error: assume valid.
633
+ result.exports = parsed.exports;
634
+ }
635
+
636
+ if (hasOwnProperty$1.call(parsed, 'imports')) {
637
+ // @ts-expect-error: assume valid.
638
+ result.imports = parsed.imports;
639
+ }
640
+
641
+ // Ignore unknown types for forwards compatibility
642
+ if (
643
+ hasOwnProperty$1.call(parsed, 'type') &&
644
+ (parsed.type === 'commonjs' || parsed.type === 'module')
645
+ ) {
646
+ result.type = parsed.type;
647
+ }
648
+ }
649
+
650
+ cache.set(jsonPath, result);
651
+
652
+ return result
653
+ }
654
+
655
+ /**
656
+ * @param {URL | string} resolved
657
+ * @returns {PackageConfig}
658
+ */
659
+ function getPackageScopeConfig(resolved) {
660
+ // Note: in Node, this is now a native module.
661
+ let packageJSONUrl = new URL('package.json', resolved);
662
+
663
+ while (true) {
664
+ const packageJSONPath = packageJSONUrl.pathname;
665
+ if (packageJSONPath.endsWith('node_modules/package.json')) {
666
+ break
667
+ }
668
+
669
+ const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
670
+ specifier: resolved
671
+ });
672
+
673
+ if (packageConfig.exists) {
674
+ return packageConfig
675
+ }
676
+
677
+ const lastPackageJSONUrl = packageJSONUrl;
678
+ packageJSONUrl = new URL('../package.json', packageJSONUrl);
679
+
680
+ // Terminates at root where ../package.json equals ../../package.json
681
+ // (can't just check "/package.json" for Windows support).
682
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
683
+ break
684
+ }
685
+ }
686
+
687
+ const packageJSONPath = fileURLToPath$1(packageJSONUrl);
688
+ // ^^ Note: in Node, this is now a native module.
689
+
690
+ return {
691
+ pjsonPath: packageJSONPath,
692
+ exists: false,
693
+ type: 'none'
694
+ }
695
+ }
696
+
697
+ /**
698
+ * Returns the package type for a given URL.
699
+ * @param {URL} url - The URL to get the package type for.
700
+ * @returns {PackageType}
701
+ */
702
+ function getPackageType(url) {
703
+ // To do @anonrig: Write a C++ function that returns only "type".
704
+ return getPackageScopeConfig(url).type
705
+ }
706
+
707
+ // Manually “tree shaken” from:
708
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
709
+ // Last checked on: Apr 29, 2023.
710
+
711
+
712
+ const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
713
+
714
+ const hasOwnProperty = {}.hasOwnProperty;
715
+
716
+ /** @type {Record<string, string>} */
717
+ const extensionFormatMap = {
718
+ // @ts-expect-error: hush.
719
+ __proto__: null,
720
+ '.cjs': 'commonjs',
721
+ '.js': 'module',
722
+ '.json': 'json',
723
+ '.mjs': 'module'
724
+ };
725
+
726
+ /**
727
+ * @param {string | null} mime
728
+ * @returns {string | null}
729
+ */
730
+ function mimeToFormat(mime) {
731
+ if (
732
+ mime &&
733
+ /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
734
+ )
735
+ return 'module'
736
+ if (mime === 'application/json') return 'json'
737
+ return null
738
+ }
739
+
740
+ /**
741
+ * @callback ProtocolHandler
742
+ * @param {URL} parsed
743
+ * @param {{parentURL: string, source?: Buffer}} context
744
+ * @param {boolean} ignoreErrors
745
+ * @returns {string | null | void}
746
+ */
747
+
748
+ /**
749
+ * @type {Record<string, ProtocolHandler>}
750
+ */
751
+ const protocolHandlers = {
752
+ // @ts-expect-error: hush.
753
+ __proto__: null,
754
+ 'data:': getDataProtocolModuleFormat,
755
+ 'file:': getFileProtocolModuleFormat,
756
+ 'http:': getHttpProtocolModuleFormat,
757
+ 'https:': getHttpProtocolModuleFormat,
758
+ 'node:'() {
759
+ return 'builtin'
760
+ }
761
+ };
762
+
763
+ /**
764
+ * @param {URL} parsed
765
+ */
766
+ function getDataProtocolModuleFormat(parsed) {
767
+ const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
768
+ parsed.pathname
769
+ ) || [null, null, null];
770
+ return mimeToFormat(mime)
771
+ }
772
+
773
+ /**
774
+ * Returns the file extension from a URL.
775
+ *
776
+ * Should give similar result to
777
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
778
+ * when used with a `file:` URL.
779
+ *
780
+ * @param {URL} url
781
+ * @returns {string}
782
+ */
783
+ function extname(url) {
784
+ const pathname = url.pathname;
785
+ let index = pathname.length;
786
+
787
+ while (index--) {
788
+ const code = pathname.codePointAt(index);
789
+
790
+ if (code === 47 /* `/` */) {
791
+ return ''
792
+ }
793
+
794
+ if (code === 46 /* `.` */) {
795
+ return pathname.codePointAt(index - 1) === 47 /* `/` */
796
+ ? ''
797
+ : pathname.slice(index)
798
+ }
799
+ }
800
+
801
+ return ''
802
+ }
803
+
804
+ /**
805
+ * @type {ProtocolHandler}
806
+ */
807
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
808
+ const value = extname(url);
809
+
810
+ if (value === '.js') {
811
+ const packageType = getPackageType(url);
812
+
813
+ if (packageType !== 'none') {
814
+ return packageType
815
+ }
816
+
817
+ return 'commonjs'
818
+ }
819
+
820
+ if (value === '') {
821
+ const packageType = getPackageType(url);
822
+
823
+ // Legacy behavior
824
+ if (packageType === 'none' || packageType === 'commonjs') {
825
+ return 'commonjs'
826
+ }
827
+
828
+ // Note: we don’t implement WASM, so we don’t need
829
+ // `getFormatOfExtensionlessFile` from `formats`.
830
+ return 'module'
831
+ }
832
+
833
+ const format = extensionFormatMap[value];
834
+ if (format) return format
835
+
836
+ // Explicit undefined return indicates load hook should rerun format check
837
+ if (ignoreErrors) {
838
+ return undefined
839
+ }
840
+
841
+ const filepath = fileURLToPath$1(url);
842
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
843
+ }
844
+
845
+ function getHttpProtocolModuleFormat() {
846
+ // To do: HTTPS imports.
847
+ }
848
+
849
+ /**
850
+ * @param {URL} url
851
+ * @param {{parentURL: string}} context
852
+ * @returns {string | null}
853
+ */
854
+ function defaultGetFormatWithoutErrors(url, context) {
855
+ const protocol = url.protocol;
856
+
857
+ if (!hasOwnProperty.call(protocolHandlers, protocol)) {
858
+ return null
859
+ }
860
+
861
+ return protocolHandlers[protocol](url, context, true) || null
862
+ }
863
+
864
+ // Manually “tree shaken” from:
865
+ // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/resolve.js>
866
+ // Last checked on: Apr 29, 2023.
867
+
868
+
869
+ const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
870
+
871
+ const {
872
+ ERR_INVALID_MODULE_SPECIFIER,
873
+ ERR_INVALID_PACKAGE_CONFIG,
874
+ ERR_INVALID_PACKAGE_TARGET,
875
+ ERR_MODULE_NOT_FOUND,
876
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
877
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
878
+ ERR_UNSUPPORTED_DIR_IMPORT,
879
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
880
+ } = codes;
881
+
882
+ const own = {}.hasOwnProperty;
883
+
884
+ const invalidSegmentRegEx =
885
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
886
+ const deprecatedInvalidSegmentRegEx =
887
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
888
+ const invalidPackageNameRegEx = /^\.|%|\\/;
889
+ const patternRegEx = /\*/g;
890
+ const encodedSeparatorRegEx = /%2f|%5c/i;
891
+ /** @type {Set<string>} */
892
+ const emittedPackageWarnings = new Set();
893
+
894
+ const doubleSlashRegEx = /[/\\]{2}/;
895
+
896
+ /**
897
+ *
898
+ * @param {string} target
899
+ * @param {string} request
900
+ * @param {string} match
901
+ * @param {URL} packageJsonUrl
902
+ * @param {boolean} internal
903
+ * @param {URL} base
904
+ * @param {boolean} isTarget
905
+ */
906
+ function emitInvalidSegmentDeprecation(
907
+ target,
908
+ request,
909
+ match,
910
+ packageJsonUrl,
911
+ internal,
912
+ base,
913
+ isTarget
914
+ ) {
915
+ // @ts-expect-error: apparently it does exist, TS.
916
+ if (process$1.noDeprecation) {
917
+ return
918
+ }
919
+
920
+ const pjsonPath = fileURLToPath$1(packageJsonUrl);
921
+ const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
922
+ process$1.emitWarning(
923
+ `Use of deprecated ${
924
+ double ? 'double slash' : 'leading or trailing slash matching'
925
+ } resolving "${target}" for module ` +
926
+ `request "${request}" ${
927
+ request === match ? '' : `matched to "${match}" `
928
+ }in the "${
929
+ internal ? 'imports' : 'exports'
930
+ }" field module resolution of the package at ${pjsonPath}${
931
+ base ? ` imported from ${fileURLToPath$1(base)}` : ''
932
+ }.`,
933
+ 'DeprecationWarning',
934
+ 'DEP0166'
935
+ );
936
+ }
937
+
938
+ /**
939
+ * @param {URL} url
940
+ * @param {URL} packageJsonUrl
941
+ * @param {URL} base
942
+ * @param {string} [main]
943
+ * @returns {void}
944
+ */
945
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
946
+ // @ts-expect-error: apparently it does exist, TS.
947
+ if (process$1.noDeprecation) {
948
+ return
949
+ }
950
+
951
+ const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
952
+ if (format !== 'module') return
953
+ const urlPath = fileURLToPath$1(url.href);
954
+ const packagePath = fileURLToPath$1(new URL$1('.', packageJsonUrl));
955
+ const basePath = fileURLToPath$1(base);
956
+ if (!main) {
957
+ process$1.emitWarning(
958
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
959
+ packagePath.length
960
+ )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
961
+ 'DeprecationWarning',
962
+ 'DEP0151'
963
+ );
964
+ } else if (path.resolve(packagePath, main) !== urlPath) {
965
+ process$1.emitWarning(
966
+ `Package ${packagePath} has a "main" field set to "${main}", ` +
967
+ `excluding the full filename and extension to the resolved file at "${urlPath.slice(
968
+ packagePath.length
969
+ )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
970
+ 'deprecated for ES modules.',
971
+ 'DeprecationWarning',
972
+ 'DEP0151'
973
+ );
974
+ }
975
+ }
976
+
977
+ /**
978
+ * @param {string} path
979
+ * @returns {Stats | undefined}
980
+ */
981
+ function tryStatSync(path) {
982
+ // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
983
+ try {
984
+ return statSync(path)
985
+ } catch {
986
+ // Note: in Node code this returns `new Stats`,
987
+ // but in Node 22 that’s marked as a deprecated internal API.
988
+ // Which, well, we kinda are, but still to prevent that warning,
989
+ // just yield `undefined`.
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Legacy CommonJS main resolution:
995
+ * 1. let M = pkg_url + (json main field)
996
+ * 2. TRY(M, M.js, M.json, M.node)
997
+ * 3. TRY(M/index.js, M/index.json, M/index.node)
998
+ * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
999
+ * 5. NOT_FOUND
1000
+ *
1001
+ * @param {URL} url
1002
+ * @returns {boolean}
1003
+ */
1004
+ function fileExists(url) {
1005
+ const stats = statSync(url, {throwIfNoEntry: false});
1006
+ const isFile = stats ? stats.isFile() : undefined;
1007
+ return isFile === null || isFile === undefined ? false : isFile
1008
+ }
1009
+
1010
+ /**
1011
+ * @param {URL} packageJsonUrl
1012
+ * @param {PackageConfig} packageConfig
1013
+ * @param {URL} base
1014
+ * @returns {URL}
1015
+ */
1016
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
1017
+ /** @type {URL | undefined} */
1018
+ let guess;
1019
+ if (packageConfig.main !== undefined) {
1020
+ guess = new URL$1(packageConfig.main, packageJsonUrl);
1021
+ // Note: fs check redundances will be handled by Descriptor cache here.
1022
+ if (fileExists(guess)) return guess
1023
+
1024
+ const tries = [
1025
+ `./${packageConfig.main}.js`,
1026
+ `./${packageConfig.main}.json`,
1027
+ `./${packageConfig.main}.node`,
1028
+ `./${packageConfig.main}/index.js`,
1029
+ `./${packageConfig.main}/index.json`,
1030
+ `./${packageConfig.main}/index.node`
1031
+ ];
1032
+ let i = -1;
1033
+
1034
+ while (++i < tries.length) {
1035
+ guess = new URL$1(tries[i], packageJsonUrl);
1036
+ if (fileExists(guess)) break
1037
+ guess = undefined;
1038
+ }
1039
+
1040
+ if (guess) {
1041
+ emitLegacyIndexDeprecation(
1042
+ guess,
1043
+ packageJsonUrl,
1044
+ base,
1045
+ packageConfig.main
1046
+ );
1047
+ return guess
1048
+ }
1049
+ // Fallthrough.
1050
+ }
1051
+
1052
+ const tries = ['./index.js', './index.json', './index.node'];
1053
+ let i = -1;
1054
+
1055
+ while (++i < tries.length) {
1056
+ guess = new URL$1(tries[i], packageJsonUrl);
1057
+ if (fileExists(guess)) break
1058
+ guess = undefined;
1059
+ }
1060
+
1061
+ if (guess) {
1062
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
1063
+ return guess
1064
+ }
1065
+
1066
+ // Not found.
1067
+ throw new ERR_MODULE_NOT_FOUND(
1068
+ fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1069
+ fileURLToPath$1(base)
1070
+ )
1071
+ }
1072
+
1073
+ /**
1074
+ * @param {URL} resolved
1075
+ * @param {URL} base
1076
+ * @param {boolean} [preserveSymlinks]
1077
+ * @returns {URL}
1078
+ */
1079
+ function finalizeResolution(resolved, base, preserveSymlinks) {
1080
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
1081
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1082
+ resolved.pathname,
1083
+ 'must not include encoded "/" or "\\" characters',
1084
+ fileURLToPath$1(base)
1085
+ )
1086
+ }
1087
+
1088
+ /** @type {string} */
1089
+ let filePath;
1090
+
1091
+ try {
1092
+ filePath = fileURLToPath$1(resolved);
1093
+ } catch (error) {
1094
+ const cause = /** @type {ErrnoException} */ (error);
1095
+ Object.defineProperty(cause, 'input', {value: String(resolved)});
1096
+ Object.defineProperty(cause, 'module', {value: String(base)});
1097
+ throw cause
1098
+ }
1099
+
1100
+ const stats = tryStatSync(
1101
+ filePath.endsWith('/') ? filePath.slice(-1) : filePath
1102
+ );
1103
+
1104
+ if (stats && stats.isDirectory()) {
1105
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
1106
+ // @ts-expect-error Add this for `import.meta.resolve`.
1107
+ error.url = String(resolved);
1108
+ throw error
1109
+ }
1110
+
1111
+ if (!stats || !stats.isFile()) {
1112
+ const error = new ERR_MODULE_NOT_FOUND(
1113
+ filePath || resolved.pathname,
1114
+ base && fileURLToPath$1(base),
1115
+ true
1116
+ );
1117
+ // @ts-expect-error Add this for `import.meta.resolve`.
1118
+ error.url = String(resolved);
1119
+ throw error
1120
+ }
1121
+
1122
+ {
1123
+ const real = realpathSync(filePath);
1124
+ const {search, hash} = resolved;
1125
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? '/' : ''));
1126
+ resolved.search = search;
1127
+ resolved.hash = hash;
1128
+ }
1129
+
1130
+ return resolved
1131
+ }
1132
+
1133
+ /**
1134
+ * @param {string} specifier
1135
+ * @param {URL | undefined} packageJsonUrl
1136
+ * @param {URL} base
1137
+ * @returns {Error}
1138
+ */
1139
+ function importNotDefined(specifier, packageJsonUrl, base) {
1140
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
1141
+ specifier,
1142
+ packageJsonUrl && fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1143
+ fileURLToPath$1(base)
1144
+ )
1145
+ }
1146
+
1147
+ /**
1148
+ * @param {string} subpath
1149
+ * @param {URL} packageJsonUrl
1150
+ * @param {URL} base
1151
+ * @returns {Error}
1152
+ */
1153
+ function exportsNotFound(subpath, packageJsonUrl, base) {
1154
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
1155
+ fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1156
+ subpath,
1157
+ base && fileURLToPath$1(base)
1158
+ )
1159
+ }
1160
+
1161
+ /**
1162
+ * @param {string} request
1163
+ * @param {string} match
1164
+ * @param {URL} packageJsonUrl
1165
+ * @param {boolean} internal
1166
+ * @param {URL} [base]
1167
+ * @returns {never}
1168
+ */
1169
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
1170
+ const reason = `request is not a valid match in pattern "${match}" for the "${
1171
+ internal ? 'imports' : 'exports'
1172
+ }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
1173
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1174
+ request,
1175
+ reason,
1176
+ base && fileURLToPath$1(base)
1177
+ )
1178
+ }
1179
+
1180
+ /**
1181
+ * @param {string} subpath
1182
+ * @param {unknown} target
1183
+ * @param {URL} packageJsonUrl
1184
+ * @param {boolean} internal
1185
+ * @param {URL} [base]
1186
+ * @returns {Error}
1187
+ */
1188
+ function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
1189
+ target =
1190
+ typeof target === 'object' && target !== null
1191
+ ? JSON.stringify(target, null, '')
1192
+ : `${target}`;
1193
+
1194
+ return new ERR_INVALID_PACKAGE_TARGET(
1195
+ fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1196
+ subpath,
1197
+ target,
1198
+ internal,
1199
+ base && fileURLToPath$1(base)
1200
+ )
1201
+ }
1202
+
1203
+ /**
1204
+ * @param {string} target
1205
+ * @param {string} subpath
1206
+ * @param {string} match
1207
+ * @param {URL} packageJsonUrl
1208
+ * @param {URL} base
1209
+ * @param {boolean} pattern
1210
+ * @param {boolean} internal
1211
+ * @param {boolean} isPathMap
1212
+ * @param {Set<string> | undefined} conditions
1213
+ * @returns {URL}
1214
+ */
1215
+ function resolvePackageTargetString(
1216
+ target,
1217
+ subpath,
1218
+ match,
1219
+ packageJsonUrl,
1220
+ base,
1221
+ pattern,
1222
+ internal,
1223
+ isPathMap,
1224
+ conditions
1225
+ ) {
1226
+ if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
1227
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1228
+
1229
+ if (!target.startsWith('./')) {
1230
+ if (internal && !target.startsWith('../') && !target.startsWith('/')) {
1231
+ let isURL = false;
1232
+
1233
+ try {
1234
+ new URL$1(target);
1235
+ isURL = true;
1236
+ } catch {
1237
+ // Continue regardless of error.
1238
+ }
1239
+
1240
+ if (!isURL) {
1241
+ const exportTarget = pattern
1242
+ ? RegExpPrototypeSymbolReplace.call(
1243
+ patternRegEx,
1244
+ target,
1245
+ () => subpath
1246
+ )
1247
+ : target + subpath;
1248
+
1249
+ return packageResolve(exportTarget, packageJsonUrl, conditions)
1250
+ }
1251
+ }
1252
+
1253
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1254
+ }
1255
+
1256
+ if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
1257
+ if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
1258
+ if (!isPathMap) {
1259
+ const request = pattern
1260
+ ? match.replace('*', () => subpath)
1261
+ : match + subpath;
1262
+ const resolvedTarget = pattern
1263
+ ? RegExpPrototypeSymbolReplace.call(
1264
+ patternRegEx,
1265
+ target,
1266
+ () => subpath
1267
+ )
1268
+ : target;
1269
+ emitInvalidSegmentDeprecation(
1270
+ resolvedTarget,
1271
+ request,
1272
+ match,
1273
+ packageJsonUrl,
1274
+ internal,
1275
+ base,
1276
+ true
1277
+ );
1278
+ }
1279
+ } else {
1280
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1281
+ }
1282
+ }
1283
+
1284
+ const resolved = new URL$1(target, packageJsonUrl);
1285
+ const resolvedPath = resolved.pathname;
1286
+ const packagePath = new URL$1('.', packageJsonUrl).pathname;
1287
+
1288
+ if (!resolvedPath.startsWith(packagePath))
1289
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1290
+
1291
+ if (subpath === '') return resolved
1292
+
1293
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
1294
+ const request = pattern
1295
+ ? match.replace('*', () => subpath)
1296
+ : match + subpath;
1297
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
1298
+ if (!isPathMap) {
1299
+ const resolvedTarget = pattern
1300
+ ? RegExpPrototypeSymbolReplace.call(
1301
+ patternRegEx,
1302
+ target,
1303
+ () => subpath
1304
+ )
1305
+ : target;
1306
+ emitInvalidSegmentDeprecation(
1307
+ resolvedTarget,
1308
+ request,
1309
+ match,
1310
+ packageJsonUrl,
1311
+ internal,
1312
+ base,
1313
+ false
1314
+ );
1315
+ }
1316
+ } else {
1317
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
1318
+ }
1319
+ }
1320
+
1321
+ if (pattern) {
1322
+ return new URL$1(
1323
+ RegExpPrototypeSymbolReplace.call(
1324
+ patternRegEx,
1325
+ resolved.href,
1326
+ () => subpath
1327
+ )
1328
+ )
1329
+ }
1330
+
1331
+ return new URL$1(subpath, resolved)
1332
+ }
1333
+
1334
+ /**
1335
+ * @param {string} key
1336
+ * @returns {boolean}
1337
+ */
1338
+ function isArrayIndex(key) {
1339
+ const keyNumber = Number(key);
1340
+ if (`${keyNumber}` !== key) return false
1341
+ return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
1342
+ }
1343
+
1344
+ /**
1345
+ * @param {URL} packageJsonUrl
1346
+ * @param {unknown} target
1347
+ * @param {string} subpath
1348
+ * @param {string} packageSubpath
1349
+ * @param {URL} base
1350
+ * @param {boolean} pattern
1351
+ * @param {boolean} internal
1352
+ * @param {boolean} isPathMap
1353
+ * @param {Set<string> | undefined} conditions
1354
+ * @returns {URL | null}
1355
+ */
1356
+ function resolvePackageTarget(
1357
+ packageJsonUrl,
1358
+ target,
1359
+ subpath,
1360
+ packageSubpath,
1361
+ base,
1362
+ pattern,
1363
+ internal,
1364
+ isPathMap,
1365
+ conditions
1366
+ ) {
1367
+ if (typeof target === 'string') {
1368
+ return resolvePackageTargetString(
1369
+ target,
1370
+ subpath,
1371
+ packageSubpath,
1372
+ packageJsonUrl,
1373
+ base,
1374
+ pattern,
1375
+ internal,
1376
+ isPathMap,
1377
+ conditions
1378
+ )
1379
+ }
1380
+
1381
+ if (Array.isArray(target)) {
1382
+ /** @type {Array<unknown>} */
1383
+ const targetList = target;
1384
+ if (targetList.length === 0) return null
1385
+
1386
+ /** @type {ErrnoException | null | undefined} */
1387
+ let lastException;
1388
+ let i = -1;
1389
+
1390
+ while (++i < targetList.length) {
1391
+ const targetItem = targetList[i];
1392
+ /** @type {URL | null} */
1393
+ let resolveResult;
1394
+ try {
1395
+ resolveResult = resolvePackageTarget(
1396
+ packageJsonUrl,
1397
+ targetItem,
1398
+ subpath,
1399
+ packageSubpath,
1400
+ base,
1401
+ pattern,
1402
+ internal,
1403
+ isPathMap,
1404
+ conditions
1405
+ );
1406
+ } catch (error) {
1407
+ const exception = /** @type {ErrnoException} */ (error);
1408
+ lastException = exception;
1409
+ if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
1410
+ throw error
1411
+ }
1412
+
1413
+ if (resolveResult === undefined) continue
1414
+
1415
+ if (resolveResult === null) {
1416
+ lastException = null;
1417
+ continue
1418
+ }
1419
+
1420
+ return resolveResult
1421
+ }
1422
+
1423
+ if (lastException === undefined || lastException === null) {
1424
+ return null
1425
+ }
1426
+
1427
+ throw lastException
1428
+ }
1429
+
1430
+ if (typeof target === 'object' && target !== null) {
1431
+ const keys = Object.getOwnPropertyNames(target);
1432
+ let i = -1;
1433
+
1434
+ while (++i < keys.length) {
1435
+ const key = keys[i];
1436
+ if (isArrayIndex(key)) {
1437
+ throw new ERR_INVALID_PACKAGE_CONFIG(
1438
+ fileURLToPath$1(packageJsonUrl),
1439
+ base,
1440
+ '"exports" cannot contain numeric property keys.'
1441
+ )
1442
+ }
1443
+ }
1444
+
1445
+ i = -1;
1446
+
1447
+ while (++i < keys.length) {
1448
+ const key = keys[i];
1449
+ if (key === 'default' || (conditions && conditions.has(key))) {
1450
+ // @ts-expect-error: indexable.
1451
+ const conditionalTarget = /** @type {unknown} */ (target[key]);
1452
+ const resolveResult = resolvePackageTarget(
1453
+ packageJsonUrl,
1454
+ conditionalTarget,
1455
+ subpath,
1456
+ packageSubpath,
1457
+ base,
1458
+ pattern,
1459
+ internal,
1460
+ isPathMap,
1461
+ conditions
1462
+ );
1463
+ if (resolveResult === undefined) continue
1464
+ return resolveResult
1465
+ }
1466
+ }
1467
+
1468
+ return null
1469
+ }
1470
+
1471
+ if (target === null) {
1472
+ return null
1473
+ }
1474
+
1475
+ throw invalidPackageTarget(
1476
+ packageSubpath,
1477
+ target,
1478
+ packageJsonUrl,
1479
+ internal,
1480
+ base
1481
+ )
1482
+ }
1483
+
1484
+ /**
1485
+ * @param {unknown} exports
1486
+ * @param {URL} packageJsonUrl
1487
+ * @param {URL} base
1488
+ * @returns {boolean}
1489
+ */
1490
+ function isConditionalExportsMainSugar(exports$1, packageJsonUrl, base) {
1491
+ if (typeof exports$1 === 'string' || Array.isArray(exports$1)) return true
1492
+ if (typeof exports$1 !== 'object' || exports$1 === null) return false
1493
+
1494
+ const keys = Object.getOwnPropertyNames(exports$1);
1495
+ let isConditionalSugar = false;
1496
+ let i = 0;
1497
+ let keyIndex = -1;
1498
+ while (++keyIndex < keys.length) {
1499
+ const key = keys[keyIndex];
1500
+ const currentIsConditionalSugar = key === '' || key[0] !== '.';
1501
+ if (i++ === 0) {
1502
+ isConditionalSugar = currentIsConditionalSugar;
1503
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
1504
+ throw new ERR_INVALID_PACKAGE_CONFIG(
1505
+ fileURLToPath$1(packageJsonUrl),
1506
+ base,
1507
+ '"exports" cannot contain some keys starting with \'.\' and some not.' +
1508
+ ' The exports object must either be an object of package subpath keys' +
1509
+ ' or an object of main entry condition name keys only.'
1510
+ )
1511
+ }
1512
+ }
1513
+
1514
+ return isConditionalSugar
1515
+ }
1516
+
1517
+ /**
1518
+ * @param {string} match
1519
+ * @param {URL} pjsonUrl
1520
+ * @param {URL} base
1521
+ */
1522
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
1523
+ // @ts-expect-error: apparently it does exist, TS.
1524
+ if (process$1.noDeprecation) {
1525
+ return
1526
+ }
1527
+
1528
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
1529
+ if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
1530
+ emittedPackageWarnings.add(pjsonPath + '|' + match);
1531
+ process$1.emitWarning(
1532
+ `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
1533
+ `"exports" field module resolution of the package at ${pjsonPath}${
1534
+ base ? ` imported from ${fileURLToPath$1(base)}` : ''
1535
+ }. Mapping specifiers ending in "/" is no longer supported.`,
1536
+ 'DeprecationWarning',
1537
+ 'DEP0155'
1538
+ );
1539
+ }
1540
+
1541
+ /**
1542
+ * @param {URL} packageJsonUrl
1543
+ * @param {string} packageSubpath
1544
+ * @param {Record<string, unknown>} packageConfig
1545
+ * @param {URL} base
1546
+ * @param {Set<string> | undefined} conditions
1547
+ * @returns {URL}
1548
+ */
1549
+ function packageExportsResolve(
1550
+ packageJsonUrl,
1551
+ packageSubpath,
1552
+ packageConfig,
1553
+ base,
1554
+ conditions
1555
+ ) {
1556
+ let exports$1 = packageConfig.exports;
1557
+
1558
+ if (isConditionalExportsMainSugar(exports$1, packageJsonUrl, base)) {
1559
+ exports$1 = {'.': exports$1};
1560
+ }
1561
+
1562
+ if (
1563
+ own.call(exports$1, packageSubpath) &&
1564
+ !packageSubpath.includes('*') &&
1565
+ !packageSubpath.endsWith('/')
1566
+ ) {
1567
+ // @ts-expect-error: indexable.
1568
+ const target = exports$1[packageSubpath];
1569
+ const resolveResult = resolvePackageTarget(
1570
+ packageJsonUrl,
1571
+ target,
1572
+ '',
1573
+ packageSubpath,
1574
+ base,
1575
+ false,
1576
+ false,
1577
+ false,
1578
+ conditions
1579
+ );
1580
+ if (resolveResult === null || resolveResult === undefined) {
1581
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1582
+ }
1583
+
1584
+ return resolveResult
1585
+ }
1586
+
1587
+ let bestMatch = '';
1588
+ let bestMatchSubpath = '';
1589
+ const keys = Object.getOwnPropertyNames(exports$1);
1590
+ let i = -1;
1591
+
1592
+ while (++i < keys.length) {
1593
+ const key = keys[i];
1594
+ const patternIndex = key.indexOf('*');
1595
+
1596
+ if (
1597
+ patternIndex !== -1 &&
1598
+ packageSubpath.startsWith(key.slice(0, patternIndex))
1599
+ ) {
1600
+ // When this reaches EOL, this can throw at the top of the whole function:
1601
+ //
1602
+ // if (StringPrototypeEndsWith(packageSubpath, '/'))
1603
+ // throwInvalidSubpath(packageSubpath)
1604
+ //
1605
+ // To match "imports" and the spec.
1606
+ if (packageSubpath.endsWith('/')) {
1607
+ emitTrailingSlashPatternDeprecation(
1608
+ packageSubpath,
1609
+ packageJsonUrl,
1610
+ base
1611
+ );
1612
+ }
1613
+
1614
+ const patternTrailer = key.slice(patternIndex + 1);
1615
+
1616
+ if (
1617
+ packageSubpath.length >= key.length &&
1618
+ packageSubpath.endsWith(patternTrailer) &&
1619
+ patternKeyCompare(bestMatch, key) === 1 &&
1620
+ key.lastIndexOf('*') === patternIndex
1621
+ ) {
1622
+ bestMatch = key;
1623
+ bestMatchSubpath = packageSubpath.slice(
1624
+ patternIndex,
1625
+ packageSubpath.length - patternTrailer.length
1626
+ );
1627
+ }
1628
+ }
1629
+ }
1630
+
1631
+ if (bestMatch) {
1632
+ // @ts-expect-error: indexable.
1633
+ const target = /** @type {unknown} */ (exports$1[bestMatch]);
1634
+ const resolveResult = resolvePackageTarget(
1635
+ packageJsonUrl,
1636
+ target,
1637
+ bestMatchSubpath,
1638
+ bestMatch,
1639
+ base,
1640
+ true,
1641
+ false,
1642
+ packageSubpath.endsWith('/'),
1643
+ conditions
1644
+ );
1645
+
1646
+ if (resolveResult === null || resolveResult === undefined) {
1647
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1648
+ }
1649
+
1650
+ return resolveResult
1651
+ }
1652
+
1653
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1654
+ }
1655
+
1656
+ /**
1657
+ * @param {string} a
1658
+ * @param {string} b
1659
+ */
1660
+ function patternKeyCompare(a, b) {
1661
+ const aPatternIndex = a.indexOf('*');
1662
+ const bPatternIndex = b.indexOf('*');
1663
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
1664
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
1665
+ if (baseLengthA > baseLengthB) return -1
1666
+ if (baseLengthB > baseLengthA) return 1
1667
+ if (aPatternIndex === -1) return 1
1668
+ if (bPatternIndex === -1) return -1
1669
+ if (a.length > b.length) return -1
1670
+ if (b.length > a.length) return 1
1671
+ return 0
1672
+ }
1673
+
1674
+ /**
1675
+ * @param {string} name
1676
+ * @param {URL} base
1677
+ * @param {Set<string>} [conditions]
1678
+ * @returns {URL}
1679
+ */
1680
+ function packageImportsResolve(name, base, conditions) {
1681
+ if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
1682
+ const reason = 'is not a valid internal imports specifier name';
1683
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
1684
+ }
1685
+
1686
+ /** @type {URL | undefined} */
1687
+ let packageJsonUrl;
1688
+
1689
+ const packageConfig = getPackageScopeConfig(base);
1690
+
1691
+ if (packageConfig.exists) {
1692
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
1693
+ const imports = packageConfig.imports;
1694
+ if (imports) {
1695
+ if (own.call(imports, name) && !name.includes('*')) {
1696
+ const resolveResult = resolvePackageTarget(
1697
+ packageJsonUrl,
1698
+ imports[name],
1699
+ '',
1700
+ name,
1701
+ base,
1702
+ false,
1703
+ true,
1704
+ false,
1705
+ conditions
1706
+ );
1707
+ if (resolveResult !== null && resolveResult !== undefined) {
1708
+ return resolveResult
1709
+ }
1710
+ } else {
1711
+ let bestMatch = '';
1712
+ let bestMatchSubpath = '';
1713
+ const keys = Object.getOwnPropertyNames(imports);
1714
+ let i = -1;
1715
+
1716
+ while (++i < keys.length) {
1717
+ const key = keys[i];
1718
+ const patternIndex = key.indexOf('*');
1719
+
1720
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
1721
+ const patternTrailer = key.slice(patternIndex + 1);
1722
+ if (
1723
+ name.length >= key.length &&
1724
+ name.endsWith(patternTrailer) &&
1725
+ patternKeyCompare(bestMatch, key) === 1 &&
1726
+ key.lastIndexOf('*') === patternIndex
1727
+ ) {
1728
+ bestMatch = key;
1729
+ bestMatchSubpath = name.slice(
1730
+ patternIndex,
1731
+ name.length - patternTrailer.length
1732
+ );
1733
+ }
1734
+ }
1735
+ }
1736
+
1737
+ if (bestMatch) {
1738
+ const target = imports[bestMatch];
1739
+ const resolveResult = resolvePackageTarget(
1740
+ packageJsonUrl,
1741
+ target,
1742
+ bestMatchSubpath,
1743
+ bestMatch,
1744
+ base,
1745
+ true,
1746
+ true,
1747
+ false,
1748
+ conditions
1749
+ );
1750
+
1751
+ if (resolveResult !== null && resolveResult !== undefined) {
1752
+ return resolveResult
1753
+ }
1754
+ }
1755
+ }
1756
+ }
1757
+ }
1758
+
1759
+ throw importNotDefined(name, packageJsonUrl, base)
1760
+ }
1761
+
1762
+ /**
1763
+ * @param {string} specifier
1764
+ * @param {URL} base
1765
+ */
1766
+ function parsePackageName(specifier, base) {
1767
+ let separatorIndex = specifier.indexOf('/');
1768
+ let validPackageName = true;
1769
+ let isScoped = false;
1770
+ if (specifier[0] === '@') {
1771
+ isScoped = true;
1772
+ if (separatorIndex === -1 || specifier.length === 0) {
1773
+ validPackageName = false;
1774
+ } else {
1775
+ separatorIndex = specifier.indexOf('/', separatorIndex + 1);
1776
+ }
1777
+ }
1778
+
1779
+ const packageName =
1780
+ separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
1781
+
1782
+ // Package name cannot have leading . and cannot have percent-encoding or
1783
+ // \\ separators.
1784
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
1785
+ validPackageName = false;
1786
+ }
1787
+
1788
+ if (!validPackageName) {
1789
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1790
+ specifier,
1791
+ 'is not a valid package name',
1792
+ fileURLToPath$1(base)
1793
+ )
1794
+ }
1795
+
1796
+ const packageSubpath =
1797
+ '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
1798
+
1799
+ return {packageName, packageSubpath, isScoped}
1800
+ }
1801
+
1802
+ /**
1803
+ * @param {string} specifier
1804
+ * @param {URL} base
1805
+ * @param {Set<string> | undefined} conditions
1806
+ * @returns {URL}
1807
+ */
1808
+ function packageResolve(specifier, base, conditions) {
1809
+ if (builtinModules.includes(specifier)) {
1810
+ return new URL$1('node:' + specifier)
1811
+ }
1812
+
1813
+ const {packageName, packageSubpath, isScoped} = parsePackageName(
1814
+ specifier,
1815
+ base
1816
+ );
1817
+
1818
+ // ResolveSelf
1819
+ const packageConfig = getPackageScopeConfig(base);
1820
+
1821
+ // Can’t test.
1822
+ /* c8 ignore next 16 */
1823
+ if (packageConfig.exists) {
1824
+ const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
1825
+ if (
1826
+ packageConfig.name === packageName &&
1827
+ packageConfig.exports !== undefined &&
1828
+ packageConfig.exports !== null
1829
+ ) {
1830
+ return packageExportsResolve(
1831
+ packageJsonUrl,
1832
+ packageSubpath,
1833
+ packageConfig,
1834
+ base,
1835
+ conditions
1836
+ )
1837
+ }
1838
+ }
1839
+
1840
+ let packageJsonUrl = new URL$1(
1841
+ './node_modules/' + packageName + '/package.json',
1842
+ base
1843
+ );
1844
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
1845
+ /** @type {string} */
1846
+ let lastPath;
1847
+ do {
1848
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
1849
+ if (!stat || !stat.isDirectory()) {
1850
+ lastPath = packageJsonPath;
1851
+ packageJsonUrl = new URL$1(
1852
+ (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
1853
+ packageName +
1854
+ '/package.json',
1855
+ packageJsonUrl
1856
+ );
1857
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
1858
+ continue
1859
+ }
1860
+
1861
+ // Package match.
1862
+ const packageConfig = read(packageJsonPath, {base, specifier});
1863
+ if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
1864
+ return packageExportsResolve(
1865
+ packageJsonUrl,
1866
+ packageSubpath,
1867
+ packageConfig,
1868
+ base,
1869
+ conditions
1870
+ )
1871
+ }
1872
+
1873
+ if (packageSubpath === '.') {
1874
+ return legacyMainResolve(packageJsonUrl, packageConfig, base)
1875
+ }
1876
+
1877
+ return new URL$1(packageSubpath, packageJsonUrl)
1878
+ // Cross-platform root check.
1879
+ } while (packageJsonPath.length !== lastPath.length)
1880
+
1881
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false)
1882
+ }
1883
+
1884
+ /**
1885
+ * @param {string} specifier
1886
+ * @returns {boolean}
1887
+ */
1888
+ function isRelativeSpecifier(specifier) {
1889
+ if (specifier[0] === '.') {
1890
+ if (specifier.length === 1 || specifier[1] === '/') return true
1891
+ if (
1892
+ specifier[1] === '.' &&
1893
+ (specifier.length === 2 || specifier[2] === '/')
1894
+ ) {
1895
+ return true
1896
+ }
1897
+ }
1898
+
1899
+ return false
1900
+ }
1901
+
1902
+ /**
1903
+ * @param {string} specifier
1904
+ * @returns {boolean}
1905
+ */
1906
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
1907
+ if (specifier === '') return false
1908
+ if (specifier[0] === '/') return true
1909
+ return isRelativeSpecifier(specifier)
1910
+ }
1911
+
1912
+ /**
1913
+ * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
1914
+ * sync and slightly lower-level than `resolve`).
1915
+ *
1916
+ * @param {string} specifier
1917
+ * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
1918
+ * @param {URL} base
1919
+ * Full URL (to a file) that `specifier` is resolved relative from.
1920
+ * @param {Set<string>} [conditions]
1921
+ * Conditions.
1922
+ * @param {boolean} [preserveSymlinks]
1923
+ * Keep symlinks instead of resolving them.
1924
+ * @returns {URL}
1925
+ * A URL object to the found thing.
1926
+ */
1927
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
1928
+ // Note: The Node code supports `base` as a string (in this internal API) too,
1929
+ // we don’t.
1930
+ const protocol = base.protocol;
1931
+ const isData = protocol === 'data:';
1932
+ const isRemote = isData || protocol === 'http:' || protocol === 'https:';
1933
+ // Order swapped from spec for minor perf gain.
1934
+ // Ok since relative URLs cannot parse as URLs.
1935
+ /** @type {URL | undefined} */
1936
+ let resolved;
1937
+
1938
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
1939
+ try {
1940
+ resolved = new URL$1(specifier, base);
1941
+ } catch (error_) {
1942
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
1943
+ error.cause = error_;
1944
+ throw error
1945
+ }
1946
+ } else if (protocol === 'file:' && specifier[0] === '#') {
1947
+ resolved = packageImportsResolve(specifier, base, conditions);
1948
+ } else {
1949
+ try {
1950
+ resolved = new URL$1(specifier);
1951
+ } catch (error_) {
1952
+ // Note: actual code uses `canBeRequiredWithoutScheme`.
1953
+ if (isRemote && !builtinModules.includes(specifier)) {
1954
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
1955
+ error.cause = error_;
1956
+ throw error
1957
+ }
1958
+
1959
+ resolved = packageResolve(specifier, base, conditions);
1960
+ }
1961
+ }
1962
+
1963
+ assert(resolved !== undefined, 'expected to be defined');
1964
+
1965
+ if (resolved.protocol !== 'file:') {
1966
+ return resolved
1967
+ }
1968
+
1969
+ return finalizeResolution(resolved, base)
1970
+ }
1971
+
1972
+ function fileURLToPath(id) {
1973
+ if (typeof id === "string" && !id.startsWith("file://")) {
1974
+ return normalizeSlash(id);
1975
+ }
1976
+ return normalizeSlash(fileURLToPath$1(id));
1977
+ }
1978
+ function pathToFileURL(id) {
1979
+ return pathToFileURL$1(fileURLToPath(id)).toString();
1980
+ }
1981
+ function normalizeid(id) {
1982
+ if (typeof id !== "string") {
1983
+ id = id.toString();
1984
+ }
1985
+ if (/(?:node|data|http|https|file):/.test(id)) {
1986
+ return id;
1987
+ }
1988
+ if (BUILTIN_MODULES.has(id)) {
1989
+ return "node:" + id;
1990
+ }
1991
+ return "file://" + encodeURI(normalizeSlash(id));
1992
+ }
1993
+
1994
+ const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
1995
+ const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
1996
+ const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
1997
+ "ERR_MODULE_NOT_FOUND",
1998
+ "ERR_UNSUPPORTED_DIR_IMPORT",
1999
+ "MODULE_NOT_FOUND",
2000
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
2001
+ ]);
2002
+ function _tryModuleResolve(id, url, conditions) {
2003
+ try {
2004
+ return moduleResolve(id, url, conditions);
2005
+ } catch (error) {
2006
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
2007
+ throw error;
2008
+ }
2009
+ }
2010
+ }
2011
+ function _resolve$1(id, options = {}) {
2012
+ if (typeof id !== "string") {
2013
+ if (id instanceof URL) {
2014
+ id = fileURLToPath(id);
2015
+ } else {
2016
+ throw new TypeError("input must be a `string` or `URL`");
2017
+ }
2018
+ }
2019
+ if (/(?:node|data|http|https):/.test(id)) {
2020
+ return id;
2021
+ }
2022
+ if (BUILTIN_MODULES.has(id)) {
2023
+ return "node:" + id;
2024
+ }
2025
+ if (id.startsWith("file://")) {
2026
+ id = fileURLToPath(id);
2027
+ }
2028
+ if (isAbsolute(id)) {
2029
+ try {
2030
+ const stat = statSync(id);
2031
+ if (stat.isFile()) {
2032
+ return pathToFileURL(id);
2033
+ }
2034
+ } catch (error) {
2035
+ if (error?.code !== "ENOENT") {
2036
+ throw error;
2037
+ }
2038
+ }
2039
+ }
2040
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
2041
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
2042
+ if (_urls.length === 0) {
2043
+ _urls.push(new URL(pathToFileURL(process.cwd())));
2044
+ }
2045
+ const urls = [..._urls];
2046
+ for (const url of _urls) {
2047
+ if (url.protocol === "file:") {
2048
+ urls.push(
2049
+ new URL("./", url),
2050
+ // If url is directory
2051
+ new URL(joinURL(url.pathname, "_index.js"), url),
2052
+ // TODO: Remove in next major version?
2053
+ new URL("node_modules", url)
2054
+ );
2055
+ }
2056
+ }
2057
+ let resolved;
2058
+ for (const url of urls) {
2059
+ resolved = _tryModuleResolve(id, url, conditionsSet);
2060
+ if (resolved) {
2061
+ break;
2062
+ }
2063
+ for (const prefix of ["", "/index"]) {
2064
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
2065
+ resolved = _tryModuleResolve(
2066
+ joinURL(id, prefix) + extension,
2067
+ url,
2068
+ conditionsSet
2069
+ );
2070
+ if (resolved) {
2071
+ break;
2072
+ }
2073
+ }
2074
+ if (resolved) {
2075
+ break;
2076
+ }
2077
+ }
2078
+ if (resolved) {
2079
+ break;
2080
+ }
2081
+ }
2082
+ if (!resolved) {
2083
+ const error = new Error(
2084
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
2085
+ );
2086
+ error.code = "ERR_MODULE_NOT_FOUND";
2087
+ throw error;
2088
+ }
2089
+ return pathToFileURL(resolved);
2090
+ }
2091
+ function resolveSync(id, options) {
2092
+ return _resolve$1(id, options);
2093
+ }
2094
+ function resolvePathSync(id, options) {
2095
+ return fileURLToPath(resolveSync(id, options));
2096
+ }
2097
+
2098
+ const GET_IS_ASYNC = Symbol.for("quansync.getIsAsync");
2099
+ class QuansyncError extends Error {
2100
+ constructor(message = "Unexpected promise in sync context") {
2101
+ super(message);
2102
+ this.name = "QuansyncError";
2103
+ }
2104
+ }
2105
+ function isThenable(value) {
2106
+ return value && typeof value === "object" && typeof value.then === "function";
2107
+ }
2108
+ function isQuansyncGenerator(value) {
2109
+ return value && typeof value === "object" && typeof value[Symbol.iterator] === "function" && "__quansync" in value;
2110
+ }
2111
+ function fromObject(options) {
2112
+ const generator = function* (...args) {
2113
+ const isAsync = yield GET_IS_ASYNC;
2114
+ if (isAsync)
2115
+ return yield options.async.apply(this, args);
2116
+ return options.sync.apply(this, args);
2117
+ };
2118
+ function fn(...args) {
2119
+ const iter = generator.apply(this, args);
2120
+ iter.then = (...thenArgs) => options.async.apply(this, args).then(...thenArgs);
2121
+ iter.__quansync = true;
2122
+ return iter;
2123
+ }
2124
+ fn.sync = options.sync;
2125
+ fn.async = options.async;
2126
+ return fn;
2127
+ }
2128
+ function fromPromise(promise) {
2129
+ return fromObject({
2130
+ async: () => Promise.resolve(promise),
2131
+ sync: () => {
2132
+ if (isThenable(promise))
2133
+ throw new QuansyncError();
2134
+ return promise;
2135
+ }
2136
+ });
2137
+ }
2138
+ function unwrapYield(value, isAsync) {
2139
+ if (value === GET_IS_ASYNC)
2140
+ return isAsync;
2141
+ if (isQuansyncGenerator(value))
2142
+ return isAsync ? iterateAsync(value) : iterateSync(value);
2143
+ if (!isAsync && isThenable(value))
2144
+ throw new QuansyncError();
2145
+ return value;
2146
+ }
2147
+ const DEFAULT_ON_YIELD = (value) => value;
2148
+ function iterateSync(generator, onYield = DEFAULT_ON_YIELD) {
2149
+ let current = generator.next();
2150
+ while (!current.done) {
2151
+ try {
2152
+ current = generator.next(unwrapYield(onYield(current.value, false)));
2153
+ } catch (err) {
2154
+ current = generator.throw(err);
2155
+ }
2156
+ }
2157
+ return unwrapYield(current.value);
2158
+ }
2159
+ async function iterateAsync(generator, onYield = DEFAULT_ON_YIELD) {
2160
+ let current = generator.next();
2161
+ while (!current.done) {
2162
+ try {
2163
+ current = generator.next(await unwrapYield(onYield(current.value, true), true));
2164
+ } catch (err) {
2165
+ current = generator.throw(err);
2166
+ }
2167
+ }
2168
+ return current.value;
2169
+ }
2170
+ function fromGeneratorFn(generatorFn, options) {
2171
+ return fromObject({
2172
+ name: generatorFn.name,
2173
+ async(...args) {
2174
+ return iterateAsync(generatorFn.apply(this, args), options?.onYield);
2175
+ },
2176
+ sync(...args) {
2177
+ return iterateSync(generatorFn.apply(this, args), options?.onYield);
2178
+ }
2179
+ });
2180
+ }
2181
+ function quansync$1(input, options) {
2182
+ if (isThenable(input))
2183
+ return fromPromise(input);
2184
+ if (typeof input === "function")
2185
+ return fromGeneratorFn(input, options);
2186
+ else
2187
+ return fromObject(input);
2188
+ }
2189
+ quansync$1({
2190
+ async: () => Promise.resolve(true),
2191
+ sync: () => false
2192
+ });
2193
+
2194
+ const quansync = quansync$1;
2195
+
2196
+ const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath$1(urlOrPath) : urlOrPath;
2197
+
2198
+ async function findUp$1(name, {
2199
+ cwd = process$1.cwd(),
2200
+ type = 'file',
2201
+ stopAt,
2202
+ } = {}) {
2203
+ let directory = path.resolve(toPath(cwd) ?? '');
2204
+ const {root} = path.parse(directory);
2205
+ stopAt = path.resolve(directory, toPath(stopAt ?? root));
2206
+ const isAbsoluteName = path.isAbsolute(name);
2207
+
2208
+ while (directory) {
2209
+ const filePath = isAbsoluteName ? name : path.join(directory, name);
2210
+ try {
2211
+ const stats = await fs$1.stat(filePath); // eslint-disable-line no-await-in-loop
2212
+ if ((type === 'file' && stats.isFile()) || (type === 'directory' && stats.isDirectory())) {
2213
+ return filePath;
2214
+ }
2215
+ } catch {}
2216
+
2217
+ if (directory === stopAt || directory === root) {
2218
+ break;
2219
+ }
2220
+
2221
+ directory = path.dirname(directory);
2222
+ }
2223
+ }
2224
+
2225
+ function findUpSync(name, {
2226
+ cwd = process$1.cwd(),
2227
+ type = 'file',
2228
+ stopAt,
2229
+ } = {}) {
2230
+ let directory = path.resolve(toPath(cwd) ?? '');
2231
+ const {root} = path.parse(directory);
2232
+ stopAt = path.resolve(directory, toPath(stopAt) ?? root);
2233
+ const isAbsoluteName = path.isAbsolute(name);
2234
+
2235
+ while (directory) {
2236
+ const filePath = isAbsoluteName ? name : path.join(directory, name);
2237
+
2238
+ try {
2239
+ const stats = fs.statSync(filePath, {throwIfNoEntry: false});
2240
+ if ((type === 'file' && stats?.isFile()) || (type === 'directory' && stats?.isDirectory())) {
2241
+ return filePath;
2242
+ }
2243
+ } catch {}
2244
+
2245
+ if (directory === stopAt || directory === root) {
2246
+ break;
2247
+ }
2248
+
2249
+ directory = path.dirname(directory);
2250
+ }
2251
+ }
2252
+
2253
+ function _resolve(path, options = {}) {
2254
+ if (options.platform === "auto" || !options.platform)
2255
+ options.platform = process$1.platform === "win32" ? "win32" : "posix";
2256
+ if (process$1.versions.pnp) {
2257
+ const paths = options.paths || [];
2258
+ if (paths.length === 0)
2259
+ paths.push(process$1.cwd());
2260
+ const targetRequire = createRequire(import.meta.url);
2261
+ try {
2262
+ return targetRequire.resolve(path, { paths });
2263
+ } catch {
2264
+ }
2265
+ }
2266
+ const modulePath = resolvePathSync(path, {
2267
+ url: options.paths
2268
+ });
2269
+ if (options.platform === "win32")
2270
+ return win32.normalize(modulePath);
2271
+ return modulePath;
2272
+ }
2273
+ function resolveModule(name, options = {}) {
2274
+ try {
2275
+ return _resolve(name, options);
2276
+ } catch {
2277
+ return void 0;
2278
+ }
2279
+ }
2280
+ function isPackageExists(name, options = {}) {
2281
+ return !!resolvePackage(name, options);
2282
+ }
2283
+ function getPackageJsonPath(name, options = {}) {
2284
+ const entry = resolvePackage(name, options);
2285
+ if (!entry)
2286
+ return;
2287
+ return searchPackageJSON(entry);
2288
+ }
2289
+ const readFile = quansync({
2290
+ async: (id) => fs.promises.readFile(id, "utf8"),
2291
+ sync: (id) => fs.readFileSync(id, "utf8")
2292
+ });
2293
+ const getPackageInfo = quansync(function* (name, options = {}) {
2294
+ const packageJsonPath = getPackageJsonPath(name, options);
2295
+ if (!packageJsonPath)
2296
+ return;
2297
+ const packageJson = JSON.parse(yield readFile(packageJsonPath));
2298
+ return {
2299
+ name,
2300
+ version: packageJson.version,
2301
+ rootPath: dirname(packageJsonPath),
2302
+ packageJsonPath,
2303
+ packageJson
2304
+ };
2305
+ });
2306
+ getPackageInfo.sync;
2307
+ function resolvePackage(name, options = {}) {
2308
+ try {
2309
+ return _resolve(`${name}/package.json`, options);
2310
+ } catch {
2311
+ }
2312
+ try {
2313
+ return _resolve(name, options);
2314
+ } catch (e) {
2315
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
2316
+ console.error(e);
2317
+ return false;
2318
+ }
2319
+ }
2320
+ function searchPackageJSON(dir) {
2321
+ let packageJsonPath;
2322
+ while (true) {
2323
+ if (!dir)
2324
+ return;
2325
+ const newDir = dirname(dir);
2326
+ if (newDir === dir)
2327
+ return;
2328
+ dir = newDir;
2329
+ packageJsonPath = join(dir, "package.json");
2330
+ if (fs.existsSync(packageJsonPath))
2331
+ break;
2332
+ }
2333
+ return packageJsonPath;
2334
+ }
2335
+ const findUp = quansync({
2336
+ sync: findUpSync,
2337
+ async: findUp$1
2338
+ });
2339
+ const loadPackageJSON = quansync(function* (cwd = process$1.cwd()) {
2340
+ const path = yield findUp("package.json", { cwd });
2341
+ if (!path || !fs.existsSync(path))
2342
+ return null;
2343
+ return JSON.parse(yield readFile(path));
2344
+ });
2345
+ loadPackageJSON.sync;
2346
+ const isPackageListed = quansync(function* (name, cwd) {
2347
+ const pkg = (yield loadPackageJSON(cwd)) || {};
2348
+ return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
2349
+ });
2350
+ isPackageListed.sync;
2351
+
2352
+ function getWorkersCountByPercentage(percent) {
2353
+ const maxWorkersCount = nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length;
2354
+ const workersCountByPercentage = Math.round(Number.parseInt(percent) / 100 * maxWorkersCount);
2355
+ return Math.max(1, Math.min(maxWorkersCount, workersCountByPercentage));
2356
+ }
2357
+
2358
+ class BaseSequencer {
2359
+ ctx;
2360
+ constructor(ctx) {
2361
+ this.ctx = ctx;
2362
+ }
2363
+ // async so it can be extended by other sequelizers
2364
+ async shard(files) {
2365
+ const { config } = this.ctx;
2366
+ const { index, count } = config.shard;
2367
+ const [shardStart, shardEnd] = this.calculateShardRange(files.length, index, count);
2368
+ return [...files].map((spec) => {
2369
+ const specPath = resolve(slash(config.root), slash(spec.moduleId))?.slice(config.root.length);
2370
+ return {
2371
+ spec,
2372
+ hash: hash("sha1", specPath, "hex")
2373
+ };
2374
+ }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ spec }) => spec);
2375
+ }
2376
+ // async so it can be extended by other sequelizers
2377
+ async sort(files) {
2378
+ const cache = this.ctx.cache;
2379
+ return [...files].sort((a, b) => {
2380
+ // "sequence.groupOrder" is higher priority
2381
+ const groupOrderDiff = a.project.config.sequence.groupOrder - b.project.config.sequence.groupOrder;
2382
+ if (groupOrderDiff !== 0) return groupOrderDiff;
2383
+ // Projects run sequential
2384
+ if (a.project.name !== b.project.name) return a.project.name < b.project.name ? -1 : 1;
2385
+ // Isolated run first
2386
+ if (a.project.config.isolate && !b.project.config.isolate) return -1;
2387
+ if (!a.project.config.isolate && b.project.config.isolate) return 1;
2388
+ const keyA = `${a.project.name}:${relative(this.ctx.config.root, a.moduleId)}`;
2389
+ const keyB = `${b.project.name}:${relative(this.ctx.config.root, b.moduleId)}`;
2390
+ const aState = cache.getFileTestResults(keyA);
2391
+ const bState = cache.getFileTestResults(keyB);
2392
+ if (!aState || !bState) {
2393
+ const statsA = cache.getFileStats(keyA);
2394
+ const statsB = cache.getFileStats(keyB);
2395
+ // run unknown first
2396
+ if (!statsA || !statsB) return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0;
2397
+ // run larger files first
2398
+ return statsB.size - statsA.size;
2399
+ }
2400
+ // run failed first
2401
+ if (aState.failed && !bState.failed) return -1;
2402
+ if (!aState.failed && bState.failed) return 1;
2403
+ // run longer first
2404
+ return bState.duration - aState.duration;
2405
+ });
2406
+ }
2407
+ // Calculate distributed shard range [start, end] distributed equally
2408
+ calculateShardRange(filesCount, index, count) {
2409
+ const baseShardSize = Math.floor(filesCount / count);
2410
+ const remainderTestFilesCount = filesCount % count;
2411
+ if (remainderTestFilesCount >= index) {
2412
+ const shardSize = baseShardSize + 1;
2413
+ return [shardSize * (index - 1), shardSize * index];
2414
+ }
2415
+ const shardStart = remainderTestFilesCount * (baseShardSize + 1) + (index - remainderTestFilesCount - 1) * baseShardSize;
2416
+ return [shardStart, shardStart + baseShardSize];
2417
+ }
2418
+ }
2419
+
2420
+ class RandomSequencer extends BaseSequencer {
2421
+ async sort(files) {
2422
+ const { sequence } = this.ctx.config;
2423
+ return shuffle(files, sequence.seed);
2424
+ }
2425
+ }
2426
+
2427
+ function resolvePath(path, root) {
2428
+ return normalize(/* @__PURE__ */ resolveModule(path, { paths: [root] }) ?? resolve(root, path));
2429
+ }
2430
+ function parseInspector(inspect) {
2431
+ if (typeof inspect === "boolean" || inspect === void 0) return {};
2432
+ if (typeof inspect === "number") return { port: inspect };
2433
+ if (inspect.match(/https?:\//)) throw new Error(`Inspector host cannot be a URL. Use "host:port" instead of "${inspect}"`);
2434
+ const [host, port] = inspect.split(":");
2435
+ if (!port) return { host };
2436
+ return {
2437
+ host,
2438
+ port: Number(port) || defaultInspectPort
2439
+ };
2440
+ }
2441
+ function resolveApiServerConfig(options, defaultPort) {
2442
+ let api;
2443
+ if (options.ui && !options.api) api = { port: defaultPort };
2444
+ else if (options.api === true) api = { port: defaultPort };
2445
+ else if (typeof options.api === "number") api = { port: options.api };
2446
+ if (typeof options.api === "object") if (api) {
2447
+ if (options.api.port) api.port = options.api.port;
2448
+ if (options.api.strictPort) api.strictPort = options.api.strictPort;
2449
+ if (options.api.host) api.host = options.api.host;
2450
+ } else api = { ...options.api };
2451
+ if (api) {
2452
+ if (!api.port && !api.middlewareMode) api.port = defaultPort;
2453
+ } else api = { middlewareMode: true };
2454
+ return api;
2455
+ }
2456
+ function resolveInlineWorkerOption(value) {
2457
+ if (typeof value === "string" && value.trim().endsWith("%")) return getWorkersCountByPercentage(value);
2458
+ else return Number(value);
2459
+ }
2460
+ function resolveConfig$1(vitest, options, viteConfig) {
2461
+ const mode = vitest.mode;
2462
+ const logger = vitest.logger;
2463
+ if (options.dom) {
2464
+ if (viteConfig.test?.environment != null && viteConfig.test.environment !== "happy-dom") logger.console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`));
2465
+ options.environment = "happy-dom";
2466
+ }
2467
+ const resolved = {
2468
+ ...configDefaults,
2469
+ ...options,
2470
+ root: viteConfig.root,
2471
+ mode
2472
+ };
2473
+ if (options.pool && typeof options.pool !== "string") {
2474
+ resolved.pool = options.pool.name;
2475
+ resolved.poolRunner = options.pool;
2476
+ }
2477
+ if ("poolOptions" in resolved) logger.deprecate("`test.poolOptions` was removed in Vitest 4. All previous `poolOptions` are now top-level options. Please, refer to the migration guide: https://vitest.dev/guide/migration#pool-rework");
2478
+ resolved.pool ??= "forks";
2479
+ resolved.project = toArray(resolved.project);
2480
+ resolved.provide ??= {};
2481
+ resolved.name = typeof options.name === "string" ? options.name : options.name?.label || "";
2482
+ resolved.color = typeof options.name !== "string" ? options.name?.color : void 0;
2483
+ if (resolved.environment === "browser") throw new Error(`Looks like you set "test.environment" to "browser". To enable Browser Mode, use "test.browser.enabled" instead.`);
2484
+ const inspector = resolved.inspect || resolved.inspectBrk;
2485
+ resolved.inspector = {
2486
+ ...resolved.inspector,
2487
+ ...parseInspector(inspector),
2488
+ enabled: !!inspector,
2489
+ waitForDebugger: options.inspector?.waitForDebugger ?? !!resolved.inspectBrk
2490
+ };
2491
+ if (viteConfig.base !== "/") resolved.base = viteConfig.base;
2492
+ resolved.clearScreen = resolved.clearScreen ?? viteConfig.clearScreen ?? true;
2493
+ if (options.shard) {
2494
+ if (resolved.watch) throw new Error("You cannot use --shard option with enabled watch");
2495
+ const [indexString, countString] = options.shard.split("/");
2496
+ const index = Math.abs(Number.parseInt(indexString, 10));
2497
+ const count = Math.abs(Number.parseInt(countString, 10));
2498
+ if (Number.isNaN(count) || count <= 0) throw new Error("--shard <count> must be a positive number");
2499
+ if (Number.isNaN(index) || index <= 0 || index > count) throw new Error("--shard <index> must be a positive number less then <count>");
2500
+ resolved.shard = {
2501
+ index,
2502
+ count
2503
+ };
2504
+ }
2505
+ if (resolved.standalone && !resolved.watch) throw new Error(`Vitest standalone mode requires --watch`);
2506
+ if (resolved.mergeReports && resolved.watch) throw new Error(`Cannot merge reports with --watch enabled`);
2507
+ if (resolved.maxWorkers) resolved.maxWorkers = resolveInlineWorkerOption(resolved.maxWorkers);
2508
+ if (!(options.fileParallelism ?? mode !== "benchmark"))
2509
+ // ignore user config, parallelism cannot be implemented without limiting workers
2510
+ resolved.maxWorkers = 1;
2511
+ if (resolved.maxConcurrency === 0) {
2512
+ logger.console.warn(c.yellow(`The option "maxConcurrency" cannot be set to 0. Using default value ${configDefaults.maxConcurrency} instead.`));
2513
+ resolved.maxConcurrency = configDefaults.maxConcurrency;
2514
+ }
2515
+ if (resolved.inspect || resolved.inspectBrk) {
2516
+ if (resolved.maxWorkers !== 1) {
2517
+ const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
2518
+ throw new Error(`You cannot use ${inspectOption} without "--no-file-parallelism"`);
2519
+ }
2520
+ }
2521
+ // apply browser CLI options only if the config already has the browser config and not disabled manually
2522
+ if (vitest._cliOptions.browser && resolved.browser && (resolved.browser.enabled !== false || vitest._cliOptions.browser.enabled)) resolved.browser = mergeConfig(resolved.browser, vitest._cliOptions.browser);
2523
+ resolved.browser ??= {};
2524
+ const browser = resolved.browser;
2525
+ if (browser.enabled) {
2526
+ const instances = browser.instances;
2527
+ if (!browser.instances) browser.instances = [];
2528
+ // use `chromium` by default when the preview provider is specified
2529
+ // for a smoother experience. if chromium is not available, it will
2530
+ // open the default browser anyway
2531
+ if (!browser.instances.length && browser.provider?.name === "preview") browser.instances = [{ browser: "chromium" }];
2532
+ if (browser.name && instances?.length) {
2533
+ // --browser=chromium filters configs to a single one
2534
+ browser.instances = browser.instances.filter((instance) => instance.browser === browser.name);
2535
+ // if `instances` were defined, but now they are empty,
2536
+ // let's throw an error because the filter is invalid
2537
+ if (!browser.instances.length) throw new Error([`"browser.instances" was set in the config, but the array is empty. Define at least one browser config.`, ` The "browser.name" was set to "${browser.name}" which filtered all configs (${instances.map((c) => c.browser).join(", ")}). Did you mean to use another name?`].join(""));
2538
+ }
2539
+ }
2540
+ const containsChromium = hasBrowserChromium(vitest, resolved);
2541
+ const hasOnlyChromium = hasOnlyBrowserChromium(vitest, resolved);
2542
+ // Browser-mode "Chromium" only features:
2543
+ if (browser.enabled && (!containsChromium || !hasOnlyChromium)) {
2544
+ const browserConfig = `
2545
+ {
2546
+ browser: {
2547
+ provider: ${browser.provider?.name || "preview"}(),
2548
+ instances: [
2549
+ ${(browser.instances || []).map((i) => `{ browser: '${i.browser}' }`).join(",\n ")}
2550
+ ],
2551
+ },
2552
+ }
2553
+ `.trim();
2554
+ const preferredProvider = !browser.provider?.name || browser.provider.name === "preview" ? "playwright" : browser.provider.name;
2555
+ const correctExample = `
2556
+ {
2557
+ browser: {
2558
+ provider: ${preferredProvider}(),
2559
+ instances: [
2560
+ { browser: '${preferredProvider === "playwright" ? "chromium" : "chrome"}' }
2561
+ ],
2562
+ },
2563
+ }
2564
+ `.trim();
2565
+ // requires all projects to be chromium
2566
+ if (!hasOnlyChromium && resolved.coverage.enabled && resolved.coverage.provider === "v8") {
2567
+ const coverageExample = `
2568
+ {
2569
+ coverage: {
2570
+ provider: 'istanbul',
2571
+ },
2572
+ }
2573
+ `.trim();
2574
+ throw new Error(`@vitest/coverage-v8 does not work with\n${browserConfig}\n\nUse either:\n${correctExample}\n\n...or change your coverage provider to:\n${coverageExample}\n`);
2575
+ }
2576
+ // ignores non-chromium browsers when there is at least one chromium project
2577
+ if (!containsChromium && (resolved.inspect || resolved.inspectBrk)) {
2578
+ const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
2579
+ throw new Error(`${inspectOption} does not work with\n${browserConfig}\n\nUse either:\n${correctExample}\n\n...or disable ${inspectOption}\n`);
2580
+ }
2581
+ }
2582
+ resolved.coverage.reporter = resolveCoverageReporters(resolved.coverage.reporter);
2583
+ if (resolved.coverage.enabled && resolved.coverage.reportsDirectory) {
2584
+ const reportsDirectory = resolve(resolved.root, resolved.coverage.reportsDirectory);
2585
+ if (reportsDirectory === resolved.root || reportsDirectory === process.cwd()) throw new Error(`You cannot set "coverage.reportsDirectory" as ${reportsDirectory}. Vitest needs to be able to remove this directory before test run`);
2586
+ }
2587
+ if (resolved.coverage.enabled && resolved.coverage.provider === "custom" && resolved.coverage.customProviderModule) resolved.coverage.customProviderModule = resolvePath(resolved.coverage.customProviderModule, resolved.root);
2588
+ resolved.expect ??= {};
2589
+ resolved.deps ??= {};
2590
+ resolved.deps.moduleDirectories ??= [];
2591
+ resolved.deps.optimizer ??= {};
2592
+ resolved.deps.optimizer.ssr ??= {};
2593
+ resolved.deps.optimizer.ssr.enabled ??= false;
2594
+ resolved.deps.optimizer.client ??= {};
2595
+ resolved.deps.optimizer.client.enabled ??= false;
2596
+ resolved.deps.web ??= {};
2597
+ resolved.deps.web.transformAssets ??= true;
2598
+ resolved.deps.web.transformCss ??= true;
2599
+ resolved.deps.web.transformGlobPattern ??= [];
2600
+ resolved.setupFiles = toArray(resolved.setupFiles || []).map((file) => resolvePath(file, resolved.root));
2601
+ resolved.globalSetup = toArray(resolved.globalSetup || []).map((file) => resolvePath(file, resolved.root));
2602
+ // Add hard-coded default coverage exclusions. These cannot be overidden by user config.
2603
+ // Override original exclude array for cases where user re-uses same object in test.exclude.
2604
+ resolved.coverage.exclude = [
2605
+ ...resolved.coverage.exclude,
2606
+ ...resolved.setupFiles.map((file) => `${resolved.coverage.allowExternal ? "**/" : ""}${relative(resolved.root, file)}`),
2607
+ ...resolved.include,
2608
+ resolved.config && slash(resolved.config),
2609
+ ...configFiles,
2610
+ "**/virtual:*",
2611
+ "**/__x00__*",
2612
+ "**/node_modules/**"
2613
+ ].filter((pattern) => typeof pattern === "string");
2614
+ resolved.forceRerunTriggers = [...resolved.forceRerunTriggers, ...resolved.setupFiles];
2615
+ if (resolved.cliExclude) resolved.exclude.push(...resolved.cliExclude);
2616
+ if (resolved.runner) resolved.runner = resolvePath(resolved.runner, resolved.root);
2617
+ resolved.attachmentsDir = resolve(resolved.root, resolved.attachmentsDir ?? ".vitest-attachments");
2618
+ if (resolved.snapshotEnvironment) resolved.snapshotEnvironment = resolvePath(resolved.snapshotEnvironment, resolved.root);
2619
+ resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
2620
+ if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat) {
2621
+ resolved.snapshotFormat.plugins = [];
2622
+ // TODO: support it via separate config (like DiffOptions) or via `Function.toString()`
2623
+ if (typeof resolved.snapshotFormat.compareKeys === "function") throw new TypeError(`"snapshotFormat.compareKeys" function is not supported.`);
2624
+ }
2625
+ const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
2626
+ resolved.snapshotOptions = {
2627
+ expand: resolved.expandSnapshotDiff ?? false,
2628
+ snapshotFormat: resolved.snapshotFormat || {},
2629
+ updateSnapshot: isCI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
2630
+ resolveSnapshotPath: options.resolveSnapshotPath,
2631
+ snapshotEnvironment: null
2632
+ };
2633
+ resolved.snapshotSerializers ??= [];
2634
+ resolved.snapshotSerializers = resolved.snapshotSerializers.map((file) => resolvePath(file, resolved.root));
2635
+ resolved.forceRerunTriggers.push(...resolved.snapshotSerializers);
2636
+ if (options.resolveSnapshotPath) delete resolved.resolveSnapshotPath;
2637
+ resolved.execArgv ??= [];
2638
+ resolved.pool ??= "threads";
2639
+ if (resolved.pool === "vmForks" || resolved.pool === "vmThreads" || resolved.pool === "typescript") resolved.isolate = false;
2640
+ if (process.env.VITEST_MAX_WORKERS) resolved.maxWorkers = Number.parseInt(process.env.VITEST_MAX_WORKERS);
2641
+ if (mode === "benchmark") {
2642
+ resolved.benchmark = {
2643
+ ...benchmarkConfigDefaults,
2644
+ ...resolved.benchmark
2645
+ };
2646
+ // override test config
2647
+ resolved.coverage.enabled = false;
2648
+ resolved.typecheck.enabled = false;
2649
+ resolved.include = resolved.benchmark.include;
2650
+ resolved.exclude = resolved.benchmark.exclude;
2651
+ resolved.includeSource = resolved.benchmark.includeSource;
2652
+ const reporters = Array.from(new Set([...toArray(resolved.benchmark.reporters), ...toArray(options.reporter)])).filter(Boolean);
2653
+ if (reporters.length) resolved.benchmark.reporters = reporters;
2654
+ else resolved.benchmark.reporters = ["default"];
2655
+ if (options.outputFile) resolved.benchmark.outputFile = options.outputFile;
2656
+ // --compare from cli
2657
+ if (options.compare) resolved.benchmark.compare = options.compare;
2658
+ if (options.outputJson) resolved.benchmark.outputJson = options.outputJson;
2659
+ }
2660
+ if (typeof resolved.diff === "string") {
2661
+ resolved.diff = resolvePath(resolved.diff, resolved.root);
2662
+ resolved.forceRerunTriggers.push(resolved.diff);
2663
+ }
2664
+ resolved.api = {
2665
+ ...resolveApiServerConfig(options, defaultPort),
2666
+ token: crypto.randomUUID()
2667
+ };
2668
+ if (options.related) resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
2669
+ /*
2670
+ * Reporters can be defined in many different ways:
2671
+ * { reporter: 'json' }
2672
+ * { reporter: { onFinish() { method() } } }
2673
+ * { reporter: ['json', { onFinish() { method() } }] }
2674
+ * { reporter: [[ 'json' ]] }
2675
+ * { reporter: [[ 'json' ], 'html'] }
2676
+ * { reporter: [[ 'json', { outputFile: 'test.json' } ], 'html'] }
2677
+ */
2678
+ if (options.reporters) if (!Array.isArray(options.reporters))
2679
+ // Reporter name, e.g. { reporters: 'json' }
2680
+ if (typeof options.reporters === "string") resolved.reporters = [[options.reporters, {}]];
2681
+ else resolved.reporters = [options.reporters];
2682
+ else {
2683
+ resolved.reporters = [];
2684
+ for (const reporter of options.reporters) if (Array.isArray(reporter))
2685
+ // Reporter with options, e.g. { reporters: [ [ 'json', { outputFile: 'test.json' } ] ] }
2686
+ resolved.reporters.push([reporter[0], reporter[1] || {}]);
2687
+ else if (typeof reporter === "string")
2688
+ // Reporter name in array, e.g. { reporters: ["html", "json"]}
2689
+ resolved.reporters.push([reporter, {}]);
2690
+ else
2691
+ // Inline reporter, e.g. { reporter: [{ onFinish() { method() } }] }
2692
+ resolved.reporters.push(reporter);
2693
+ }
2694
+ if (mode !== "benchmark") {
2695
+ // @ts-expect-error "reporter" is from CLI, should be absolute to the running directory
2696
+ // it is passed down as "vitest --reporter ../reporter.js"
2697
+ const reportersFromCLI = resolved.reporter;
2698
+ const cliReporters = toArray(reportersFromCLI || []).map((reporter) => {
2699
+ // ./reporter.js || ../reporter.js, but not .reporters/reporter.js
2700
+ if (/^\.\.?\//.test(reporter)) return resolve(process.cwd(), reporter);
2701
+ return reporter;
2702
+ });
2703
+ if (cliReporters.length) {
2704
+ // When CLI reporters are specified, preserve options from config file
2705
+ const configReportersMap = /* @__PURE__ */ new Map();
2706
+ // Build a map of reporter names to their options from the config
2707
+ for (const reporter of resolved.reporters) if (Array.isArray(reporter)) {
2708
+ const [reporterName, reporterOptions] = reporter;
2709
+ if (typeof reporterName === "string") configReportersMap.set(reporterName, reporterOptions);
2710
+ }
2711
+ resolved.reporters = Array.from(new Set(toArray(cliReporters))).filter(Boolean).map((reporter) => [reporter, configReportersMap.get(reporter) || {}]);
2712
+ }
2713
+ }
2714
+ if (!resolved.reporters.length) {
2715
+ resolved.reporters.push(["default", {}]);
2716
+ // also enable github-actions reporter as a default
2717
+ if (process.env.GITHUB_ACTIONS === "true") resolved.reporters.push(["github-actions", {}]);
2718
+ }
2719
+ if (resolved.changed) resolved.passWithNoTests ??= true;
2720
+ resolved.css ??= {};
2721
+ if (typeof resolved.css === "object") {
2722
+ resolved.css.modules ??= {};
2723
+ resolved.css.modules.classNameStrategy ??= "stable";
2724
+ }
2725
+ if (resolved.cache !== false) {
2726
+ if (resolved.cache && typeof resolved.cache.dir === "string") vitest.logger.deprecate(`"cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest"`);
2727
+ resolved.cache = { dir: viteConfig.cacheDir };
2728
+ }
2729
+ resolved.sequence ??= {};
2730
+ if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === "object") {
2731
+ const { files, tests } = resolved.sequence.shuffle;
2732
+ resolved.sequence.sequencer ??= files ? RandomSequencer : BaseSequencer;
2733
+ resolved.sequence.shuffle = tests;
2734
+ }
2735
+ if (!resolved.sequence?.sequencer)
2736
+ // CLI flag has higher priority
2737
+ resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
2738
+ resolved.sequence.groupOrder ??= 0;
2739
+ resolved.sequence.hooks ??= "stack";
2740
+ if (resolved.sequence.sequencer === RandomSequencer) resolved.sequence.seed ??= Date.now();
2741
+ resolved.typecheck = {
2742
+ ...configDefaults.typecheck,
2743
+ ...resolved.typecheck
2744
+ };
2745
+ resolved.typecheck ??= {};
2746
+ resolved.typecheck.enabled ??= false;
2747
+ if (resolved.typecheck.enabled) logger.console.warn(c.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."));
2748
+ resolved.browser.enabled ??= false;
2749
+ resolved.browser.headless ??= isCI;
2750
+ resolved.browser.isolate ??= resolved.isolate ?? true;
2751
+ resolved.browser.fileParallelism ??= options.fileParallelism ?? mode !== "benchmark";
2752
+ // disable in headless mode by default, and if CI is detected
2753
+ resolved.browser.ui ??= resolved.browser.headless === true ? false : !isCI;
2754
+ resolved.browser.commands ??= {};
2755
+ if (resolved.browser.screenshotDirectory) resolved.browser.screenshotDirectory = resolve(resolved.root, resolved.browser.screenshotDirectory);
2756
+ if (resolved.inspector.enabled) resolved.browser.trackUnhandledErrors ??= false;
2757
+ resolved.browser.viewport ??= {};
2758
+ resolved.browser.viewport.width ??= 414;
2759
+ resolved.browser.viewport.height ??= 896;
2760
+ resolved.browser.locators ??= {};
2761
+ resolved.browser.locators.testIdAttribute ??= "data-testid";
2762
+ if (typeof resolved.browser.provider === "string") {
2763
+ const source = `@vitest/browser-${resolved.browser.provider}`;
2764
+ throw new TypeError(`The \`browser.provider\` configuration was changed to accept a factory instead of a string. Add an import of "${resolved.browser.provider}" from "${source}" instead. See: https://vitest.dev/config/browser/provider`);
2765
+ }
2766
+ const isPreview = resolved.browser.provider?.name === "preview";
2767
+ if (!isPreview && resolved.browser.enabled && provider === "stackblitz") throw new Error(`stackblitz environment does not support the ${resolved.browser.provider?.name} provider. Please, use "@vitest/browser-preview" instead.`);
2768
+ if (isPreview && resolved.browser.screenshotFailures === true) {
2769
+ console.warn(c.yellow([
2770
+ `Browser provider "preview" doesn't support screenshots, `,
2771
+ `so "browser.screenshotFailures" option is forcefully disabled. `,
2772
+ `Set "browser.screenshotFailures" to false or remove it from the config to suppress this warning.`
2773
+ ].join("")));
2774
+ resolved.browser.screenshotFailures = false;
2775
+ } else resolved.browser.screenshotFailures ??= !isPreview && !resolved.browser.ui;
2776
+ if (resolved.browser.provider && resolved.browser.provider.options == null) resolved.browser.provider.options = {};
2777
+ resolved.browser.api = resolveApiServerConfig(resolved.browser, defaultBrowserPort) || { port: defaultBrowserPort };
2778
+ // enable includeTaskLocation by default in UI mode
2779
+ if (resolved.browser.enabled) {
2780
+ if (resolved.browser.ui) resolved.includeTaskLocation ??= true;
2781
+ } else if (resolved.ui) resolved.includeTaskLocation ??= true;
2782
+ if (typeof resolved.browser.trace === "string" || !resolved.browser.trace) resolved.browser.trace = { mode: resolved.browser.trace || "off" };
2783
+ if (resolved.browser.trace.tracesDir != null) resolved.browser.trace.tracesDir = resolvePath(resolved.browser.trace.tracesDir, resolved.root);
2784
+ if (toArray(resolved.reporters).some((reporter) => {
2785
+ if (Array.isArray(reporter)) return reporter[0] === "html";
2786
+ return false;
2787
+ })) resolved.includeTaskLocation ??= true;
2788
+ resolved.server ??= {};
2789
+ resolved.server.deps ??= {};
2790
+ if (resolved.server.debug?.dump || process.env.VITEST_DEBUG_DUMP) {
2791
+ const userFolder = resolved.server.debug?.dump || process.env.VITEST_DEBUG_DUMP;
2792
+ resolved.dumpDir = resolve(resolved.root, typeof userFolder === "string" && userFolder !== "true" ? userFolder : ".vitest-dump", resolved.name || "root");
2793
+ }
2794
+ resolved.testTimeout ??= resolved.browser.enabled ? 15e3 : 5e3;
2795
+ resolved.hookTimeout ??= resolved.browser.enabled ? 3e4 : 1e4;
2796
+ resolved.experimental ??= {};
2797
+ if (resolved.experimental.openTelemetry?.sdkPath) {
2798
+ const sdkPath = resolve(resolved.root, resolved.experimental.openTelemetry.sdkPath);
2799
+ resolved.experimental.openTelemetry.sdkPath = pathToFileURL$1(sdkPath).toString();
2800
+ }
2801
+ if (resolved.experimental.openTelemetry?.browserSdkPath) {
2802
+ const browserSdkPath = resolve(resolved.root, resolved.experimental.openTelemetry.browserSdkPath);
2803
+ resolved.experimental.openTelemetry.browserSdkPath = browserSdkPath;
2804
+ }
2805
+ if (resolved.experimental.fsModuleCachePath) resolved.experimental.fsModuleCachePath = resolve(resolved.root, resolved.experimental.fsModuleCachePath);
2806
+ return resolved;
2807
+ }
2808
+ function isBrowserEnabled(config) {
2809
+ return Boolean(config.browser?.enabled);
2810
+ }
2811
+ function resolveCoverageReporters(configReporters) {
2812
+ // E.g. { reporter: "html" }
2813
+ if (!Array.isArray(configReporters)) return [[configReporters, {}]];
2814
+ const resolvedReporters = [];
2815
+ for (const reporter of configReporters) if (Array.isArray(reporter))
2816
+ // E.g. { reporter: [ ["html", { skipEmpty: true }], ["lcov"], ["json", { file: "map.json" }] ]}
2817
+ resolvedReporters.push([reporter[0], reporter[1] || {}]);
2818
+ else
2819
+ // E.g. { reporter: ["html", "json"]}
2820
+ resolvedReporters.push([reporter, {}]);
2821
+ return resolvedReporters;
2822
+ }
2823
+ function isChromiumName(provider, name) {
2824
+ if (provider === "playwright") return name === "chromium";
2825
+ return name === "chrome" || name === "edge";
2826
+ }
2827
+ function hasBrowserChromium(vitest, config) {
2828
+ const browser = config.browser;
2829
+ if (!browser || !browser.provider || browser.provider.name === "preview" || !browser.enabled) return false;
2830
+ if (browser.name) return isChromiumName(browser.provider.name, browser.name);
2831
+ if (!browser.instances) return false;
2832
+ return browser.instances.some((instance) => {
2833
+ const name = instance.name || (config.name ? `${config.name} (${instance.browser})` : instance.browser);
2834
+ // browser config is filtered out
2835
+ if (!vitest.matchesProjectFilter(name)) return false;
2836
+ return isChromiumName(browser.provider.name, instance.browser);
2837
+ });
2838
+ }
2839
+ function hasOnlyBrowserChromium(vitest, config) {
2840
+ const browser = config.browser;
2841
+ if (!browser || !browser.provider || browser.provider.name === "preview" || !browser.enabled) return false;
2842
+ if (browser.name) return isChromiumName(browser.provider.name, browser.name);
2843
+ if (!browser.instances) return false;
2844
+ return browser.instances.every((instance) => {
2845
+ const name = instance.name || (config.name ? `${config.name} (${instance.browser})` : instance.browser);
2846
+ // browser config is filtered out
2847
+ if (!vitest.matchesProjectFilter(name)) return true;
2848
+ return isChromiumName(browser.provider.name, instance.browser);
2849
+ });
2850
+ }
2851
+
2852
+ const THRESHOLD_KEYS = [
2853
+ "lines",
2854
+ "functions",
2855
+ "statements",
2856
+ "branches"
2857
+ ];
2858
+ const GLOBAL_THRESHOLDS_KEY = "global";
2859
+ const DEFAULT_PROJECT = Symbol.for("default-project");
2860
+ let uniqueId = 0;
2861
+ async function getCoverageProvider(options, loader) {
2862
+ const coverageModule = await resolveCoverageProviderModule(options, loader);
2863
+ if (coverageModule) return coverageModule.getProvider();
2864
+ return null;
2865
+ }
2866
+ class BaseCoverageProvider {
2867
+ ctx;
2868
+ name;
2869
+ version;
2870
+ options;
2871
+ globCache = /* @__PURE__ */ new Map();
2872
+ coverageFiles = /* @__PURE__ */ new Map();
2873
+ pendingPromises = [];
2874
+ coverageFilesDirectory;
2875
+ roots = [];
2876
+ _initialize(ctx) {
2877
+ this.ctx = ctx;
2878
+ if (ctx.version !== this.version) ctx.logger.warn(c.yellow(`Loaded ${c.inverse(c.yellow(` vitest@${ctx.version} `))} and ${c.inverse(c.yellow(` @vitest/coverage-${this.name}@${this.version} `))}.
2879
+ Running mixed versions is not supported and may lead into bugs
2880
+ Update your dependencies and make sure the versions match.`));
2881
+ const config = ctx._coverageOptions;
2882
+ this.options = {
2883
+ ...coverageConfigDefaults,
2884
+ ...config,
2885
+ provider: this.name,
2886
+ reportsDirectory: resolve(ctx.config.root, config.reportsDirectory || coverageConfigDefaults.reportsDirectory),
2887
+ reporter: resolveCoverageReporters(config.reporter || coverageConfigDefaults.reporter),
2888
+ thresholds: config.thresholds && {
2889
+ ...config.thresholds,
2890
+ lines: config.thresholds["100"] ? 100 : config.thresholds.lines,
2891
+ branches: config.thresholds["100"] ? 100 : config.thresholds.branches,
2892
+ functions: config.thresholds["100"] ? 100 : config.thresholds.functions,
2893
+ statements: config.thresholds["100"] ? 100 : config.thresholds.statements
2894
+ }
2895
+ };
2896
+ const shard = this.ctx.config.shard;
2897
+ const tempDirectory = `.tmp${shard ? `-${shard.index}-${shard.count}` : ""}`;
2898
+ this.coverageFilesDirectory = resolve(this.options.reportsDirectory, tempDirectory);
2899
+ // If --project filter is set pick only roots of resolved projects
2900
+ this.roots = ctx.config.project?.length ? [...new Set(ctx.projects.map((project) => project.config.root))] : [ctx.config.root];
2901
+ }
2902
+ /**
2903
+ * Check if file matches `coverage.include` but not `coverage.exclude`
2904
+ */
2905
+ isIncluded(_filename, root) {
2906
+ const roots = root ? [root] : this.roots;
2907
+ const filename = slash(_filename);
2908
+ const cacheHit = this.globCache.get(filename);
2909
+ if (cacheHit !== void 0) return cacheHit;
2910
+ // File outside project root with default allowExternal
2911
+ if (this.options.allowExternal === false && roots.every((root) => !filename.startsWith(root))) {
2912
+ this.globCache.set(filename, false);
2913
+ return false;
2914
+ }
2915
+ // By default `coverage.include` matches all files, except "coverage.exclude"
2916
+ const glob = this.options.include || "**";
2917
+ const included = pm.isMatch(filename, glob, {
2918
+ contains: true,
2919
+ dot: true,
2920
+ ignore: this.options.exclude
2921
+ });
2922
+ this.globCache.set(filename, included);
2923
+ return included;
2924
+ }
2925
+ async getUntestedFilesByRoot(testedFiles, include, root) {
2926
+ let includedFiles = await glob(include, {
2927
+ cwd: root,
2928
+ ignore: [...this.options.exclude, ...testedFiles.map((file) => slash(file))],
2929
+ absolute: true,
2930
+ dot: true,
2931
+ onlyFiles: true
2932
+ });
2933
+ // Run again through picomatch as tinyglobby's exclude pattern is different ({ "exclude": ["math"] } should ignore "src/math.ts")
2934
+ includedFiles = includedFiles.filter((file) => this.isIncluded(file, root));
2935
+ if (this.ctx.config.changed) includedFiles = (this.ctx.config.related || []).filter((file) => includedFiles.includes(file));
2936
+ return includedFiles.map((file) => slash(path.resolve(root, file)));
2937
+ }
2938
+ async getUntestedFiles(testedFiles) {
2939
+ if (this.options.include == null) return [];
2940
+ const rootMapper = this.getUntestedFilesByRoot.bind(this, testedFiles, this.options.include);
2941
+ return (await Promise.all(this.roots.map(rootMapper))).flatMap((files) => files);
2942
+ }
2943
+ createCoverageMap() {
2944
+ throw new Error("BaseReporter's createCoverageMap was not overwritten");
2945
+ }
2946
+ async generateReports(_, __) {
2947
+ throw new Error("BaseReporter's generateReports was not overwritten");
2948
+ }
2949
+ async parseConfigModule(_) {
2950
+ throw new Error("BaseReporter's parseConfigModule was not overwritten");
2951
+ }
2952
+ resolveOptions() {
2953
+ return this.options;
2954
+ }
2955
+ async clean(clean = true) {
2956
+ if (clean && existsSync(this.options.reportsDirectory)) await promises.rm(this.options.reportsDirectory, {
2957
+ recursive: true,
2958
+ force: true,
2959
+ maxRetries: 10
2960
+ });
2961
+ if (existsSync(this.coverageFilesDirectory)) await promises.rm(this.coverageFilesDirectory, {
2962
+ recursive: true,
2963
+ force: true,
2964
+ maxRetries: 10
2965
+ });
2966
+ await promises.mkdir(this.coverageFilesDirectory, { recursive: true });
2967
+ this.coverageFiles = /* @__PURE__ */ new Map();
2968
+ this.pendingPromises = [];
2969
+ }
2970
+ onAfterSuiteRun({ coverage, environment, projectName, testFiles }) {
2971
+ if (!coverage) return;
2972
+ let entry = this.coverageFiles.get(projectName || DEFAULT_PROJECT);
2973
+ if (!entry) {
2974
+ entry = {};
2975
+ this.coverageFiles.set(projectName || DEFAULT_PROJECT, entry);
2976
+ }
2977
+ const testFilenames = testFiles.join();
2978
+ const filename = resolve(this.coverageFilesDirectory, `coverage-${uniqueId++}.json`);
2979
+ entry[environment] ??= {};
2980
+ // If there's a result from previous run, overwrite it
2981
+ entry[environment][testFilenames] = filename;
2982
+ const promise = promises.writeFile(filename, JSON.stringify(coverage), "utf-8");
2983
+ this.pendingPromises.push(promise);
2984
+ }
2985
+ async readCoverageFiles({ onFileRead, onFinished, onDebug }) {
2986
+ let index = 0;
2987
+ const total = this.pendingPromises.length;
2988
+ await Promise.all(this.pendingPromises);
2989
+ this.pendingPromises = [];
2990
+ for (const [projectName, coveragePerProject] of this.coverageFiles.entries()) for (const [environment, coverageByTestfiles] of Object.entries(coveragePerProject)) {
2991
+ const filenames = Object.values(coverageByTestfiles);
2992
+ const project = this.ctx.getProjectByName(projectName);
2993
+ for (const chunk of this.toSlices(filenames, this.options.processingConcurrency)) {
2994
+ if (onDebug.enabled) {
2995
+ index += chunk.length;
2996
+ onDebug(`Reading coverage results ${index}/${total}`);
2997
+ }
2998
+ await Promise.all(chunk.map(async (filename) => {
2999
+ const contents = await promises.readFile(filename, "utf-8");
3000
+ onFileRead(JSON.parse(contents));
3001
+ }));
3002
+ }
3003
+ await onFinished(project, environment);
3004
+ }
3005
+ }
3006
+ async cleanAfterRun() {
3007
+ this.coverageFiles = /* @__PURE__ */ new Map();
3008
+ await promises.rm(this.coverageFilesDirectory, { recursive: true });
3009
+ // Remove empty reports directory, e.g. when only text-reporter is used
3010
+ if (readdirSync(this.options.reportsDirectory).length === 0) await promises.rm(this.options.reportsDirectory, { recursive: true });
3011
+ }
3012
+ async onTestFailure() {
3013
+ if (!this.options.reportOnFailure) await this.cleanAfterRun();
3014
+ }
3015
+ async reportCoverage(coverageMap, { allTestsRun }) {
3016
+ await this.generateReports(coverageMap || this.createCoverageMap(), allTestsRun);
3017
+ if (!(!this.options.cleanOnRerun && this.ctx.config.watch)) await this.cleanAfterRun();
3018
+ }
3019
+ async reportThresholds(coverageMap, allTestsRun) {
3020
+ const resolvedThresholds = this.resolveThresholds(coverageMap);
3021
+ this.checkThresholds(resolvedThresholds);
3022
+ if (this.options.thresholds?.autoUpdate && allTestsRun) {
3023
+ if (!this.ctx.vite.config.configFile) throw new Error("Missing configurationFile. The \"coverage.thresholds.autoUpdate\" can only be enabled when configuration file is used.");
3024
+ const configFilePath = this.ctx.vite.config.configFile;
3025
+ const configModule = await this.parseConfigModule(configFilePath);
3026
+ await this.updateThresholds({
3027
+ thresholds: resolvedThresholds,
3028
+ configurationFile: configModule,
3029
+ onUpdate: () => writeFileSync(configFilePath, configModule.generate().code, "utf-8")
3030
+ });
3031
+ }
3032
+ }
3033
+ /**
3034
+ * Constructs collected coverage and users' threshold options into separate sets
3035
+ * where each threshold set holds their own coverage maps. Threshold set is either
3036
+ * for specific files defined by glob pattern or global for all other files.
3037
+ */
3038
+ resolveThresholds(coverageMap) {
3039
+ const resolvedThresholds = [];
3040
+ const files = coverageMap.files();
3041
+ const globalCoverageMap = this.createCoverageMap();
3042
+ for (const key of Object.keys(this.options.thresholds)) {
3043
+ if (key === "perFile" || key === "autoUpdate" || key === "100" || THRESHOLD_KEYS.includes(key)) continue;
3044
+ const glob = key;
3045
+ const globThresholds = resolveGlobThresholds(this.options.thresholds[glob]);
3046
+ const globCoverageMap = this.createCoverageMap();
3047
+ const matcher = pm(glob);
3048
+ const matchingFiles = files.filter((file) => matcher(relative(this.ctx.config.root, file)));
3049
+ for (const file of matchingFiles) {
3050
+ const fileCoverage = coverageMap.fileCoverageFor(file);
3051
+ globCoverageMap.addFileCoverage(fileCoverage);
3052
+ }
3053
+ resolvedThresholds.push({
3054
+ name: glob,
3055
+ coverageMap: globCoverageMap,
3056
+ thresholds: globThresholds
3057
+ });
3058
+ }
3059
+ // Global threshold is for all files, even if they are included by glob patterns
3060
+ for (const file of files) {
3061
+ const fileCoverage = coverageMap.fileCoverageFor(file);
3062
+ globalCoverageMap.addFileCoverage(fileCoverage);
3063
+ }
3064
+ resolvedThresholds.unshift({
3065
+ name: GLOBAL_THRESHOLDS_KEY,
3066
+ coverageMap: globalCoverageMap,
3067
+ thresholds: {
3068
+ branches: this.options.thresholds?.branches,
3069
+ functions: this.options.thresholds?.functions,
3070
+ lines: this.options.thresholds?.lines,
3071
+ statements: this.options.thresholds?.statements
3072
+ }
3073
+ });
3074
+ return resolvedThresholds;
3075
+ }
3076
+ /**
3077
+ * Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
3078
+ */
3079
+ checkThresholds(allThresholds) {
3080
+ for (const { coverageMap, thresholds, name } of allThresholds) {
3081
+ if (thresholds.branches === void 0 && thresholds.functions === void 0 && thresholds.lines === void 0 && thresholds.statements === void 0) continue;
3082
+ // Construct list of coverage summaries where thresholds are compared against
3083
+ const summaries = this.options.thresholds?.perFile ? coverageMap.files().map((file) => ({
3084
+ file,
3085
+ summary: coverageMap.fileCoverageFor(file).toSummary()
3086
+ })) : [{
3087
+ file: null,
3088
+ summary: coverageMap.getCoverageSummary()
3089
+ }];
3090
+ // Check thresholds of each summary
3091
+ for (const { summary, file } of summaries) for (const thresholdKey of THRESHOLD_KEYS) {
3092
+ const threshold = thresholds[thresholdKey];
3093
+ if (threshold === void 0) continue;
3094
+ /**
3095
+ * Positive thresholds are treated as minimum coverage percentages (X means: X% of lines must be covered),
3096
+ * while negative thresholds are treated as maximum uncovered counts (-X means: X lines may be uncovered).
3097
+ */
3098
+ if (threshold >= 0) {
3099
+ const coverage = summary.data[thresholdKey].pct;
3100
+ if (coverage < threshold) {
3101
+ process.exitCode = 1;
3102
+ /**
3103
+ * Generate error message based on perFile flag:
3104
+ * - ERROR: Coverage for statements (33.33%) does not meet threshold (85%) for src/math.ts
3105
+ * - ERROR: Coverage for statements (50%) does not meet global threshold (85%)
3106
+ */
3107
+ let errorMessage = `ERROR: Coverage for ${thresholdKey} (${coverage}%) does not meet ${name === GLOBAL_THRESHOLDS_KEY ? name : `"${name}"`} threshold (${threshold}%)`;
3108
+ if (this.options.thresholds?.perFile && file) errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
3109
+ this.ctx.logger.error(errorMessage);
3110
+ }
3111
+ } else {
3112
+ const uncovered = summary.data[thresholdKey].total - summary.data[thresholdKey].covered;
3113
+ const absoluteThreshold = threshold * -1;
3114
+ if (uncovered > absoluteThreshold) {
3115
+ process.exitCode = 1;
3116
+ /**
3117
+ * Generate error message based on perFile flag:
3118
+ * - ERROR: Uncovered statements (33) exceed threshold (30) for src/math.ts
3119
+ * - ERROR: Uncovered statements (33) exceed global threshold (30)
3120
+ */
3121
+ let errorMessage = `ERROR: Uncovered ${thresholdKey} (${uncovered}) exceed ${name === GLOBAL_THRESHOLDS_KEY ? name : `"${name}"`} threshold (${absoluteThreshold})`;
3122
+ if (this.options.thresholds?.perFile && file) errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
3123
+ this.ctx.logger.error(errorMessage);
3124
+ }
3125
+ }
3126
+ }
3127
+ }
3128
+ }
3129
+ /**
3130
+ * Check if current coverage is above configured thresholds and bump the thresholds if needed
3131
+ */
3132
+ async updateThresholds({ thresholds: allThresholds, onUpdate, configurationFile }) {
3133
+ let updatedThresholds = false;
3134
+ const config = resolveConfig(configurationFile);
3135
+ assertConfigurationModule(config);
3136
+ for (const { coverageMap, thresholds, name } of allThresholds) {
3137
+ const summaries = this.options.thresholds?.perFile ? coverageMap.files().map((file) => coverageMap.fileCoverageFor(file).toSummary()) : [coverageMap.getCoverageSummary()];
3138
+ const thresholdsToUpdate = [];
3139
+ for (const key of THRESHOLD_KEYS) {
3140
+ const threshold = thresholds[key] ?? 100;
3141
+ /**
3142
+ * Positive thresholds are treated as minimum coverage percentages (X means: X% of lines must be covered),
3143
+ * while negative thresholds are treated as maximum uncovered counts (-X means: X lines may be uncovered).
3144
+ */
3145
+ if (threshold >= 0) {
3146
+ const actual = Math.min(...summaries.map((summary) => summary[key].pct));
3147
+ if (actual > threshold) thresholdsToUpdate.push([key, actual]);
3148
+ } else {
3149
+ const absoluteThreshold = threshold * -1;
3150
+ const actual = Math.max(...summaries.map((summary) => summary[key].total - summary[key].covered));
3151
+ if (actual < absoluteThreshold) {
3152
+ // If everything was covered, set new threshold to 100% (since a threshold of 0 would be considered as 0%)
3153
+ const updatedThreshold = actual === 0 ? 100 : actual * -1;
3154
+ thresholdsToUpdate.push([key, updatedThreshold]);
3155
+ }
3156
+ }
3157
+ }
3158
+ if (thresholdsToUpdate.length === 0) continue;
3159
+ updatedThresholds = true;
3160
+ const thresholdFormatter = typeof this.options.thresholds?.autoUpdate === "function" ? this.options.thresholds?.autoUpdate : (value) => value;
3161
+ for (const [threshold, newValue] of thresholdsToUpdate) {
3162
+ const formattedValue = thresholdFormatter(newValue);
3163
+ if (name === GLOBAL_THRESHOLDS_KEY) config.test.coverage.thresholds[threshold] = formattedValue;
3164
+ else {
3165
+ const glob = config.test.coverage.thresholds[name];
3166
+ glob[threshold] = formattedValue;
3167
+ }
3168
+ }
3169
+ }
3170
+ if (updatedThresholds) {
3171
+ this.ctx.logger.log("Updating thresholds to configuration file. You may want to push with updated coverage thresholds.");
3172
+ onUpdate();
3173
+ }
3174
+ }
3175
+ async mergeReports(coverageMaps) {
3176
+ const coverageMap = this.createCoverageMap();
3177
+ for (const coverage of coverageMaps) coverageMap.merge(coverage);
3178
+ await this.generateReports(coverageMap, true);
3179
+ }
3180
+ hasTerminalReporter(reporters) {
3181
+ return reporters.some(([reporter]) => reporter === "text" || reporter === "text-summary" || reporter === "text-lcov" || reporter === "teamcity");
3182
+ }
3183
+ toSlices(array, size) {
3184
+ return array.reduce((chunks, item) => {
3185
+ const index = Math.max(0, chunks.length - 1);
3186
+ const lastChunk = chunks[index] || [];
3187
+ chunks[index] = lastChunk;
3188
+ if (lastChunk.length >= size) chunks.push([item]);
3189
+ else lastChunk.push(item);
3190
+ return chunks;
3191
+ }, []);
3192
+ }
3193
+ createUncoveredFileTransformer(ctx) {
3194
+ const servers = [...ctx.projects.map((project) => ({
3195
+ root: project.config.root,
3196
+ isBrowserEnabled: project.isBrowserEnabled(),
3197
+ vite: project.vite
3198
+ })), (
3199
+ // Check core last as it will match all files anyway
3200
+ {
3201
+ root: ctx.config.root,
3202
+ vite: ctx.vite,
3203
+ isBrowserEnabled: ctx.getRootProject().isBrowserEnabled()
3204
+ })];
3205
+ return async function transformFile(filename) {
3206
+ let lastError;
3207
+ for (const { root, vite, isBrowserEnabled } of servers) {
3208
+ // On Windows root doesn't start with "/" while filenames do
3209
+ if (!filename.startsWith(root) && !filename.startsWith(`/${root}`)) continue;
3210
+ if (isBrowserEnabled) {
3211
+ const result = await vite.environments.client.transformRequest(filename).catch(() => null);
3212
+ if (result) return result;
3213
+ }
3214
+ try {
3215
+ return await vite.environments.ssr.transformRequest(filename);
3216
+ } catch (error) {
3217
+ lastError = error;
3218
+ }
3219
+ }
3220
+ // All vite-node servers failed to transform the file
3221
+ throw lastError;
3222
+ };
3223
+ }
3224
+ }
3225
+ /**
3226
+ * Narrow down `unknown` glob thresholds to resolved ones
3227
+ */
3228
+ function resolveGlobThresholds(thresholds) {
3229
+ if (!thresholds || typeof thresholds !== "object") return {};
3230
+ if (100 in thresholds && thresholds[100] === true) return {
3231
+ lines: 100,
3232
+ branches: 100,
3233
+ functions: 100,
3234
+ statements: 100
3235
+ };
3236
+ return {
3237
+ lines: "lines" in thresholds && typeof thresholds.lines === "number" ? thresholds.lines : void 0,
3238
+ branches: "branches" in thresholds && typeof thresholds.branches === "number" ? thresholds.branches : void 0,
3239
+ functions: "functions" in thresholds && typeof thresholds.functions === "number" ? thresholds.functions : void 0,
3240
+ statements: "statements" in thresholds && typeof thresholds.statements === "number" ? thresholds.statements : void 0
3241
+ };
3242
+ }
3243
+ function assertConfigurationModule(config) {
3244
+ try {
3245
+ // @ts-expect-error -- Intentional unsafe null pointer check as wrapped in try-catch
3246
+ if (typeof config.test.coverage.thresholds !== "object") throw new TypeError("Expected config.test.coverage.thresholds to be an object");
3247
+ } catch (error) {
3248
+ const message = error instanceof Error ? error.message : String(error);
3249
+ throw new Error(`Unable to parse thresholds from configuration file: ${message}`);
3250
+ }
3251
+ }
3252
+ function resolveConfig(configModule) {
3253
+ const mod = configModule.exports.default;
3254
+ try {
3255
+ // Check for "export default { test: {...} }"
3256
+ if (mod.$type === "object") return mod;
3257
+ // "export default defineConfig(...)"
3258
+ let config = resolveDefineConfig(mod);
3259
+ if (config) return config;
3260
+ // "export default mergeConfig(..., defineConfig(...))"
3261
+ if (mod.$type === "function-call" && mod.$callee === "mergeConfig") {
3262
+ config = resolveMergeConfig(mod);
3263
+ if (config) return config;
3264
+ }
3265
+ } catch (error) {
3266
+ // Reduce magicast's verbose errors to readable ones
3267
+ throw new Error(error instanceof Error ? error.message : String(error));
3268
+ }
3269
+ throw new Error("Failed to update coverage thresholds. Configuration file is too complex.");
3270
+ }
3271
+ function resolveDefineConfig(mod) {
3272
+ if (mod.$type === "function-call" && mod.$callee === "defineConfig") {
3273
+ // "export default defineConfig({ test: {...} })"
3274
+ if (mod.$args[0].$type === "object") return mod.$args[0];
3275
+ if (mod.$args[0].$type === "arrow-function-expression") {
3276
+ if (mod.$args[0].$body.$type === "object")
3277
+ // "export default defineConfig(() => ({ test: {...} }))"
3278
+ return mod.$args[0].$body;
3279
+ // "export default defineConfig(() => mergeConfig({...}, ...))"
3280
+ const config = resolveMergeConfig(mod.$args[0].$body);
3281
+ if (config) return config;
3282
+ }
3283
+ }
3284
+ }
3285
+ function resolveMergeConfig(mod) {
3286
+ if (mod.$type === "function-call" && mod.$callee === "mergeConfig") for (const arg of mod.$args) {
3287
+ const config = resolveDefineConfig(arg);
3288
+ if (config) return config;
3289
+ }
3290
+ }
3291
+
3292
+ export { BaseCoverageProvider as B, RandomSequencer as R, resolveApiServerConfig as a, BaseSequencer as b, isBrowserEnabled as c, resolveModule as d, getCoverageProvider as g, hash as h, isPackageExists as i, resolveConfig$1 as r };