vite-hub 0.3.1 → 0.4.1

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 (254) hide show
  1. package/README.md +34 -36
  2. package/dist/_internal/runtime/browser-errors.d.ts +1 -1
  3. package/dist/_internal/runtime/browser-errors.js +1 -1
  4. package/dist/{access-F0YP5D5E.js → access-BDST818p.js} +6 -6
  5. package/dist/{access-policy-BsB3QVe5.d.ts → access-policy-CGXhO3Ee.d.ts} +3 -3
  6. package/dist/{access-policy-B_DCpZUt.js → access-policy-DjBKLo3c.js} +2 -2
  7. package/dist/{account-Bsu-LBOF.d.ts → account-BnOAU055.d.ts} +1 -1
  8. package/dist/{agent-invocations.post-DIm8tJV2.js → agent-invocations.post-CcPvfA0n.js} +7 -7
  9. package/dist/{agents-DnHexzTJ.js → agents-BDeazoAW.js} +2 -2
  10. package/dist/{agents-y5hBFHUQ.js → agents-BoWau_ei.js} +1 -1
  11. package/dist/{auth-BFVHYizM.d.ts → auth-BZOy7obk.d.ts} +2 -2
  12. package/dist/{auth-types-DWpTBZvp.d.ts → auth-types-CyqhWvYF.d.ts} +1 -1
  13. package/dist/bin.js +15 -7
  14. package/dist/{blob-CiUmptIp.d.ts → blob-CFLwMsjH.d.ts} +1 -1
  15. package/dist/{blob-BRV6_wZa.js → blob-CpvlM8jp.js} +3 -3
  16. package/dist/cache/operations.d.ts +1 -1
  17. package/dist/cache/operations.js +2 -2
  18. package/dist/cache.js +1 -1
  19. package/dist/choices/vue.d.ts +1 -0
  20. package/dist/choices/vue.js +2 -0
  21. package/dist/choices.d.ts +1 -0
  22. package/dist/choices.js +2 -0
  23. package/dist/cli-config-UAGTmuFa.js +2 -0
  24. package/dist/{cli-config-Bpjjfz5j.js → cli-config-wxKjF2Y0.js} +1 -16
  25. package/dist/console/auth-types.d.ts +1 -1
  26. package/dist/console/auth.d.ts +1 -1
  27. package/dist/console/auth.js +1 -1
  28. package/dist/console/runtime/client/account.d.ts +1 -1
  29. package/dist/console/runtime/client/account.js +2 -2
  30. package/dist/console/runtime/client/blob-media.d.ts +1 -1
  31. package/dist/console/runtime/client/blob-media.js +3 -3
  32. package/dist/console/runtime/client/comment-thread.js +1 -1
  33. package/dist/console/runtime/client/content-heads.d.ts +45 -0
  34. package/dist/console/runtime/client/content-heads.js +58 -0
  35. package/dist/console/runtime/client/documents.d.ts +2 -2
  36. package/dist/console/runtime/client/documents.js +1 -1
  37. package/dist/console/runtime/client/editor.d.ts +1 -1
  38. package/dist/console/runtime/client/invocation.js +3 -3
  39. package/dist/console/runtime/client/live.d.ts +1 -1
  40. package/dist/console/runtime/client/mcp-client.js +1 -1
  41. package/dist/console/runtime/client/media-library.d.ts +1 -1
  42. package/dist/console/runtime/client/media-library.js +1 -1
  43. package/dist/console/runtime/client/media-uploads.d.ts +1 -1
  44. package/dist/console/runtime/client/media-uploads.js +1 -1
  45. package/dist/console/runtime/client/operation-view.d.ts +1 -1
  46. package/dist/console/runtime/client/operation-view.js +2 -2
  47. package/dist/console/runtime/client/presence.d.ts +1 -1
  48. package/dist/console/runtime/client/problem.js +2 -2
  49. package/dist/console/runtime/client/project-link.d.ts +1 -1
  50. package/dist/console/runtime/client/project-link.js +1 -1
  51. package/dist/console/runtime/client/project-session.d.ts +2 -2
  52. package/dist/console/runtime/client/project-session.js +4 -4
  53. package/dist/console/runtime/client/project.d.ts +1 -1
  54. package/dist/console/runtime/client/project.js +1 -1
  55. package/dist/console/runtime/client/publish.d.ts +1 -1
  56. package/dist/console/runtime/client/rate-limit.js +2 -2
  57. package/dist/console/runtime/client/read-only.d.ts +1 -1
  58. package/dist/console/runtime/client/read-only.js +1 -1
  59. package/dist/console/runtime/client/request.js +1 -1
  60. package/dist/console/runtime/client/schedule-run.js +2 -2
  61. package/dist/console/runtime/client/sections.d.ts +1 -1
  62. package/dist/console/runtime/client/sections.js +1 -1
  63. package/dist/console/runtime/client/sidebar.ts +1 -1
  64. package/dist/console/runtime/client/site-access.js +2 -2
  65. package/dist/console/runtime/client/ticket.js +1 -1
  66. package/dist/console/runtime/client/workflow.js +2 -2
  67. package/dist/console/runtime/components/console-content-heads.vue +72 -0
  68. package/dist/console/runtime/components/console-document-dashboard.vue +43 -35
  69. package/dist/console/runtime/components/console-documents.vue +1 -0
  70. package/dist/console/runtime/components/console-markdown-editor.vue +4 -1
  71. package/dist/console/runtime/components/invocation/agent-invocation.ts +18 -5
  72. package/dist/console/runtime/components/invocation/internal/input-attachments.ts +69 -0
  73. package/dist/console/runtime/components/invocation/internal/invocation-activity.ts +67 -12
  74. package/dist/console/runtime/components/invocation/internal/invocation-conversation.ts +12 -4
  75. package/dist/console/runtime/components/invocation/invocation.css +16 -0
  76. package/dist/console/runtime/console-route.js +1 -1
  77. package/dist/console/runtime/definitions.d.ts +1 -1
  78. package/dist/console/runtime/definitions.js +1 -1
  79. package/dist/console/runtime/diagnostics.ts +30 -30
  80. package/dist/console/runtime/page-tool/page-tool.js +1 -1
  81. package/dist/console/runtime/public/skills/vitehub/SKILL.md +3 -3
  82. package/dist/console/runtime/public/skills/vitehub/references/framework-composition.md +1 -1
  83. package/dist/console/runtime/public/skills/vitehub/references/preview-contract.md +9 -1
  84. package/dist/console/runtime/public/skills/vitehub/references/primitives/channels.md +1 -1
  85. package/dist/console/runtime/public/skills/vitehub/references/primitives/database.md +1 -1
  86. package/dist/console/runtime/public/skills/vitehub/references/primitives/markdown-template.md +3 -3
  87. package/dist/console/runtime/public/skills/vitehub/references/project-shapes.md +2 -2
  88. package/dist/console/runtime/public/skills/vitehub/references/sandboxes-hosts.md +4 -4
  89. package/dist/console/runtime/sections.d.ts +1 -1
  90. package/dist/console/runtime/sections.js +1 -1
  91. package/dist/console/runtime/server/access-policy.d.ts +1 -1
  92. package/dist/console/runtime/server/access-policy.js +1 -1
  93. package/dist/console/runtime/server/agents.get.js +2 -2
  94. package/dist/console/runtime/server/auth.d.ts +1 -1
  95. package/dist/console/runtime/server/auth.js +2 -2
  96. package/dist/console/runtime/server/blob.d.ts +1 -1
  97. package/dist/console/runtime/server/blob.js +1 -1
  98. package/dist/console/runtime/server/channel-replay.d.ts +2 -2
  99. package/dist/console/runtime/server/channel-replay.js +4 -4
  100. package/dist/console/runtime/server/database.d.ts +1 -1
  101. package/dist/console/runtime/server/database.get.d.ts +1 -1
  102. package/dist/console/runtime/server/database.get.js +2 -2
  103. package/dist/console/runtime/server/database.js +1 -1
  104. package/dist/console/runtime/server/definitions.d.ts +1 -1
  105. package/dist/console/runtime/server/definitions.get.d.ts +3 -3
  106. package/dist/console/runtime/server/definitions.get.js +3 -3
  107. package/dist/console/runtime/server/definitions.js +1 -1
  108. package/dist/console/runtime/server/development.d.ts +2 -2
  109. package/dist/console/runtime/server/development.js +2 -2
  110. package/dist/console/runtime/server/documents.d.ts +1 -1
  111. package/dist/console/runtime/server/documents.js +1 -1
  112. package/dist/console/runtime/server/env.get.d.ts +1 -1
  113. package/dist/console/runtime/server/env.get.js +3 -3
  114. package/dist/console/runtime/server/invocation-capabilities.get.js +2 -2
  115. package/dist/console/runtime/server/invocation-workspace.get.d.ts +1 -1
  116. package/dist/console/runtime/server/invocation-workspace.get.js +5 -5
  117. package/dist/console/runtime/server/invocation.get.d.ts +1 -1
  118. package/dist/console/runtime/server/invocation.get.js +6 -6
  119. package/dist/console/runtime/server/invocations.get.js +3 -3
  120. package/dist/console/runtime/server/logs.get.d.ts +2 -2
  121. package/dist/console/runtime/server/logs.get.js +5 -5
  122. package/dist/console/runtime/server/mcp-client-operations.d.ts +1 -1
  123. package/dist/console/runtime/server/mcp-client-operations.js +3 -3
  124. package/dist/console/runtime/server/operation-contributions.d.ts +1 -1
  125. package/dist/console/runtime/server/operation-contributions.js +1 -1
  126. package/dist/console/runtime/server/page-auth.d.ts +1 -1
  127. package/dist/console/runtime/server/page-tool.d.ts +1 -1
  128. package/dist/console/runtime/server/page-tool.js +2 -2
  129. package/dist/console/runtime/server/rpc.d.ts +2 -2
  130. package/dist/console/runtime/server/rpc.js +7 -7
  131. package/dist/console/runtime/server/search.get.js +1 -1
  132. package/dist/console/runtime/server/sections.d.ts +4 -4
  133. package/dist/console/runtime/server/sections.get.d.ts +1 -1
  134. package/dist/console/runtime/server/sections.get.js +5 -5
  135. package/dist/console/runtime/server/sections.js +3 -3
  136. package/dist/console/runtime/server/setup.d.ts +3 -3
  137. package/dist/console/runtime/server/setup.js +2 -2
  138. package/dist/console/runtime/server/site-entry.d.ts +1 -1
  139. package/dist/console/runtime/server/site-entry.js +9 -6
  140. package/dist/console/runtime/server/site-session.d.ts +5 -1
  141. package/dist/console/runtime/server/site-session.js +1 -1
  142. package/dist/console/runtime/server/status.get.d.ts +2 -2
  143. package/dist/console/runtime/server/status.get.js +5 -5
  144. package/dist/console/runtime/server/tickets.d.ts +1 -1
  145. package/dist/console/runtime/server/tickets.js +1 -1
  146. package/dist/console/runtime/server/usage.get.d.ts +2 -2
  147. package/dist/console/runtime/server/usage.get.js +7 -7
  148. package/dist/console/runtime/server/workspace-files.get.d.ts +1 -1
  149. package/dist/console/runtime/server/workspace-files.get.js +3 -3
  150. package/dist/console/server.d.ts +5 -5
  151. package/dist/console/server.js +6 -6
  152. package/dist/console/ui.js +121 -20
  153. package/dist/{console-route-COvNB_Xj.js → console-route-CBuqZ4wO.js} +1 -1
  154. package/dist/{database-J7M0B3ED.js → database-BdOBjPkS.js} +1 -1
  155. package/dist/{database-BVyhAxq-.d.ts → database-DyPVMjp_.d.ts} +1 -1
  156. package/dist/{definitions-BDRkT5-f.js → definitions-BW6SvmMM.js} +1 -0
  157. package/dist/{definitions-bepsXY5G.js → definitions-CNq_Shkh.js} +3 -3
  158. package/dist/{definitions-CxDT8D8Y.d.ts → definitions-DB4LbZ7T.d.ts} +2 -0
  159. package/dist/{definitions-CGTWTj67.d.ts → definitions-Dbgxfz3I.d.ts} +1 -1
  160. package/dist/development-W5EwONyL.d.ts +12 -0
  161. package/dist/{development-BzeSHZGH.js → development-zLxOp-AO.js} +12 -2
  162. package/dist/{diagnostics-D0DefmQj.js → diagnostics-9U_fYxMy.js} +30 -30
  163. package/dist/doctor.js +88 -107
  164. package/dist/{documents-C97WMaJZ.d.ts → documents-BASIRZ91.d.ts} +1 -1
  165. package/dist/{documents-RVHsQKFw.d.ts → documents-CboVhYFz.d.ts} +3 -3
  166. package/dist/{documents-DwPfR-fz.js → documents-CjJTCrY8.js} +3 -3
  167. package/dist/{documents-8US1nUgK.js → documents-qrHHqlNU.js} +1 -1
  168. package/dist/durability/operations.d.ts +1 -1
  169. package/dist/durability/operations.js +2 -2
  170. package/dist/{entries-D48wVEaS.js → entries-Bj-jPs_J.js} +1 -1
  171. package/dist/{error-diagnostics-C2rjmOlX.js → error-diagnostics-Bm3JKYjz.js} +19 -11
  172. package/dist/error-diagnostics.ts +19 -11
  173. package/dist/index.d.ts +15 -2
  174. package/dist/index.js +8 -4
  175. package/dist/internal/disabled-redis-driver.js +1 -1
  176. package/dist/internal/disabled-upstash-driver.js +1 -1
  177. package/dist/internal/test-loader.js +1 -1
  178. package/dist/internal/test-server.js +1 -1
  179. package/dist/{internal-BP_O70ic.d.ts → internal-CO4OqqaS.d.ts} +3 -3
  180. package/dist/{invocation-page-undo-BkUau8X7.js → invocation-page-undo-DIZ-s3xT.js} +2 -2
  181. package/dist/{invocations-CsucCJuq.js → invocations-CK_-G540.js} +3 -3
  182. package/dist/logs/memory.js +1 -1
  183. package/dist/logs/source.js +1 -1
  184. package/dist/logs.js +2 -2
  185. package/dist/{mcp-client-D0mUt18v.js → mcp-client-By4zk0vU.js} +6 -6
  186. package/dist/{media-wZMY6f2M.js → media-BHpQ-4jw.js} +4 -4
  187. package/dist/{media-library-CEo-Ye2B.d.ts → media-library-D9ThbXqs.d.ts} +1 -1
  188. package/dist/{media-library-BChf8XOd.js → media-library-NaOMBKWS.js} +2 -2
  189. package/dist/{memory-DhirB6SA.js → memory-DTmq-Z6x.js} +2 -2
  190. package/dist/{nuxt-server-imports-Lnaf5Fe-.js → nuxt-server-imports-DH60Z7LA.js} +3 -2
  191. package/dist/nuxt.d.ts +1 -1
  192. package/dist/nuxt.js +94 -67
  193. package/dist/{operation-contributions-DflAv5AC.js → operation-contributions-BdS0z3tx.js} +2 -2
  194. package/dist/{operation-contributions-fZyVo662.d.ts → operation-contributions-DpkO_iSU.d.ts} +1 -1
  195. package/dist/{operation-definition-Bn8V2hab.js → operation-definition-a5keEpCd.js} +6 -1
  196. package/dist/{operations-DX9EkHwb.d.ts → operations-B0689BG1.d.ts} +5 -0
  197. package/dist/operations-CAQmIxGK.js +2 -0
  198. package/dist/{operations-B6N-ja8x.js → operations-CWP9dF3i.js} +11 -11
  199. package/dist/{operations-Dj_cp-UK.js → operations-EOdyctDc.js} +1 -1
  200. package/dist/{optional-owners-Crm6kVS5.js → optional-owners-BNA2OX6z.js} +37 -23
  201. package/dist/{page-tool-BCRyx3pM.d.ts → page-tool-CRCK1RHV.d.ts} +1 -1
  202. package/dist/{plugins-DQ8pF-38.js → plugins-B-DpgDPB.js} +1459 -714
  203. package/dist/{plugins-5uDXr9Km.d.ts → plugins-BqAtIEX2.d.ts} +75 -56
  204. package/dist/{project-C2dnB9Kf.js → project-C4N_Zcjl.js} +3 -3
  205. package/dist/{project-5EN7JaXI.d.ts → project-CufkVP1u.d.ts} +2 -2
  206. package/dist/{project-DOeM0zg3.js → project-DlWTGB7h.js} +1 -1
  207. package/dist/{project-link-D_XQvBOC.d.ts → project-link-BuOzBH9f.d.ts} +1 -1
  208. package/dist/{project-link-Qi7nltHM.js → project-link-D-6UefhA.js} +2 -2
  209. package/dist/{request-yCybBeqT.js → request-DE8w_cSM.js} +8 -3
  210. package/dist/{request-BUYAlAJl.js → request-DbFfYmCu.js} +2 -2
  211. package/dist/{runtime-DM8Z6KLT.js → runtime-DQuHg7OO.js} +1 -1
  212. package/dist/{runtime-DG34DLXc.js → runtime-OsEDfbM9.js} +1 -1
  213. package/dist/runtime-feature-guard-B64MMW9I.js +140 -0
  214. package/dist/scan-module-D_3X08mj.js +2 -0
  215. package/dist/scan-module-Df58L_6T.js +311 -0
  216. package/dist/{secret-AZLhaNyr.js → secret-Dy5uqvq9.js} +1 -1
  217. package/dist/{sections-BriKrBgN.d.ts → sections-BogiCmtz.d.ts} +2 -2
  218. package/dist/{sections-ACHVTCWn.d.ts → sections-CyrXbbkG.d.ts} +4 -4
  219. package/dist/{sections-4xyBoiar.d.ts → sections-Do7X4Nwt.d.ts} +1 -2
  220. package/dist/{sections-D6AM5Gy5.js → sections-DumoLKQN.js} +2 -3
  221. package/dist/{sections-CUJyQA9d.js → sections-et20h8w3.js} +3 -3
  222. package/dist/{sections.get-1lHjyKCI.d.ts → sections.get-COiLcQ0P.d.ts} +2 -2
  223. package/dist/seo/runtime.js +1 -1
  224. package/dist/{server-DbjFYSeU.js → server-BRJE4t-W.js} +2 -2
  225. package/dist/{setup-DLZFzuLv.d.ts → setup-ZbA1by7W.d.ts} +4 -3
  226. package/dist/{site-access-Bhsty_v4.js → site-access-BbJUe5QI.js} +1 -1
  227. package/dist/{site-access-CyRtc0gZ.js → site-access-BmE8HGxs.js} +4 -4
  228. package/dist/{site-session-Jf21TVw8.js → site-session-odJq1dYa.js} +5 -5
  229. package/dist/skills/operations.d.ts +1 -1
  230. package/dist/skills/operations.js +2 -2
  231. package/dist/skills.d.ts +1 -1
  232. package/dist/{skills.get-CHQMzSD_.js → skills.get-Bl8cBe8u.js} +2 -2
  233. package/dist/{source-w9BHUwyO.js → source-D4wWtoHh.js} +1 -1
  234. package/dist/task/operations.d.ts +1 -1
  235. package/dist/task/operations.js +2 -2
  236. package/dist/test/register.js +1 -1
  237. package/dist/{ticket-RKQF6Wy9.js → ticket-Cudn1dq3.js} +1 -1
  238. package/dist/{tickets-CfJhT7d0.js → tickets-C_0Fhc00.js} +6 -6
  239. package/dist/{usage-Bc0YY_ka.js → usage-B4taNt4a.js} +1 -1
  240. package/dist/{usage-index-CMMT4cXQ.js → usage-index-BsGAFzyq.js} +1 -1
  241. package/dist/{version-DDRL_OYz.js → version-DNmSsk5r.js} +22 -19
  242. package/dist/{cli-DjoDGgT4.js → vite-stage-mmtwQIMA.js} +32 -2
  243. package/dist/{workspace-history-l47NPVSy.js → workspace-history-CraoERnc.js} +1 -1
  244. package/package.json +93 -93
  245. package/dist/cli-config--rAg6V-a.js +0 -2
  246. package/dist/decisions/vue.d.ts +0 -1
  247. package/dist/decisions/vue.js +0 -2
  248. package/dist/decisions.d.ts +0 -1
  249. package/dist/decisions.js +0 -2
  250. package/dist/development-DgaQ05jw.d.ts +0 -9
  251. package/dist/operations-H9q0QB2C.js +0 -2
  252. package/dist/runtime-feature-guard-rpZz1eMF.js +0 -55
  253. package/dist/scan-module-BTeOuZsp.js +0 -2
  254. package/dist/scan-module-DlHQ8a0X.js +0 -148
@@ -1,23 +1,23 @@
1
1
  import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
2
- import { a as isPackageInstalled, c as requireOptionalOwner, i as importOptionalOwner, n as forgetPackageChecks, o as isPackageInstalledInApp, r as hostFeaturePackages, s as optionalFeaturePackages, t as assertFeaturePackages, u as featureSupport } from "./optional-owners-Crm6kVS5.js";
2
+ import { a as installArguments, c as optionalFeaturePackages, d as featureSupport, f as features, i as importOptionalOwner, l as requireOptionalOwner, n as forgetPackageChecks, o as isPackageInstalled, r as hostFeaturePackages, s as isPackageInstalledInApp, t as assertFeaturePackages } from "./optional-owners-BNA2OX6z.js";
3
3
  import { n as isRecord$1, r as isRecordOrFunction, t as cloneRecord } from "./object-D8pRdprI.js";
4
- import { t as viteHubErrorDiagnostics } from "./error-diagnostics-C2rjmOlX.js";
4
+ import { t as viteHubErrorDiagnostics } from "./error-diagnostics-Bm3JKYjz.js";
5
5
  import { a as resolve$1, i as relative$1, n as summarizeDefinitions, r as dirname$1, t as redactInspectionText } from "./inspect-CDw7e0vK.js";
6
- import { n as removeViteHubDevServerFile, r as writeViteHubDevServerFile } from "./cli-DjoDGgT4.js";
7
- import { D as resolveConsoleSectionIds, b as isConsoleMcpClientEnabled, v as insertConsoleSection } from "./sections-D6AM5Gy5.js";
6
+ import { o as internalErrorDiagnostics } from "./operation-definition-a5keEpCd.js";
7
+ import { a as writeViteHubDevServerFile, i as removeViteHubDevServerFile, r as readViteHubDevServerFile, t as loadAllEnv } from "./vite-stage-mmtwQIMA.js";
8
+ import { D as resolveConsoleSectionIds, b as isConsoleMcpClientEnabled, v as insertConsoleSection } from "./sections-DumoLKQN.js";
8
9
  import { n as callOperationRpc, r as operationRpcPath } from "./operation-rpc-DI9txNxK.js";
9
- import { o as internalErrorDiagnostics } from "./operation-definition-Bn8V2hab.js";
10
10
  import { n as addViteHubDevPeerUpgradeSigner, o as consolePublicKeyPrefix, r as isViteHubLoopbackAddress, t as addViteHubDevPeerDevHandler } from "./dev-peer-am78OsHH.js";
11
- import { a as createOperationRegistry, i as collectOperationContributions, p as operationsOf } from "./operations-Dj_cp-UK.js";
12
- import { a as exports, n as assertNoRemovedViteHubOptions, t as readViteHubVersion } from "./version-DDRL_OYz.js";
13
- import { a as scanModule, c as walk } from "./scan-module-DlHQ8a0X.js";
11
+ import { a as createOperationRegistry, i as collectOperationContributions, p as operationsOf } from "./operations-EOdyctDc.js";
12
+ import { a as exports, n as assertNoRemovedViteHubOptions, t as readViteHubVersion } from "./version-DNmSsk5r.js";
13
+ import { _ as moduleLanguage, f as scanModule, v as walk } from "./scan-module-Df58L_6T.js";
14
14
  import { t as renderServedSkillsRegistryPlugin } from "./registry-zw6aE2N9.js";
15
15
  import { i as viteHubPageToolsAssets, n as viteHubBasePath, r as viteHubPageSessionPath } from "./page-tools-shared-D3fFoEV2.js";
16
- import { n as isViteHubSecretEqual } from "./secret-AZLhaNyr.js";
16
+ import { n as isViteHubSecretEqual } from "./secret-Dy5uqvq9.js";
17
17
  import { t as renderTaskRegistryPlugin } from "./registry-CDKLACCZ.js";
18
- import { builtinModules, createRequire } from "node:module";
19
- import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
20
- import { isDeepStrictEqual, promisify } from "node:util";
18
+ import { builtinModules, createRequire, findPackageJSON, isBuiltin } from "node:module";
19
+ import { basename, dirname, extname, isAbsolute, join, parse, posix, relative, resolve, sep } from "node:path";
20
+ import { inspect, isDeepStrictEqual, promisify } from "node:util";
21
21
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
22
22
  import { fileURLToPath, pathToFileURL } from "node:url";
23
23
  import { createConsoleReporter, formatDiagnostic } from "nostics";
@@ -27,7 +27,7 @@ import { tmpdir } from "node:os";
27
27
  import { isRuntimeDiagnostic } from "@vite-hub/runtime";
28
28
  import { describeServerEnv } from "@vite-hub/env/server";
29
29
  import { findContentEntry, hubSource, prepareSourceGeneration, toRuntimeModuleSpecifier } from "@vite-hub/source/vite";
30
- import { defaultServerConditions, mergeConfig, parseAst } from "vite";
30
+ import { defaultServerConditions, loadEnv, mergeConfig, parseAst } from "vite";
31
31
  import { env, hubEnv } from "@vite-hub/env/vite";
32
32
  import { hubBundle } from "@vite-hub/bundle/vite";
33
33
  import { createHash, randomUUID } from "node:crypto";
@@ -77,12 +77,41 @@ function workerdDependencyConfig(name, config, env) {
77
77
  } };
78
78
  }
79
79
  /**
80
- * Whether Node loads installed ViteHub packages directly in this environment, without Vite's SSR transform.
81
- * This is the Nitro environment of `vite dev`. Generated Nitro plugins give these packages the registries and the
82
- * `define` values that Vite gives to the code it transforms. Builds and other environments still inline the packages.
80
+ * Use one app's effective Nitro runner for both environment configuration and generated imports.
81
+ * `configureEnvironment` reads the runner after Nitro's `build:before` hooks and saves the decision for `load`.
83
82
  */
84
- function loadsViteHubPackagesNatively(name, env) {
85
- return env.command === "serve" && name === "nitro";
83
+ function createNativePackageLoading() {
84
+ let nitro;
85
+ let native = false;
86
+ return {
87
+ nitro: { setup(instance) {
88
+ nitro = instance;
89
+ } },
90
+ configureEnvironment(name, env) {
91
+ if (name !== "nitro") return false;
92
+ const runner = nitro?.options.devServer?.runner || process.env.NITRO_DEV_RUNNER || "node-worker";
93
+ native = env.command === "serve" && (runner === "node-worker" || runner === "node-process");
94
+ return native;
95
+ },
96
+ load(id, environmentName) {
97
+ if (environmentName === "nitro" && native) return loadNativePackageModule(id);
98
+ }
99
+ };
100
+ }
101
+ const nativePackageDistFile = /\/node_modules\/@vite-hub\/(?:agent|connections|runtime|workspace)\/dist\/.+\.js$/;
102
+ /**
103
+ * Generated code imports the runtime files of its owner by path. Vite gives Node only bare package names, so in the
104
+ * Nitro environment of `vite dev` it would inline a second copy of a package that Node already loaded, with its own
105
+ * registries. This returns a module that lets Node load the file instead, so the app and the generated code share one
106
+ * instance. Use it as the `load` hook result for the file. It returns nothing for other files and environments.
107
+ */
108
+ function loadNativePackageModule(id) {
109
+ const file = id.startsWith("file:") ? fileURLToPath(id) : id;
110
+ if (!nativePackageDistFile.test(file.replace(/\\/g, "/"))) return;
111
+ const url = JSON.stringify(pathToFileURL(realpathSync(file)).href);
112
+ const hasDefault = /\bexport default\b|\bas default\b/.test(readFileSync(file, "utf8"));
113
+ const native = JSON.stringify(`data:text/javascript,${encodeURIComponent(`export * from ${url}${hasDefault ? `\nexport { default } from ${url}` : ""}`)}`);
114
+ return `export * from ${native}\n${hasDefault ? `export { default } from ${native}\n` : ""}`;
86
115
  }
87
116
  const VITEHUB_NITRO_CONFIG_CONTEXT = "__vitehubNitroConfigContext";
88
117
  const VITEHUB_GENERATED_ROOT = "__vitehubGeneratedRoot";
@@ -206,6 +235,130 @@ function hasProjectRootFileMarker(root, markers) {
206
235
  }
207
236
  return false;
208
237
  }
238
+ const publishedDevServers = /* @__PURE__ */ new WeakSet();
239
+ /**
240
+ * Tell `vitehub` commands where this dev server listens: `.vitehub/dev-server.json` in the project root, removed when
241
+ * the server closes. A host that runs Vite in middleware mode has no listening server and writes nothing.
242
+ */
243
+ function publishViteHubDevServer(server) {
244
+ const http = server.httpServer;
245
+ if (!http || server.config.server.middlewareMode || publishedDevServers.has(http)) return;
246
+ publishedDevServers.add(http);
247
+ const root = resolve(server.config.root);
248
+ let publishedUrl;
249
+ const write = () => {
250
+ const address = http.address();
251
+ if (!address || typeof address === "string") return;
252
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
253
+ const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
254
+ try {
255
+ writeViteHubDevServerFile(root, {
256
+ root,
257
+ url
258
+ });
259
+ publishedUrl = url;
260
+ } catch {}
261
+ };
262
+ const remove = () => {
263
+ try {
264
+ if (publishedUrl && readViteHubDevServerFile(root)?.url === publishedUrl) removeViteHubDevServerFile(root);
265
+ } catch {}
266
+ };
267
+ if (http.listening) write();
268
+ else http.once("listening", write);
269
+ http.once("close", remove);
270
+ }
271
+ //#endregion
272
+ //#region src/hook-errors.ts
273
+ /** Vite prints a `config` or `configResolved` error with `util.inspect`, as an error of the config file itself. */
274
+ const inspectedByVite = /* @__PURE__ */ new Set(["config", "configResolved"]);
275
+ const printed = /* @__PURE__ */ new WeakSet();
276
+ /** A nostics diagnostic from any bundled copy of nostics: an error with a code and a fix or docs link. */
277
+ function isDiagnostic(error) {
278
+ return error instanceof Error && typeof Reflect.get(error, "code") === "string" && (typeof Reflect.get(error, "fix") === "string" || typeof Reflect.get(error, "docs") === "string");
279
+ }
280
+ /**
281
+ * `[CODE] message`, then the sources, the cause, the docs link and the fix, so the last line says what to do. nostics
282
+ * prints the fix before the docs link.
283
+ */
284
+ function formatViteHubDiagnostic(diagnostic, cause) {
285
+ const details = [
286
+ ...diagnostic.sources?.length ? [`sources: ${diagnostic.sources.join(", ")}`] : [],
287
+ ...cause ? [`cause: ${cause}`] : [],
288
+ ...diagnostic.docs ? [`see: ${diagnostic.docs}`] : [],
289
+ ...diagnostic.fix ? [`fix: ${diagnostic.fix}`] : []
290
+ ];
291
+ return [`[${diagnostic.name}] ${diagnostic.message}`, ...details.map((detail, index) => `${index < details.length - 1 ? "├▶" : "╰▶"} ${detail}`)].join("\n");
292
+ }
293
+ /** Prints to stderr, with the original error of a diagnostic after it when the diagnostic has a `cause`. */
294
+ const printDiagnostic = createConsoleReporter({
295
+ method: "error",
296
+ formatter: formatViteHubDiagnostic
297
+ });
298
+ /**
299
+ * Makes `util.inspect` show a diagnostic as its short text, with the fix on the last line. Vite prints an error of the
300
+ * config file, such as one that `vitehub()` throws, and of a `config` or `configResolved` hook with `util.inspect`.
301
+ * Without this, the terminal shows the stack and then every field, and the fix is in the middle of that dump.
302
+ * The error keeps its message, stack and fields.
303
+ */
304
+ function withShortInspect(error) {
305
+ if (isDiagnostic(error) && !Object.hasOwn(error, inspect.custom)) {
306
+ const cause = error.cause === void 0 ? void 0 : error.cause instanceof Error ? error.cause.message : String(error.cause);
307
+ Object.defineProperty(error, inspect.custom, { value: () => formatViteHubDiagnostic(error, cause) });
308
+ }
309
+ return error;
310
+ }
311
+ function throwShort(error) {
312
+ throw withShortInspect(error);
313
+ }
314
+ /**
315
+ * Prints a diagnostic once, with its fix, docs link and cause. Rolldown wraps a hook error in "Build failed with 1 error".
316
+ * It keeps `fix`, `docs` and `cause` on `errors[0]` and prints `cause`, but no bundler prints `fix`, so the fix of a
317
+ * ViteHub code would not reach the terminal. Rolldown also drops `url` (https://github.com/rolldown/rolldown/issues/11739).
318
+ * `vite dev` prints neither `cause` nor `url`.
319
+ */
320
+ function report(error) {
321
+ if (isDiagnostic(error) && !printed.has(error)) {
322
+ printed.add(error);
323
+ printDiagnostic(error, {});
324
+ }
325
+ throw error;
326
+ }
327
+ function wrap(handler, onError) {
328
+ return function(...args) {
329
+ let result;
330
+ try {
331
+ result = handler.apply(this, args);
332
+ } catch (error) {
333
+ onError(error);
334
+ }
335
+ return result instanceof Promise ? result.catch(onError) : result;
336
+ };
337
+ }
338
+ function wrapPlugin(plugin) {
339
+ for (const [name, hook] of Object.entries(plugin)) {
340
+ const onError = inspectedByVite.has(name) ? throwShort : report;
341
+ if (typeof hook === "function") Reflect.set(plugin, name, wrap(hook, onError));
342
+ else if (hook && typeof hook === "object" && "handler" in hook && typeof hook.handler === "function") hook.handler = wrap(hook.handler, onError);
343
+ }
344
+ }
345
+ /**
346
+ * Makes the build and dev hooks of the ViteHub plugins print the fix and docs link of a ViteHub error before Vite or
347
+ * Rolldown reports it, and makes Vite print an error of a `config` or `configResolved` hook short. The error itself does
348
+ * not change. The plugins keep their identity, so other plugins still find them.
349
+ */
350
+ function withPrintedDiagnostics(option) {
351
+ if (option instanceof Promise) {
352
+ option.then(withPrintedDiagnostics, () => {});
353
+ return option;
354
+ }
355
+ if (Array.isArray(option)) {
356
+ for (const item of option) withPrintedDiagnostics(item);
357
+ return option;
358
+ }
359
+ if (option && typeof option === "object" && "name" in option) wrapPlugin(option);
360
+ return option;
361
+ }
209
362
  //#endregion
210
363
  //#region ../internal/src/build/included-nitro-registry.ts
211
364
  const includedKey = Symbol.for("vitehub.included-nitro");
@@ -370,7 +523,7 @@ function optionalOwnerEntriesPlugin(options = {}) {
370
523
  if (hasWebhooksDirectory(projectRoot, serverDirs)) features.push("webhooks");
371
524
  if (content) features.push("content");
372
525
  if (content && importsCmsPreset(content)) features.push("cms", "database", "workspace");
373
- assertFeaturePackages([...new Set(features)]);
526
+ assertFeaturePackages([...new Set(features)], {}, false);
374
527
  }
375
528
  };
376
529
  }
@@ -392,7 +545,7 @@ const ownerFacadeFeatures = new Map(Object.entries({
392
545
  "channels": "channels",
393
546
  "connections": "connections",
394
547
  "console/ui": "console ui",
395
- "decisions": "decisions",
548
+ "choices": "choices",
396
549
  "device": "device",
397
550
  "email": "email",
398
551
  "forge": "forge",
@@ -720,6 +873,7 @@ function applyCacheStorage(nitro, cache) {
720
873
  * the file instead of the terminal.
721
874
  */
722
875
  const viteHubHintsFile = ".vitehub/hints.json";
876
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
723
877
  const runsKey = Symbol.for("vitehub.hints.runs");
724
878
  const shared = globalThis;
725
879
  const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
@@ -754,10 +908,13 @@ function write(run) {
754
908
  writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
755
909
  }
756
910
  /**
757
- * Reports a hint from a Vite plugin hook: prints it once with its fix and docs link, and adds it to
911
+ * Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
758
912
  * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
759
913
  */
760
914
  function reportViteHubHint(config, diagnostic) {
915
+ if (skipHints(config)) return;
916
+ const nuxt = config[VITEHUB_NUXT_HINTS];
917
+ if (typeof nuxt === "function") return nuxt(diagnostic);
761
918
  const run = runs.get(hintsFile(config)) ?? startRun(config);
762
919
  const hint = {
763
920
  code: diagnostic.code,
@@ -771,17 +928,20 @@ function reportViteHubHint(config, diagnostic) {
771
928
  run.keys.add(key);
772
929
  run.report.hints.push(hint);
773
930
  write(run);
774
- config.logger.warn(formatDiagnostic(diagnostic));
931
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
932
+ }
933
+ function skipHints(config) {
934
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
775
935
  }
776
936
  /**
777
937
  * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
778
938
  * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
779
- * package used without `vitehub()` starts its own run. The first call for a resolved config starts the run, and the
780
- * calls of other plugins of the same build keep it.
939
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
940
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
781
941
  */
782
- function startViteHubHints(config) {
783
- if (started.has(config)) return;
784
- started.add(config);
942
+ function startViteHubHints(config, owner = config) {
943
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
944
+ started.add(owner);
785
945
  write(startRun(config));
786
946
  }
787
947
  /** The plugin that `vitehub()` adds, so a build without any hint still writes an empty report. */
@@ -790,7 +950,7 @@ function viteHubHintsPlugin() {
790
950
  name: "vite-hub/hints",
791
951
  configResolved: {
792
952
  order: "pre",
793
- handler: startViteHubHints
953
+ handler: (config) => startViteHubHints(config)
794
954
  }
795
955
  };
796
956
  }
@@ -1249,6 +1409,7 @@ async function collapseWranglerConfigFile(serverDir, options = {}) {
1249
1409
  }
1250
1410
  //#endregion
1251
1411
  //#region ../internal/src/build/cloudflare.ts
1412
+ const defaultCloudflareCompatibilityDate = "2026-04-20";
1252
1413
  function createDefaultCloudflareOutputRoot(rootDir) {
1253
1414
  return resolve(rootDir, "dist", toSafeAppName(rootDir));
1254
1415
  }
@@ -1279,20 +1440,52 @@ function resolveViteHubBundleDefines(config) {
1279
1440
  return defines;
1280
1441
  }
1281
1442
  //#endregion
1282
- //#region ../internal/src/build/esbuild.ts
1283
- const viteRawNamespace = "vitehub-vite-raw";
1284
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
1443
+ //#region ../internal/src/build/rolldown.ts
1444
+ const viteRawPrefix = "\0vitehub-vite-raw:";
1445
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
1285
1446
  const markdownTemplateFileSuffix = ".template.md";
1286
1447
  const markdownTemplateModuleQuery = "markdown-template";
1287
1448
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
1288
1449
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
1450
+ const resolvingViteAlias = "vitehubResolvingAlias";
1289
1451
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
1452
+ /**
1453
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
1454
+ * Vite+, instead of installing a second bundler.
1455
+ */
1456
+ async function importRolldown() {
1457
+ let entry;
1458
+ try {
1459
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
1460
+ } catch (error) {
1461
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
1462
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
1463
+ }
1464
+ return await import(pathToFileURL(entry).href);
1465
+ }
1290
1466
  function normalizePathSeparators(path) {
1291
1467
  return path.replaceAll("\\", "/");
1292
1468
  }
1293
1469
  function escapeRegExp$3(value) {
1294
1470
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1295
1471
  }
1472
+ function isRelativeSpecifier(path) {
1473
+ return /^\.\.?[\\/]/.test(path);
1474
+ }
1475
+ function isBareSpecifier(id) {
1476
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
1477
+ }
1478
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
1479
+ function importerDir(importer, workingDir) {
1480
+ return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
1481
+ }
1482
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
1483
+ function importerFor(importer, workingDir) {
1484
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
1485
+ }
1486
+ function isFileResolution(resolved) {
1487
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
1488
+ }
1296
1489
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
1297
1490
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
1298
1491
  if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
@@ -1319,7 +1512,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
1319
1512
  }
1320
1513
  return candidates;
1321
1514
  }
1322
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
1515
+ /**
1516
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
1517
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
1518
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
1519
+ */
1520
+ function resolveFrom(context, specifier, request, workingDir, flag) {
1521
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
1522
+ custom: {
1523
+ ...request.custom,
1524
+ [flag]: true
1525
+ },
1526
+ isEntry: request.isEntry,
1527
+ kind: request.kind,
1528
+ skipSelf: true
1529
+ });
1530
+ }
1531
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
1323
1532
  const entries = Object.entries(aliases || {});
1324
1533
  if (!entries.length) return;
1325
1534
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -1339,186 +1548,175 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
1339
1548
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
1340
1549
  };
1341
1550
  }));
1551
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
1342
1552
  return {
1343
1553
  name: "vitehub-resolved-alias",
1344
- setup(build) {
1345
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
1346
- build.onResolve({ filter: /.*/ }, async (args) => {
1347
- if (args.pluginData?.[skipResolvedAlias]) return;
1348
- const resolveWithContext = (specifier) => build.resolve(specifier, {
1349
- importer: args.importer,
1350
- kind: args.kind,
1351
- namespace: args.namespace,
1352
- pluginData: {
1353
- ...args.pluginData,
1354
- [skipResolvedAlias]: true
1355
- },
1356
- resolveDir: args.resolveDir,
1357
- with: args.with
1358
- });
1359
- const aliases = await resolvedEntries;
1360
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
1361
- let matchedAlias = match?.specifier;
1362
- let matchedSpecifier = match ? args.path : void 0;
1363
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
1364
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
1365
- let canonicalSpecifier = normalizedSpecifier;
1366
- const canonicalizeSpecifier = async () => {
1367
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
1368
- return canonicalSpecifier;
1369
- };
1370
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
1371
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
1372
- await canonicalizeSpecifier();
1373
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
1374
- }
1375
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
1376
- const candidates = [];
1377
- for (const alias of aliases) {
1378
- if (isAbsolute(alias.specifier)) continue;
1379
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
1380
- const aliasSegments = packageAlias.split("/");
1381
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
1382
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
1383
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
1384
- const scopeMarker = `/node_modules/${packageAlias}/`;
1385
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
1386
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
1387
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
1388
- }
1389
- const packageMarker = `/node_modules/${packageName}/`;
1390
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
1391
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
1392
- const cacheKey = [
1393
- alias.specifier,
1394
- alias.prefix,
1395
- resolutionScope,
1396
- normalizedSpecifier,
1397
- args.importer,
1398
- args.resolveDir,
1399
- args.kind,
1400
- args.namespace,
1401
- JSON.stringify(args.with)
1402
- ].join("\0");
1403
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
1404
- if (!resolution) {
1405
- resolution = (async () => {
1406
- let resolvedAliasPath;
1407
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
1408
- else if (resolutionScope) {
1409
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
1410
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
1411
- if (!isRecord$1(parsedPackageJson)) return;
1412
- const packageJson = parsedPackageJson;
1413
- if (packageJson.exports === void 0 && !alias.prefix) {
1414
- const resolvedCandidate = await resolveWithContext(alias.specifier);
1415
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
1416
- canonical: alias.specifier,
1417
- normalized: alias.specifier,
1418
- publicSpecifier: alias.specifier
1419
- };
1420
- return;
1421
- }
1422
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
1423
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
1424
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
1425
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
1426
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
1427
- matchingPublicSpecifiers.add(publicSpecifier);
1428
- }
1429
- if (matchingPublicSpecifiers.size === 1) {
1430
- const publicSpecifier = [...matchingPublicSpecifiers][0];
1431
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
1432
- canonical: publicSpecifier,
1433
- normalized: publicSpecifier,
1434
- publicSpecifier
1435
- };
1436
- }
1554
+ async resolveId(source, importer, extra) {
1555
+ if (extra.custom?.[skipResolvedAlias]) return;
1556
+ const request = {
1557
+ custom: extra.custom,
1558
+ importer,
1559
+ isEntry: extra.isEntry,
1560
+ kind: extra.kind
1561
+ };
1562
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
1563
+ const resolveDir = importerDir(importer, workingDir);
1564
+ const aliases = await resolvedEntries;
1565
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
1566
+ let matchedAlias = match?.specifier;
1567
+ let matchedSpecifier = match ? source : void 0;
1568
+ const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
1569
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
1570
+ let canonicalSpecifier = normalizedSpecifier;
1571
+ const canonicalizeSpecifier = async () => {
1572
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
1573
+ return canonicalSpecifier;
1574
+ };
1575
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
1576
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
1577
+ await canonicalizeSpecifier();
1578
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
1579
+ }
1580
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
1581
+ const candidates = [];
1582
+ for (const alias of aliases) {
1583
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
1584
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
1585
+ const aliasSegments = packageAlias.split("/");
1586
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
1587
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
1588
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
1589
+ const scopeMarker = `/node_modules/${packageAlias}/`;
1590
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
1591
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
1592
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
1593
+ }
1594
+ const packageMarker = `/node_modules/${packageName}/`;
1595
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
1596
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
1597
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
1598
+ const cacheKey = [
1599
+ alias.specifier,
1600
+ alias.prefix,
1601
+ resolutionScope,
1602
+ normalizedSpecifier,
1603
+ importer,
1604
+ extra.kind,
1605
+ extra.isEntry
1606
+ ].join("\0");
1607
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
1608
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
1609
+ if (!resolution) {
1610
+ resolution = (async () => {
1611
+ let resolvedAliasPath;
1612
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
1613
+ else if (resolutionScope) {
1614
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
1615
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
1616
+ if (!isRecord$1(parsedPackageJson)) return;
1617
+ const packageJson = parsedPackageJson;
1618
+ if (packageJson.exports === void 0 && !alias.prefix) {
1619
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
1620
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
1621
+ canonical: alias.specifier,
1622
+ normalized: alias.specifier,
1623
+ publicSpecifier: alias.specifier
1624
+ };
1437
1625
  return;
1438
- } else {
1439
- const resolvedAlias = await resolveWithContext(alias.specifier);
1440
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
1441
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
1442
1626
  }
1443
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
1444
- return {
1445
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
1446
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
1447
- };
1448
- })();
1449
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
1450
- }
1451
- candidates.push({
1452
- alias,
1453
- resolution
1454
- });
1627
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
1628
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
1629
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
1630
+ if (!isFileResolution(resolvedCandidate)) continue;
1631
+ if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
1632
+ matchingPublicSpecifiers.add(publicSpecifier);
1633
+ }
1634
+ if (matchingPublicSpecifiers.size === 1) {
1635
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
1636
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
1637
+ canonical: publicSpecifier,
1638
+ normalized: publicSpecifier,
1639
+ publicSpecifier
1640
+ };
1641
+ }
1642
+ return;
1643
+ } else {
1644
+ const resolvedAlias = await resolveWithContext(alias.specifier);
1645
+ if (!isFileResolution(resolvedAlias)) return;
1646
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
1647
+ }
1648
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
1649
+ return {
1650
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
1651
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
1652
+ };
1653
+ })();
1654
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
1455
1655
  }
1456
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
1457
- for (const { alias, resolution } of candidates) {
1458
- const paths = await resolution;
1459
- if (!paths) continue;
1460
- if (paths.publicSpecifier) {
1461
- match = alias;
1462
- matchedAlias = alias.specifier;
1463
- matchedSpecifier = paths.publicSpecifier;
1464
- break;
1465
- }
1466
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
1467
- let canonicalMatch = false;
1468
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
1469
- await canonicalizeSpecifier();
1470
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
1471
- }
1472
- if (normalizedMatch || canonicalMatch) {
1473
- match = alias;
1474
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
1475
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
1476
- break;
1477
- }
1656
+ candidates.push({
1657
+ alias,
1658
+ resolution
1659
+ });
1660
+ }
1661
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
1662
+ for (const { alias, resolution } of candidates) {
1663
+ const paths = await resolution;
1664
+ if (!paths) continue;
1665
+ if (paths.publicSpecifier) {
1666
+ match = alias;
1667
+ matchedAlias = alias.specifier;
1668
+ matchedSpecifier = paths.publicSpecifier;
1669
+ break;
1670
+ }
1671
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
1672
+ let canonicalMatch = false;
1673
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
1674
+ await canonicalizeSpecifier();
1675
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
1676
+ }
1677
+ if (normalizedMatch || canonicalMatch) {
1678
+ match = alias;
1679
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
1680
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
1681
+ break;
1478
1682
  }
1479
1683
  }
1480
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
1481
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
1482
- if (!match) return;
1483
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
1484
- if (!target) return;
1485
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
1486
- });
1684
+ }
1685
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
1686
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
1687
+ if (!match) return;
1688
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
1689
+ if (!target) return;
1690
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
1691
+ const resolved = await resolveWithContext(resolvedTarget);
1692
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
1693
+ return resolved;
1487
1694
  }
1488
1695
  };
1489
1696
  }
1490
- function createViteAliasPlugin(aliases) {
1697
+ function createViteAliasPlugin(aliases, workingDir) {
1491
1698
  if (!Array.isArray(aliases)) return;
1492
- const resolvingAlias = "vitehubResolvingAlias";
1493
1699
  return {
1494
1700
  name: "vitehub-vite-alias",
1495
- setup(build) {
1496
- build.onResolve({ filter: /.*/ }, async (args) => {
1497
- if (args.pluginData?.[resolvingAlias]) return;
1498
- const alias = aliases.find(({ find }) => {
1499
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
1500
- find.lastIndex = 0;
1501
- return find.test(args.path);
1502
- });
1503
- if (!alias) return;
1504
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
1505
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
1506
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
1507
- const result = await build.resolve(replacement, {
1508
- importer: args.importer,
1509
- kind: args.kind,
1510
- namespace: args.namespace,
1511
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
1512
- resolveDir: args.resolveDir,
1513
- with: args.with
1514
- });
1515
- const pluginData = Object.assign({}, result.pluginData);
1516
- Reflect.deleteProperty(pluginData, resolvingAlias);
1517
- return {
1518
- ...result,
1519
- pluginData
1520
- };
1701
+ async resolveId(source, importer, extra) {
1702
+ if (extra.custom?.[resolvingViteAlias]) return;
1703
+ const alias = aliases.find(({ find }) => {
1704
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
1705
+ find.lastIndex = 0;
1706
+ return find.test(source);
1521
1707
  });
1708
+ if (!alias) return;
1709
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
1710
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
1711
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
1712
+ const resolved = await resolveFrom(this, replacement, {
1713
+ custom: extra.custom,
1714
+ importer,
1715
+ isEntry: extra.isEntry,
1716
+ kind: extra.kind
1717
+ }, workingDir, resolvingViteAlias);
1718
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
1719
+ return resolved;
1522
1720
  }
1523
1721
  };
1524
1722
  }
@@ -1557,174 +1755,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
1557
1755
  return resolve(rootDir, rootRelativePath);
1558
1756
  }
1559
1757
  }
1560
- function createViteRawPlugin(rootDir, frameworkRuntime) {
1758
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
1561
1759
  return {
1562
1760
  name: "vitehub-vite-raw",
1563
- setup(build) {
1564
- build.onResolve({
1565
- filter: /^@vite-hub\/markdown-template$/,
1566
- namespace: viteMarkdownTemplateNamespace
1567
- }, async (args) => {
1568
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
1569
- return build.resolve("vite-hub/markdown-template", {
1570
- importer: args.importer,
1571
- kind: args.kind,
1572
- resolveDir: args.resolveDir
1761
+ async resolveId(source, importer, extra) {
1762
+ if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
1763
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
1764
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
1765
+ custom: extra.custom,
1766
+ kind: extra.kind
1573
1767
  });
1574
- });
1575
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
1576
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
1577
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
1578
- const raw = hasViteRawQuery(args.path);
1579
- if (!markdownTemplate && !raw) return;
1580
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
1581
- let pluginData = args.pluginData;
1582
- if (markdownTemplate) pluginData = {
1583
- ...args.pluginData,
1584
- [skipMarkdownTemplateResolve]: true
1585
- };
1586
- const resolved = await build.resolve(specifier, {
1587
- importer: args.importer,
1588
- kind: args.kind,
1589
- namespace: args.namespace,
1590
- pluginData,
1591
- resolveDir: args.resolveDir,
1592
- with: args.with
1593
- });
1594
- if (resolved.errors.length) return {
1595
- errors: resolved.errors,
1596
- warnings: resolved.warnings
1597
- };
1598
- if (resolved.external) return {
1599
- external: true,
1600
- namespace: resolved.namespace,
1601
- path: resolved.path,
1602
- pluginData: resolved.pluginData,
1603
- sideEffects: resolved.sideEffects,
1604
- suffix: resolved.suffix,
1605
- warnings: resolved.warnings
1606
- };
1607
- if (resolved.namespace !== "file") return {
1608
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
1609
- warnings: resolved.warnings
1610
- };
1611
- return {
1612
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
1613
- path: resolved.path,
1614
- pluginData: resolved.pluginData,
1615
- sideEffects: resolved.sideEffects,
1616
- suffix: resolved.suffix,
1617
- warnings: resolved.warnings
1618
- };
1619
- });
1620
- build.onLoad({
1621
- filter: /.*/,
1622
- namespace: viteRawNamespace
1623
- }, async (args) => ({
1624
- contents: await readFile(args.path),
1625
- loader: "text"
1626
- }));
1627
- build.onLoad({
1628
- filter: /.*/,
1629
- namespace: viteMarkdownTemplateNamespace
1630
- }, async (args) => ({
1631
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
1632
- loader: "js",
1633
- resolveDir: dirname(args.path)
1634
- }));
1768
+ }
1769
+ if (extra.custom?.[skipMarkdownTemplateResolve]) return;
1770
+ const markdownTemplate = parseMarkdownTemplateRequest(source);
1771
+ const raw = hasViteRawQuery(source);
1772
+ if (!markdownTemplate && !raw) return;
1773
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
1774
+ const resolved = await resolveFrom(this, specifier, {
1775
+ custom: extra.custom,
1776
+ importer,
1777
+ isEntry: extra.isEntry,
1778
+ kind: extra.kind
1779
+ }, workingDir, skipMarkdownTemplateResolve);
1780
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
1781
+ if (resolved.external) return {
1782
+ id: resolved.id,
1783
+ external: resolved.external
1784
+ };
1785
+ const resolvedId = resolved.id;
1786
+ if (!isFileResolution(resolved)) this.error(markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this raw import in a caller plugin.`);
1787
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
1788
+ },
1789
+ async load(id) {
1790
+ if (id.startsWith(viteRawPrefix)) return {
1791
+ code: await readFile(id.slice(18), "utf8"),
1792
+ moduleType: "text"
1793
+ };
1794
+ if (id.startsWith(markdownTemplatePrefix)) return {
1795
+ code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
1796
+ moduleType: "js"
1797
+ };
1635
1798
  }
1636
1799
  };
1637
1800
  }
1638
1801
  function createFileUrlPlugin() {
1639
1802
  return {
1640
1803
  name: "vitehub-file-url",
1641
- setup(build) {
1642
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
1804
+ resolveId(source) {
1805
+ if (source.startsWith("file:")) return fileURLToPath(source);
1643
1806
  }
1644
1807
  };
1645
1808
  }
1646
1809
  /**
1647
1810
  * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
1648
1811
  * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
1812
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
1649
1813
  */
1650
- function createWasmModulePlugin(outdir) {
1814
+ function createWasmModulePlugin(outdir, workingDir, copy) {
1651
1815
  return {
1652
1816
  name: "vitehub-wasm-module",
1653
- setup(build) {
1654
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
1655
- const resolved = await build.resolve(args.path.slice(0, -7), {
1656
- importer: args.importer,
1657
- kind: args.kind,
1658
- resolveDir: args.resolveDir
1659
- });
1660
- if (resolved.errors.length) return { errors: resolved.errors };
1661
- const bytes = await readFile(resolved.path);
1662
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
1663
- await mkdir(outdir, { recursive: true });
1664
- await copyFile(resolved.path, join(outdir, name));
1665
- return {
1666
- external: true,
1667
- path: `./${name}`
1668
- };
1817
+ async resolveId(source, importer, extra) {
1818
+ if (!source.endsWith(".wasm?module")) return;
1819
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
1820
+ custom: extra.custom,
1821
+ kind: extra.kind
1669
1822
  });
1823
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
1824
+ if (!copy) return resolved.id;
1825
+ const bytes = await readFile(resolved.id);
1826
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
1827
+ await mkdir(outdir, { recursive: true });
1828
+ await copyFile(resolved.id, join(outdir, name));
1829
+ return {
1830
+ id: `./${name}`,
1831
+ external: true
1832
+ };
1833
+ }
1834
+ };
1835
+ }
1836
+ /**
1837
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
1838
+ */
1839
+ function createExternalPackagesPlugin() {
1840
+ return {
1841
+ name: "vitehub-external-packages",
1842
+ async resolveId(source, importer, extra) {
1843
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
1844
+ id: source,
1845
+ external: true
1846
+ };
1847
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
1848
+ custom: extra.custom,
1849
+ kind: extra.kind
1850
+ }) ?? {
1851
+ id: source,
1852
+ external: true
1853
+ };
1854
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
1855
+ id: source,
1856
+ external: true
1857
+ };
1858
+ }
1859
+ };
1860
+ }
1861
+ function hasImportRejectionHandler(importNode, parents) {
1862
+ let expression = importNode;
1863
+ let parent = parents.get(expression);
1864
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
1865
+ const call = parents.get(parent);
1866
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
1867
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
1868
+ const handler = call.arguments[method === "then" ? 1 : 0];
1869
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
1870
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
1871
+ }
1872
+ if (method !== "then" && method !== "finally") break;
1873
+ expression = call;
1874
+ parent = parents.get(expression);
1875
+ }
1876
+ if (parent?.type !== "AwaitExpression") return false;
1877
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
1878
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
1879
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
1880
+ child = ancestor;
1881
+ }
1882
+ return false;
1883
+ }
1884
+ function createOptionalImportPlugin() {
1885
+ const prefix = "\0vitehub-optional-import:";
1886
+ return {
1887
+ name: "vitehub-optional-import",
1888
+ resolveId(source) {
1889
+ if (source.startsWith(prefix)) return {
1890
+ id: source.slice(25),
1891
+ external: "absolute"
1892
+ };
1893
+ },
1894
+ transform: {
1895
+ order: "post",
1896
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
1897
+ async handler(code, id) {
1898
+ const { parseSync } = await import("vite");
1899
+ const module = parseSync(id, code, {
1900
+ lang: moduleLanguage(id),
1901
+ preserveParens: false,
1902
+ sourceType: "module"
1903
+ });
1904
+ if (module.errors.length) return;
1905
+ const parents = /* @__PURE__ */ new WeakMap();
1906
+ const handled = [];
1907
+ walk(module.program, (node, parent) => {
1908
+ if (parent) parents.set(node, parent);
1909
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
1910
+ if (hasImportRejectionHandler(node, parents)) handled.push({
1911
+ source: node.source.value,
1912
+ start: node.source.start,
1913
+ end: node.source.end
1914
+ });
1915
+ });
1916
+ if (!handled.length) return;
1917
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
1918
+ for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
1919
+ return code;
1920
+ }
1670
1921
  }
1671
1922
  };
1672
1923
  }
1924
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
1925
+ function createExternalMatcher(patterns) {
1926
+ if (!patterns?.length) return;
1927
+ const matchers = patterns.map((pattern) => {
1928
+ if (pattern.includes("*")) {
1929
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$3).join(".*")}$`);
1930
+ return (id) => expression.test(id);
1931
+ }
1932
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
1933
+ });
1934
+ return (id) => matchers.some((matches) => matches(id));
1935
+ }
1673
1936
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
1674
- const { build: bundle } = await import("esbuild");
1937
+ const { rolldown } = await importRolldown();
1675
1938
  options.signal?.throwIfAborted();
1676
1939
  const format = options.format || "esm";
1677
1940
  const platform = options.platform || "neutral";
1678
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
1941
+ const workingDir = options.workingDir ?? process.cwd();
1679
1942
  const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
1680
1943
  const plugins = [];
1681
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
1944
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
1945
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
1682
1946
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
1683
1947
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
1948
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
1684
1949
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
1685
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
1686
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
1687
- const result = await bundle({
1688
- absWorkingDir: options.workingDir,
1689
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
1690
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
1691
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
1692
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
1693
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
1694
- "}"
1695
- ] : []].filter(Boolean).join("\n") } : void 0,
1696
- bundle: true,
1697
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
1698
- define: options.define,
1699
- entryPoints: [entryFile],
1700
- external: options.external,
1701
- format,
1702
- keepNames: options.minifySyntax || options.minifyIdentifiers,
1703
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
1704
- logLevel: "silent",
1705
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
1706
- resolveExtensions: options.extensions,
1707
- minifyIdentifiers: options.minifyIdentifiers,
1708
- minifySyntax: options.minifySyntax,
1709
- minifyWhitespace: options.minifyWhitespace,
1710
- outfile,
1711
- packages: options.packages,
1950
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
1951
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
1952
+ plugins.push(createOptionalImportPlugin());
1953
+ const isExternal = createExternalMatcher(options.external);
1954
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
1955
+ compress: options.minifySyntax ?? false,
1956
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
1957
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
1958
+ } : false;
1959
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
1960
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
1961
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
1962
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
1963
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
1964
+ "}"
1965
+ ] : []].filter(Boolean).join("\n");
1966
+ const bundle = await rolldown({
1967
+ cwd: workingDir,
1968
+ external: isExternal ? (id) => isExternal(id) : void 0,
1969
+ input: entryFile,
1970
+ onLog(level, log) {
1971
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
1972
+ },
1973
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
1712
1974
  platform,
1713
- preserveSymlinks: options.preserveSymlinks,
1714
1975
  plugins,
1715
- sourcemap: false,
1716
- target: "es2022",
1717
- write: options.signal ? false : true
1976
+ resolve: {
1977
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
1978
+ extensions: options.extensions,
1979
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
1980
+ symlinks: !options.preserveSymlinks
1981
+ },
1982
+ transform: {
1983
+ define: options.define,
1984
+ target: "es2022"
1985
+ },
1986
+ tsconfig: options.tsconfig ?? true
1718
1987
  });
1719
- options.signal?.throwIfAborted();
1720
- if (options.signal) {
1721
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
1722
- await mkdir(dirname(output.path), { recursive: true });
1723
- options.signal.throwIfAborted();
1724
- await writeFile(output.path, output.contents, { signal: options.signal });
1725
- }));
1726
- options.signal.throwIfAborted();
1988
+ let output;
1989
+ try {
1990
+ output = (await bundle.generate({
1991
+ banner: banner || void 0,
1992
+ codeSplitting: false,
1993
+ format,
1994
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
1995
+ minify,
1996
+ polyfillRequire: !(format === "esm" && platform === "node"),
1997
+ sourcemap: false
1998
+ })).output;
1999
+ } finally {
2000
+ await bundle.close();
1727
2001
  }
2002
+ options.signal?.throwIfAborted();
2003
+ const chunk = output.find((file) => file.type === "chunk");
2004
+ await mkdir(dirname(outfile), { recursive: true });
2005
+ await writeFile(outfile, chunk.code, { signal: options.signal });
2006
+ options.signal?.throwIfAborted();
1728
2007
  }
1729
2008
  //#endregion
1730
2009
  //#region ../internal/src/build/paths.ts
@@ -1922,7 +2201,7 @@ function createNodeFunctionConfig(extra = {}) {
1922
2201
  return {
1923
2202
  handler: "index.mjs",
1924
2203
  launcherType: "Nodejs",
1925
- runtime: "nodejs22.x",
2204
+ runtime: "nodejs24.x",
1926
2205
  shouldAddHelpers: false,
1927
2206
  supportsResponseStreaming: true,
1928
2207
  ...extra
@@ -2446,10 +2725,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2446
2725
  assertNetlifyFunctionName(functionName);
2447
2726
  return resolve(functionsRoot, `${functionName}.mjs`);
2448
2727
  }
2728
+ async function declaresTopLevelBinding(code, name) {
2729
+ const { parseSync } = await import("vite");
2730
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
2731
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
2732
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
2733
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
2734
+ });
2735
+ }
2449
2736
  async function appendNetlifyFunctionConfig(outfile, config) {
2450
2737
  if (!config) return;
2451
2738
  const bundled = await readFile(outfile, "utf8");
2452
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2739
+ const literal = stringifyProviderOutputConfig(config);
2740
+ let exported = `export const config = ${literal}`;
2741
+ if (await declaresTopLevelBinding(bundled, "config")) {
2742
+ const baseName = "vitehubNetlifyFunctionConfig";
2743
+ let name = baseName;
2744
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
2745
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
2746
+ }
2747
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
2453
2748
  }
2454
2749
  async function writeCloudflareDeploymentOutput(options, signal) {
2455
2750
  signal?.throwIfAborted();
@@ -3531,6 +3826,57 @@ function isPackageResolutionMiss(error) {
3531
3826
  return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
3532
3827
  }
3533
3828
  //#endregion
3829
+ //#region ../../node_modules/.pnpm/resolve-pkg-maps@1.0.0/node_modules/resolve-pkg-maps/dist/index.mjs
3830
+ const A = (r) => r !== null && typeof r == "object";
3831
+ const a = (r, t) => Object.assign(/* @__PURE__ */ new Error(`[${r}]: ${t}`), { code: r });
3832
+ const _ = "ERR_INVALID_PACKAGE_CONFIG";
3833
+ const E = "ERR_INVALID_PACKAGE_TARGET";
3834
+ const P = "ERR_PACKAGE_IMPORT_NOT_DEFINED";
3835
+ const R = /^\d+$/;
3836
+ const O = /^(\.{1,2}|node_modules)$/i;
3837
+ const w = /\/|\\/;
3838
+ var h = ((r) => (r.Export = "exports", r.Import = "imports", r))(h || {});
3839
+ const f = (r, t, e, o, c) => {
3840
+ if (t == null) return [];
3841
+ if (typeof t == "string") {
3842
+ const [n, ...i] = t.split(w);
3843
+ if (n === ".." || i.some((l) => O.test(l))) throw a(E, `Invalid "${r}" target "${t}" defined in the package config`);
3844
+ return [c ? t.replace(/\*/g, c) : t];
3845
+ }
3846
+ if (Array.isArray(t)) return t.flatMap((n) => f(r, n, e, o, c));
3847
+ if (A(t)) {
3848
+ for (const n of Object.keys(t)) {
3849
+ if (R.test(n)) throw a(_, "Cannot contain numeric property keys");
3850
+ if (n === "default" || o.includes(n)) return f(r, t[n], e, o, c);
3851
+ }
3852
+ return [];
3853
+ }
3854
+ throw a(E, `Invalid "${r}" target "${t}"`);
3855
+ };
3856
+ const s = "*";
3857
+ const m = (r, t) => {
3858
+ const e = r.indexOf(s), o = t.indexOf(s);
3859
+ return e === o ? t.length > r.length : o > e;
3860
+ };
3861
+ function d(r, t) {
3862
+ if (!t.includes(s) && r.hasOwnProperty(t)) return [t];
3863
+ let e, o;
3864
+ for (const c of Object.keys(r)) if (c.includes(s)) {
3865
+ const [n, i, l] = c.split(s);
3866
+ if (l === void 0 && t.startsWith(n) && t.endsWith(i)) {
3867
+ const g = t.slice(n.length, -i.length || void 0);
3868
+ g && (!e || m(e, c)) && (e = c, o = g);
3869
+ }
3870
+ }
3871
+ return [e, o];
3872
+ }
3873
+ const T = (r, t, e) => {
3874
+ if (!r) throw new Error("\"imports\" is required");
3875
+ const [o, c] = d(r, t), n = f(h.Import, r[o], t, e, c);
3876
+ if (n.length === 0) throw a(P, `Package import specifier "${t}" is not defined in package`);
3877
+ return n;
3878
+ };
3879
+ //#endregion
3534
3880
  //#region ../internal/src/build/deno-deploy-runner.injected.ts
3535
3881
  function denoDeployRunnerSource(deploymentName, entrypoint) {
3536
3882
  return `import { spawn } from "node:child_process"
@@ -4003,57 +4349,48 @@ function maskInertImportText(module, packageCallNames = /* @__PURE__ */ new Set(
4003
4349
  });
4004
4350
  return output.join("");
4005
4351
  }
4006
- function packageImportPlugin() {
4007
- const resolvingPackageImport = "vitehubResolvingPackageImport";
4008
- return {
4009
- name: "vitehub-package-imports",
4010
- setup(build) {
4011
- build.onResolve({ filter: /^#/ }, async (args) => {
4012
- if (args.pluginData?.[resolvingPackageImport]) return;
4013
- const result = await build.resolve(args.path, {
4014
- importer: args.importer,
4015
- kind: args.kind,
4016
- namespace: args.namespace,
4017
- pluginData: {
4018
- ...args.pluginData,
4019
- [resolvingPackageImport]: true
4020
- },
4021
- resolveDir: args.resolveDir,
4022
- with: args.with
4023
- });
4024
- const pluginData = Object.assign({}, result.pluginData);
4025
- Reflect.deleteProperty(pluginData, resolvingPackageImport);
4026
- return {
4027
- ...result,
4028
- pluginData
4029
- };
4030
- });
4031
- }
4032
- };
4033
- }
4034
- function runtimePackageResolutionPlugin(rootDir, aliases, packageJsonPaths, packages) {
4352
+ function runtimePackageResolutionPlugin(rootDir, aliases, conditions, packageJsonPaths, packages) {
4035
4353
  return {
4036
4354
  name: "vitehub-deno-runtime-packages",
4037
- setup(build) {
4038
- build.onResolve({ filter: /.*/ }, async (args) => {
4039
- const name = packageNameFromSpecifier(args.path);
4040
- if (!name || aliases?.some((alias) => {
4041
- if (!(alias.find instanceof RegExp)) return args.path === alias.find || args.path.startsWith(`${alias.find}/`);
4042
- alias.find.lastIndex = 0;
4043
- const matches = alias.find.test(args.path);
4044
- alias.find.lastIndex = 0;
4045
- return matches;
4046
- })) return;
4047
- const fromDir = args.resolveDir || (isAbsolute(args.importer) ? dirname(args.importer) : rootDir);
4048
- const resolver = createRequire(isAbsolute(args.importer) ? args.importer : join(fromDir, "package.json"));
4049
- const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
4050
- const resolvedPackageJsonPath = packageJsonPath && await realpath(packageJsonPath);
4051
- if (resolvedPackageJsonPath) recordRuntimePackageResolution(packageJsonPaths, name, resolvedPackageJsonPath);
4052
- addRuntimePackage(packages, {
4053
- name,
4054
- optional: args.kind !== "import-statement",
4055
- packageJsonPath: resolvedPackageJsonPath
4355
+ async resolveId(source, importer, extra) {
4356
+ if (aliases?.some((alias) => {
4357
+ if (!(alias.find instanceof RegExp)) return source === alias.find || source.startsWith(`${alias.find}/`);
4358
+ alias.find.lastIndex = 0;
4359
+ const matches = alias.find.test(source);
4360
+ alias.find.lastIndex = 0;
4361
+ return matches;
4362
+ })) return;
4363
+ if (source.startsWith("#") && importer && isAbsolute(importer)) {
4364
+ const packageJsonPath = findPackageJSON(".", pathToFileURL(importer));
4365
+ if (!packageJsonPath || basename(packageJsonPath) !== "package.json") return;
4366
+ const manifest = JSON.parse(await readFile(packageJsonPath, "utf8"));
4367
+ if (!isRecord$1(manifest) || !isRecord$1(manifest.imports)) return;
4368
+ let target;
4369
+ try {
4370
+ const kind = extra.kind === "require-call" ? "require" : "import";
4371
+ target = T(manifest.imports, source, [kind, ...conditions ?? []])[0];
4372
+ } catch (error) {
4373
+ if (error instanceof Error && "code" in error && error.code === "ERR_PACKAGE_IMPORT_NOT_DEFINED") return;
4374
+ throw error;
4375
+ }
4376
+ if (!target || !packageNameFromSpecifier(target) && !/^(npm|jsr):/.test(target)) return;
4377
+ return this.resolve(target, importer, {
4378
+ custom: extra.custom,
4379
+ kind: extra.kind,
4380
+ skipSelf: false
4056
4381
  });
4382
+ }
4383
+ const name = packageNameFromSpecifier(source);
4384
+ if (!name) return;
4385
+ const fromDir = importer && isAbsolute(importer) ? dirname(importer) : rootDir;
4386
+ const resolver = createRequire(importer && isAbsolute(importer) ? importer : join(fromDir, "package.json"));
4387
+ const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
4388
+ const resolvedPackageJsonPath = packageJsonPath && await realpath(packageJsonPath);
4389
+ if (resolvedPackageJsonPath) recordRuntimePackageResolution(packageJsonPaths, name, resolvedPackageJsonPath);
4390
+ addRuntimePackage(packages, {
4391
+ name,
4392
+ optional: extra.kind !== "import-statement",
4393
+ packageJsonPath: resolvedPackageJsonPath
4057
4394
  });
4058
4395
  }
4059
4396
  };
@@ -4501,7 +4838,7 @@ async function finalizeStagedDenoDeploymentOutput(options) {
4501
4838
  platform: "neutral",
4502
4839
  preserveSymlinks: options.preserveSymlinks,
4503
4840
  mainFields: options.mainFields,
4504
- plugins: [packageImportPlugin(), runtimePackageResolutionPlugin(options.rootDir, options.alias, resolvedPackageJsonPaths, runtimePackages)],
4841
+ plugins: [runtimePackageResolutionPlugin(options.rootDir, options.alias, options.conditions, resolvedPackageJsonPaths, runtimePackages)],
4505
4842
  rootDir: options.rootDir,
4506
4843
  workingDir: options.rootDir
4507
4844
  });
@@ -4533,7 +4870,7 @@ async function finalizeStagedDenoDeploymentOutput(options) {
4533
4870
  platform: "neutral",
4534
4871
  preserveSymlinks: options.preserveSymlinks,
4535
4872
  mainFields: options.mainFields,
4536
- plugins: [packageImportPlugin(), runtimePackageResolutionPlugin(options.rootDir, options.alias, resolvedPackageJsonPaths, runtimePackages)],
4873
+ plugins: [runtimePackageResolutionPlugin(options.rootDir, options.alias, options.conditions, resolvedPackageJsonPaths, runtimePackages)],
4537
4874
  rootDir: options.rootDir,
4538
4875
  workingDir: options.rootDir
4539
4876
  });
@@ -4654,130 +4991,6 @@ function nitroCacheBypass() {
4654
4991
  };
4655
4992
  }
4656
4993
  //#endregion
4657
- //#region ../internal/src/definition-catalog.ts
4658
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
4659
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
4660
- const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
4661
- const ignoredDirs = /* @__PURE__ */ new Set([
4662
- "node_modules",
4663
- "dist",
4664
- ".output",
4665
- ".nuxt",
4666
- ".vercel",
4667
- ".git",
4668
- ".vitehub"
4669
- ]);
4670
- function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
4671
- return {
4672
- ...options,
4673
- kind: "directory",
4674
- scanDirs,
4675
- source,
4676
- subdir
4677
- };
4678
- }
4679
- function readDirEntries(root) {
4680
- try {
4681
- return readdirSync(root, { withFileTypes: true });
4682
- } catch (error) {
4683
- if (error.code === "ENOENT") return [];
4684
- throw error;
4685
- }
4686
- }
4687
- function isGitRepositoryDirectory(directory) {
4688
- return existsSync(resolve$1(directory, ".git"));
4689
- }
4690
- function listMatchingFiles(root, predicate, options = {}) {
4691
- const files = [];
4692
- for (const entry of readDirEntries(root)) {
4693
- const absolute = resolve$1(root, entry.name);
4694
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
4695
- if (isGitRepositoryDirectory(absolute)) continue;
4696
- if (entry.name.startsWith(".")) continue;
4697
- if (ignoredDirs.has(entry.name)) continue;
4698
- files.push(...listMatchingFiles(absolute, predicate, options));
4699
- continue;
4700
- }
4701
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
4702
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
4703
- }
4704
- return files.sort();
4705
- }
4706
- /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
4707
- function isDefinitionSourceFile(name) {
4708
- return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
4709
- }
4710
- function listSourceFiles(root, options = {}) {
4711
- return listMatchingFiles(root, isDefinitionSourceFile, options);
4712
- }
4713
- function normalizePathDefinitionName(rootDir, file) {
4714
- return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
4715
- }
4716
- function sortDefinitions(definitions) {
4717
- return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
4718
- }
4719
- function registerDefinition(definitions, definition, sourceLabel) {
4720
- const existing = definitions.get(definition.name);
4721
- if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
4722
- definitions.set(definition.name, definition);
4723
- }
4724
- function mergeDefinitions(feature, ...sources) {
4725
- const definitions = /* @__PURE__ */ new Map();
4726
- for (const source of sources) {
4727
- if (!source) continue;
4728
- for (const definition of source) {
4729
- const existing = definitions.get(definition.name);
4730
- if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
4731
- if (!existing) definitions.set(definition.name, definition);
4732
- }
4733
- }
4734
- return sortDefinitions(definitions);
4735
- }
4736
- function createDefinition(source, file, name) {
4737
- if (source.createDefinition) return source.createDefinition({
4738
- file,
4739
- name
4740
- });
4741
- return {
4742
- handler: file,
4743
- name,
4744
- source: source.source
4745
- };
4746
- }
4747
- function scanSuffixDefinitions(feature, source) {
4748
- const definitions = /* @__PURE__ */ new Map();
4749
- for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
4750
- source.pattern.lastIndex = 0;
4751
- return source.pattern.test(name);
4752
- }, { includeHidden: source.includeHidden })) {
4753
- const name = source.normalizeName(root, file);
4754
- if (!name) continue;
4755
- registerDefinition(definitions, createDefinition(source, file, name), feature);
4756
- }
4757
- return sortDefinitions(definitions);
4758
- }
4759
- function scanDirectoryDefinitions(feature, source) {
4760
- const definitions = /* @__PURE__ */ new Map();
4761
- for (const scanDir of source.scanDirs) {
4762
- const directory = resolve$1(scanDir, source.subdir);
4763
- for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
4764
- const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
4765
- if (!name) continue;
4766
- registerDefinition(definitions, createDefinition(source, file, name), feature);
4767
- }
4768
- }
4769
- return sortDefinitions(definitions);
4770
- }
4771
- function discoverDefinitions(feature, sources) {
4772
- return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
4773
- }
4774
- /** `writeFileIfChangedSync` for async callers. */
4775
- async function writeFileIfChanged$1(file, contents) {
4776
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
4777
- await mkdir(resolve$1(file, ".."), { recursive: true });
4778
- await writeFile(file, contents, "utf8");
4779
- }
4780
- //#endregion
4781
4994
  //#region ../internal/src/deployment.ts
4782
4995
  const unsupported = (reason) => ({
4783
4996
  reason,
@@ -5051,7 +5264,7 @@ async function collectGeneratedTypeFiles(directory, root = directory, visitedDir
5051
5264
  }
5052
5265
  return files;
5053
5266
  }
5054
- async function writeFileIfChanged(path, contents) {
5267
+ async function writeFileIfChanged$1(path, contents) {
5055
5268
  let current;
5056
5269
  try {
5057
5270
  current = await readFile(path, "utf8");
@@ -5069,7 +5282,7 @@ async function writeViteHubTypes(options) {
5069
5282
  const generatedDirectory = resolve(root, ".vitehub");
5070
5283
  return (await collectGeneratedTypeFiles(generatedDirectory)).map((file) => relative(directory, join(generatedDirectory, file)).replaceAll("\\", "/"));
5071
5284
  }))).flat())].sort().map((file) => `/// <reference path="${isAbsolute(file) ? file : `./${file}`}" />`).join("\n");
5072
- await writeFileIfChanged(resolve(options.projectRoot, viteHubTypesEntry), `${references}${references ? "\n\n" : ""}export {}\n`);
5285
+ await writeFileIfChanged$1(resolve(options.projectRoot, viteHubTypesEntry), `${references}${references ? "\n\n" : ""}export {}\n`);
5073
5286
  }
5074
5287
  function viteHubTypesPlugin(options = {}) {
5075
5288
  let projectRoot;
@@ -5154,10 +5367,7 @@ function viteHubTypesPlugin(options = {}) {
5154
5367
  //#endregion
5155
5368
  //#region src/internal/feature-support.ts
5156
5369
  /** The features that `vitehub()` checks when the app turns them on, with the error for a host that cannot provide them. */
5157
- const featureErrors = {
5158
- browser: () => viteHubErrorDiagnostics.VITE_HUB_R0088({ message: "[vitehub] Browser currently requires the Cloudflare host." }),
5159
- email: () => viteHubErrorDiagnostics.VITE_HUB_R0089({ message: "[vitehub] email: true currently requires the Cloudflare host; configure an explicit Email driver for other hosts." })
5160
- };
5370
+ const featureErrors = { browser: () => viteHubErrorDiagnostics.VITE_HUB_R0088({ message: "[vitehub] Browser currently requires the Cloudflare host." }) };
5161
5371
  /**
5162
5372
  * Throws when `host` cannot provide the feature `id` that `options` turns on.
5163
5373
  * An `explicit` host needs the app to choose the provider. Only the `true` shorthand asks ViteHub to choose. An options
@@ -5170,6 +5380,19 @@ function assertFeatureSupported(id, host, options) {
5170
5380
  if (support.level === "native" || support.level === "explicit" && value !== true) return;
5171
5381
  throw featureErrors[id]();
5172
5382
  }
5383
+ /**
5384
+ * The Email driver that `email: true` selects: the host driver from the catalog, or `log` when the host has none.
5385
+ * A production build with `log` fails in `assertEmailBuildDriver()`.
5386
+ */
5387
+ function defaultEmailDriver(host) {
5388
+ const support = featureSupport("email", host);
5389
+ return support.level === "native" && support.driver === "cloudflare" ? "cloudflare" : "log";
5390
+ }
5391
+ /** Throws when a production build has `email: true` on a host that has no default Email provider. */
5392
+ function assertEmailBuildDriver(host, email) {
5393
+ if (email !== true || defaultEmailDriver(host) !== "log") return;
5394
+ throw viteHubErrorDiagnostics.VITE_HUB_R0089({ message: `[vitehub] \`email: true\` has no default provider on the "${host}" host. \`vite dev\` keeps each message in the development outbox, but a production build must send real email.` });
5395
+ }
5173
5396
  /** The Deployment Plan services that the app can ask ViteHub to select from the host, and their features. */
5174
5397
  const serviceFeatures = {
5175
5398
  blob: "blob",
@@ -5209,7 +5432,7 @@ function projectOf(config) {
5209
5432
  serverDirs: config[VITEHUB_SERVER_DIRS]
5210
5433
  };
5211
5434
  }
5212
- /** Options whose `cms` preset features a framework integration already resolved, for example Nuxt with a known root. */
5435
+ /** Options whose features a framework integration already resolved, for example Nuxt with a known root. */
5213
5436
  const resolvedFeatureOptions = /* @__PURE__ */ new WeakSet();
5214
5437
  /** The features that the `cms` preset needs. `vitehub()` turns on the ones left unset. */
5215
5438
  function withCmsPresetFeatures(options, store) {
@@ -5244,11 +5467,18 @@ function resolveStorageFeatures(options, project) {
5244
5467
  database: true
5245
5468
  } : options;
5246
5469
  }
5247
- /** Marks options whose `cms` preset features are resolved, so `vitehub()` does not resolve them again. */
5470
+ /**
5471
+ * Marks options whose `cms` preset features and Definition features are resolved, so `vitehub()` does not resolve them
5472
+ * again.
5473
+ */
5248
5474
  function markCmsPresetFeaturesResolved(options) {
5249
5475
  resolvedFeatureOptions.add(options);
5250
5476
  return options;
5251
5477
  }
5478
+ /** Whether a framework integration resolved the features of these options with `markCmsPresetFeaturesResolved()`. */
5479
+ function featureOptionsResolved(options) {
5480
+ return resolvedFeatureOptions.has(options);
5481
+ }
5252
5482
  function selectedCmsPresetStore(config) {
5253
5483
  return cmsStore(projectOf(config));
5254
5484
  }
@@ -5378,82 +5608,253 @@ function withCmsPresetPlugins(options, createPlain) {
5378
5608
  if (github) merged = composeVariants(merged, "error" in github ? failing(github.error) : github, (config) => selectedCmsPresetStore(config) === "github");
5379
5609
  return merged;
5380
5610
  }
5381
- /**
5382
- * Builds the plugin list for `options`, with KV on when `kv` is unset and `server/content.ts` imports `github()`. A
5383
- * `github()` Source keeps its head commit in KV. When the list with KV fails to build, such as without `@vite-hub/kv`,
5384
- * the app keeps no KV, and Content logs `CONTENT_R0021` and reads the branch.
5385
- */
5386
- function withContentKVPlugins(options, create) {
5387
- if (options.kv !== void 0 || !ownerModules.contentVite || !ownerModules.kvVite) return create(options);
5388
- let withKV;
5389
- try {
5390
- withKV = flattenPluginOptions$1(create({
5391
- ...options,
5392
- kv: true
5393
- }), []);
5394
- } catch {
5395
- return create(options);
5611
+ /**
5612
+ * Builds the plugin list for `options`, with KV on when `kv` is unset and `server/content.ts` imports `github()`. A
5613
+ * `github()` Source keeps its head commit in KV. When the list with KV fails to build, such as without `@vite-hub/kv`,
5614
+ * the app keeps no KV, and Content logs `CONTENT_R0021` and reads the branch.
5615
+ */
5616
+ function withContentKVPlugins(options, create) {
5617
+ if (options.kv !== void 0 || !ownerModules.contentVite || !ownerModules.kvVite) return create(options);
5618
+ let withKV;
5619
+ try {
5620
+ withKV = flattenPluginOptions$1(create({
5621
+ ...options,
5622
+ kv: true
5623
+ }), []);
5624
+ } catch {
5625
+ return create(options);
5626
+ }
5627
+ return composeVariants(flattenPluginOptions$1(create(options), []), withKV, (config) => usesGitHubSources(projectOf(config)));
5628
+ }
5629
+ //#endregion
5630
+ //#region ../internal/src/definition-catalog.ts
5631
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
5632
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
5633
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
5634
+ const ignoredDirs = /* @__PURE__ */ new Set([
5635
+ "node_modules",
5636
+ "dist",
5637
+ ".output",
5638
+ ".nuxt",
5639
+ ".vercel",
5640
+ ".git",
5641
+ ".vitehub"
5642
+ ]);
5643
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
5644
+ return {
5645
+ ...options,
5646
+ kind: "directory",
5647
+ scanDirs,
5648
+ source,
5649
+ subdir
5650
+ };
5651
+ }
5652
+ function readDirEntries(root) {
5653
+ try {
5654
+ return readdirSync(root, { withFileTypes: true });
5655
+ } catch (error) {
5656
+ if (error.code === "ENOENT") return [];
5657
+ throw error;
5658
+ }
5659
+ }
5660
+ function isGitRepositoryDirectory(directory) {
5661
+ return existsSync(resolve$1(directory, ".git"));
5662
+ }
5663
+ function listMatchingFiles(root, predicate, options = {}) {
5664
+ const files = [];
5665
+ for (const entry of readDirEntries(root)) {
5666
+ const absolute = resolve$1(root, entry.name);
5667
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
5668
+ if (isGitRepositoryDirectory(absolute)) continue;
5669
+ if (entry.name.startsWith(".")) continue;
5670
+ if (ignoredDirs.has(entry.name)) continue;
5671
+ files.push(...listMatchingFiles(absolute, predicate, options));
5672
+ continue;
5673
+ }
5674
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
5675
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
5676
+ }
5677
+ return files.sort();
5678
+ }
5679
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
5680
+ function isDefinitionSourceFile(name) {
5681
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
5682
+ }
5683
+ function listSourceFiles(root, options = {}) {
5684
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
5685
+ }
5686
+ /**
5687
+ * Whether `path` is a file, or a folder that holds a Definition source file. A Definition file in a server directory,
5688
+ * such as `server/auth.ts` or a file in `server/queues/`, turns its feature on without a key. An empty folder, which
5689
+ * Git does not keep, turns nothing on.
5690
+ */
5691
+ function hasDefinitionFiles(path) {
5692
+ if (!existsSync(path)) return false;
5693
+ return statSync(path).isFile() || listSourceFiles(path).length > 0;
5694
+ }
5695
+ function normalizePathDefinitionName(rootDir, file) {
5696
+ return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
5697
+ }
5698
+ function sortDefinitions(definitions) {
5699
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
5700
+ }
5701
+ function registerDefinition(definitions, definition, sourceLabel) {
5702
+ const existing = definitions.get(definition.name);
5703
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
5704
+ definitions.set(definition.name, definition);
5705
+ }
5706
+ function mergeDefinitions(feature, ...sources) {
5707
+ const definitions = /* @__PURE__ */ new Map();
5708
+ for (const source of sources) {
5709
+ if (!source) continue;
5710
+ for (const definition of source) {
5711
+ const existing = definitions.get(definition.name);
5712
+ if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
5713
+ if (!existing) definitions.set(definition.name, definition);
5714
+ }
5715
+ }
5716
+ return sortDefinitions(definitions);
5717
+ }
5718
+ function createDefinition(source, file, name) {
5719
+ if (source.createDefinition) return source.createDefinition({
5720
+ file,
5721
+ name
5722
+ });
5723
+ return {
5724
+ handler: file,
5725
+ name,
5726
+ source: source.source
5727
+ };
5728
+ }
5729
+ function scanSuffixDefinitions(feature, source) {
5730
+ const definitions = /* @__PURE__ */ new Map();
5731
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
5732
+ source.pattern.lastIndex = 0;
5733
+ return source.pattern.test(name);
5734
+ }, { includeHidden: source.includeHidden })) {
5735
+ const name = source.normalizeName(root, file);
5736
+ if (!name) continue;
5737
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
5738
+ }
5739
+ return sortDefinitions(definitions);
5740
+ }
5741
+ function scanDirectoryDefinitions(feature, source) {
5742
+ const definitions = /* @__PURE__ */ new Map();
5743
+ for (const scanDir of source.scanDirs) {
5744
+ const directory = resolve$1(scanDir, source.subdir);
5745
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
5746
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
5747
+ if (!name) continue;
5748
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
5749
+ }
5396
5750
  }
5397
- return composeVariants(flattenPluginOptions$1(create(options), []), withKV, (config) => usesGitHubSources(projectOf(config)));
5751
+ return sortDefinitions(definitions);
5398
5752
  }
5399
- //#endregion
5400
- //#region src/hook-errors.ts
5401
- /** Vite prints a `config` or `configResolved` error with all its fields, so it shows the fix already. */
5402
- const printedByVite = /* @__PURE__ */ new Set(["config", "configResolved"]);
5403
- const printed = /* @__PURE__ */ new WeakSet();
5404
- /** Prints to stderr, with the original error of a diagnostic after it when the diagnostic has a `cause`. */
5405
- const printDiagnostic = createConsoleReporter({ method: "error" });
5406
- /** A nostics diagnostic from any bundled copy of nostics: an error with a code and a fix or docs link. */
5407
- function isDiagnostic(error) {
5408
- return error instanceof Error && typeof Reflect.get(error, "code") === "string" && (typeof Reflect.get(error, "fix") === "string" || typeof Reflect.get(error, "docs") === "string");
5753
+ function discoverDefinitions(feature, sources) {
5754
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
5755
+ }
5756
+ /** `writeFileIfChangedSync` for async callers. */
5757
+ async function writeFileIfChanged(file, contents) {
5758
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
5759
+ await mkdir(resolve$1(file, ".."), { recursive: true });
5760
+ await writeFile(file, contents, "utf8");
5409
5761
  }
5762
+ //#endregion
5763
+ //#region src/internal/definition-features.ts
5410
5764
  /**
5411
- * Prints a diagnostic once, with its fix, docs link and cause. Rolldown wraps a hook error in "Build failed with 1 error".
5412
- * It keeps `fix`, `docs` and `cause` on `errors[0]` and prints `cause`, but no bundler prints `fix`, so the fix of a
5413
- * ViteHub code would not reach the terminal. Rolldown also drops `url` (https://github.com/rolldown/rolldown/issues/11739).
5414
- * `vite dev` prints neither `cause` nor `url`; not reported to Vite yet (repro:
5415
- * https://github.com/onmax/repros/tree/repro/vite-dev-error-cause/vite-dev-error-cause).
5765
+ * The features that a Definition file turns on when the app does not set their key, such as Auth with
5766
+ * `server/auth.ts` or Queue with `server/queues/`. `x: false` keeps a feature off, and `x: {…}` sets its options.
5767
+ * The feature catalog lists the files of each feature in `enabledByDiscovery`.
5416
5768
  */
5417
- function report(error) {
5418
- if (isDiagnostic(error) && !printed.has(error)) {
5419
- printed.add(error);
5420
- printDiagnostic(error, {});
5769
+ const definitionFeatureIds = [
5770
+ "agent",
5771
+ "auth",
5772
+ "browser",
5773
+ "channels",
5774
+ "connections",
5775
+ "queue",
5776
+ "realtime",
5777
+ "schedule",
5778
+ "workflow",
5779
+ "workspace"
5780
+ ];
5781
+ /** The first Definition file or folder of each feature whose key is unset, relative to the project root. */
5782
+ function discoverDefinitionFeatures(options, project) {
5783
+ const serverDirs = project.serverDirs ?? ["server"];
5784
+ const found = /* @__PURE__ */ new Map();
5785
+ for (const id of definitionFeatureIds) {
5786
+ if (options[id] !== void 0) continue;
5787
+ const file = serverDirs.flatMap((directory) => (features[id].enabledByDiscovery ?? []).map((name) => resolve(project.projectRoot, directory, name))).find((candidate) => hasDefinitionFiles(candidate));
5788
+ if (file) found.set(id, relative(project.projectRoot, file));
5789
+ }
5790
+ if ((found.has("channels") || options.channels !== void 0 && options.channels !== false) && options.agent === void 0 && !found.has("agent")) {
5791
+ const channelRoot = typeof options.channels === "object" ? options.channels.projectRoot : void 0;
5792
+ const inbound = ownerModules.channelsVite?.findWebhookChannel({
5793
+ projectRoot: channelRoot ? resolve(project.viteRoot ?? project.projectRoot, channelRoot) : project.projectRoot,
5794
+ serverDirs: channelRoot ? void 0 : project.serverDirs?.map((directory) => resolve(project.projectRoot, directory))
5795
+ });
5796
+ if (inbound) found.set("agent", relative(project.projectRoot, inbound.handler));
5421
5797
  }
5422
- throw error;
5423
- }
5424
- function wrap(handler) {
5425
- return function(...args) {
5426
- let result;
5427
- try {
5428
- result = handler.apply(this, args);
5429
- } catch (error) {
5430
- report(error);
5431
- }
5432
- return result instanceof Promise ? result.catch(report) : result;
5433
- };
5798
+ return found;
5434
5799
  }
5435
- function wrapPlugin(plugin) {
5436
- for (const [name, hook] of Object.entries(plugin)) {
5437
- if (printedByVite.has(name)) continue;
5438
- if (typeof hook === "function") Reflect.set(plugin, name, wrap(hook));
5439
- else if (hook && typeof hook === "object" && "handler" in hook && typeof hook.handler === "function") hook.handler = wrap(hook.handler);
5440
- }
5800
+ function missingPackages(id) {
5801
+ return optionalFeaturePackages[id].filter((name) => !isPackageInstalled(name));
5441
5802
  }
5442
5803
  /**
5443
- * Makes the build and dev hooks of the ViteHub plugins print the fix and docs link of a ViteHub error before Vite or
5444
- * Rolldown reports it. The error itself does not change. The plugins keep their identity, so other plugins still find them.
5804
+ * Turns on each feature whose key is unset and whose Definition file exists. It fails with the `pnpm add` command when
5805
+ * a Definition file exists and its package is not installed.
5445
5806
  */
5446
- function withPrintedDiagnostics(option) {
5447
- if (option instanceof Promise) {
5448
- option.then(withPrintedDiagnostics, () => {});
5449
- return option;
5807
+ function resolveDefinitionFeatures(options, project) {
5808
+ const found = discoverDefinitionFeatures(options, project);
5809
+ if (!found.size) return options;
5810
+ let missing = [...found.keys()].filter((id) => missingPackages(id).length);
5811
+ if (missing.length) {
5812
+ forgetPackageChecks();
5813
+ missing = missing.filter((id) => missingPackages(id).length);
5450
5814
  }
5451
- if (Array.isArray(option)) {
5452
- for (const item of option) withPrintedDiagnostics(item);
5453
- return option;
5815
+ if (missing.length) {
5816
+ const packages = [...new Set(missing.flatMap(missingPackages))];
5817
+ throw viteHubErrorDiagnostics.VITE_HUB_DEFINITION_PACKAGE_MISSING({
5818
+ definitions: missing.map((id) => `${found.get(id)} turns ${features[id].title} on`).join(", and "),
5819
+ install: installArguments(packages).join(" "),
5820
+ off: missing.map((id) => `\`${id}: false\``).join(", "),
5821
+ packages: packages.join(", ")
5822
+ });
5454
5823
  }
5455
- if (option && typeof option === "object" && "name" in option) wrapPlugin(option);
5456
- return option;
5824
+ return {
5825
+ ...options,
5826
+ ...Object.fromEntries([...found.keys()].map((id) => [id, true]))
5827
+ };
5828
+ }
5829
+ /**
5830
+ * `vitehub()` looks for Definition files in the project of the working directory, because Vite gives the plugins its
5831
+ * root only later. This plugin fails the build when the Vite root is another project with other Definition files, so a
5832
+ * feature is never on or off by mistake.
5833
+ */
5834
+ function definitionFeaturesRootPlugin(options, project, validate) {
5835
+ const guessed = [...discoverDefinitionFeatures(options, project).keys()];
5836
+ return {
5837
+ name: "vite-hub/definition-features-root",
5838
+ configResolved(config) {
5839
+ const viteConfig = config;
5840
+ const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
5841
+ const serverDirs = viteConfig[VITEHUB_SERVER_DIRS];
5842
+ if (projectRoot !== project.projectRoot || serverDirs || resolve(config.root) !== (project.viteRoot ?? project.projectRoot)) {
5843
+ const found = discoverDefinitionFeatures(options, {
5844
+ projectRoot,
5845
+ serverDirs,
5846
+ viteRoot: config.root
5847
+ });
5848
+ const changed = definitionFeatureIds.filter((id) => found.has(id) !== guessed.includes(id));
5849
+ if (changed.length) throw viteHubErrorDiagnostics.VITE_HUB_DEFINITION_ROOT_MISMATCH({
5850
+ keys: changed.map((id) => `\`${id}\``).join(", "),
5851
+ projectRoot,
5852
+ workingDirectory: project.projectRoot
5853
+ });
5854
+ }
5855
+ validate?.();
5856
+ }
5857
+ };
5457
5858
  }
5458
5859
  //#endregion
5459
5860
  //#region src/internal/kv-runtime.ts
@@ -5926,6 +6327,120 @@ function vitestInlinePlugin() {
5926
6327
  };
5927
6328
  }
5928
6329
  //#endregion
6330
+ //#region src/cloudflare-node-dev.ts
6331
+ const cloudflareDevShims = {
6332
+ "cloudflare:email": {
6333
+ id: "\0vitehub-dev:cloudflare-email",
6334
+ source: cloudflareEmailDevShimSource
6335
+ },
6336
+ "cloudflare:workers": {
6337
+ id: "\0vitehub-dev:cloudflare-workers",
6338
+ source: cloudflareWorkersDevShimSource
6339
+ }
6340
+ };
6341
+ /**
6342
+ * Code that ViteHub generates for the Cloudflare host imports `cloudflare:workers` and `cloudflare:email`. `vite dev`
6343
+ * runs the Nitro server on Node by default, where these modules do not exist, so it gets the Node stubs that `nuxt dev`
6344
+ * uses: `env` reads the request bindings and `process.env`. The `miniflare` dev runner has the real modules.
6345
+ */
6346
+ function cloudflareNodeDevPlugin() {
6347
+ let nitro;
6348
+ return {
6349
+ name: "vite-hub/cloudflare-node-dev",
6350
+ apply: "serve",
6351
+ enforce: "pre",
6352
+ nitro: { setup(instance) {
6353
+ nitro = instance;
6354
+ } },
6355
+ resolveId(id) {
6356
+ if ((nitro?.options.devServer.runner || process.env.NITRO_DEV_RUNNER) !== "miniflare" && Object.hasOwn(cloudflareDevShims, id)) return cloudflareDevShims[id].id;
6357
+ },
6358
+ load(id) {
6359
+ for (const shim of Object.values(cloudflareDevShims)) if (shim.id === id) return shim.source;
6360
+ }
6361
+ };
6362
+ }
6363
+ //#endregion
6364
+ //#region src/internal/forge-build-check.ts
6365
+ const sourceEntries = /* @__PURE__ */ new Set([
6366
+ "vite-hub/source",
6367
+ "@vite-hub/source",
6368
+ "vite-hub/workspace",
6369
+ "@vite-hub/workspace"
6370
+ ]);
6371
+ const resolvedSourceEntry = /[/\\](?:(?:dist[/\\](source|workspace|index)\.js)|(?:src[/\\](source|workspace|index)\.ts))$/;
6372
+ const runtimeOwners = /* @__PURE__ */ new Set([
6373
+ "@vite-hub/workspace",
6374
+ "@vite-hub/agent",
6375
+ "@vite-hub/source",
6376
+ "vite-hub"
6377
+ ]);
6378
+ const checkedGitHub = "\0vitehub:checked-github:";
6379
+ const sourceFacade = "\0vitehub:source-facade:";
6380
+ const originalEntry = "\0vitehub:original-source-entry:";
6381
+ /**
6382
+ * Check the GitHub helper selected by server code, not the imports kept by shared runtime code.
6383
+ */
6384
+ function forgeBuildCheckPlugin() {
6385
+ const owners = /* @__PURE__ */ new Map();
6386
+ const entries = /* @__PURE__ */ new Map();
6387
+ function ownerOf(path) {
6388
+ const directory = dirname(path);
6389
+ if (!owners.has(directory)) {
6390
+ const manifest = findPackageJSON(pathToFileURL(directory + sep));
6391
+ owners.set(directory, manifest && basename(manifest) === "package.json" ? JSON.parse(readFileSync(manifest, "utf8")).name : void 0);
6392
+ }
6393
+ return owners.get(directory);
6394
+ }
6395
+ return {
6396
+ name: "vite-hub/forge-build-check",
6397
+ apply: "build",
6398
+ enforce: "pre",
6399
+ async resolveId(source, importer, options) {
6400
+ if (source.startsWith(originalEntry)) return entries.get(source);
6401
+ if (source.startsWith(checkedGitHub)) return source;
6402
+ if (!importer || isPackageInstalled("@vite-hub/forge")) return;
6403
+ if (!sourceEntries.has(source)) {
6404
+ const matched = isAbsolute(source) && resolvedSourceEntry.exec(source);
6405
+ if (!matched) return;
6406
+ const exportName = matched[1] ?? matched[2];
6407
+ const owner = ownerOf(source);
6408
+ if (exportName === "index" ? owner !== "@vite-hub/source" && owner !== "@vite-hub/workspace" : owner !== "vite-hub") return;
6409
+ }
6410
+ const file = importer.split("?", 1)[0];
6411
+ const path = file.startsWith("file:") ? fileURLToPath(file) : file;
6412
+ if (!isAbsolute(path) || runtimeOwners.has(ownerOf(path) ?? "")) return;
6413
+ const entry = await this.resolve(source, importer, {
6414
+ ...options,
6415
+ skipSelf: true
6416
+ });
6417
+ if (!entry) return;
6418
+ const key = JSON.stringify([entry.id, entry.external]);
6419
+ entries.set(originalEntry + key, {
6420
+ id: entry.id,
6421
+ external: entry.external
6422
+ });
6423
+ return {
6424
+ id: sourceFacade + key,
6425
+ moduleSideEffects: false
6426
+ };
6427
+ },
6428
+ load(id) {
6429
+ if (id.startsWith(sourceFacade)) {
6430
+ const key = id.slice(23);
6431
+ return `export * from ${JSON.stringify(originalEntry + key)}; export { github } from ${JSON.stringify(checkedGitHub + key)};`;
6432
+ }
6433
+ if (id.startsWith(checkedGitHub)) {
6434
+ const key = id.slice(24);
6435
+ return `import { github as createGitHub } from ${JSON.stringify(originalEntry + key)}; export function github(...args) { return createGitHub(...args); }`;
6436
+ }
6437
+ },
6438
+ generateBundle(_options, bundle) {
6439
+ if (Object.values(bundle).some((output) => output.type === "chunk" && output.moduleIds.some((id) => id.startsWith(checkedGitHub)))) assertFeaturePackages(["forge"]);
6440
+ }
6441
+ };
6442
+ }
6443
+ //#endregion
5929
6444
  //#region src/error-log-vite.ts
5930
6445
  /**
5931
6446
  * Render the Nitro plugin that logs unhandled request errors with their message, stack, status, and cause chain.
@@ -6046,22 +6561,26 @@ async function readBuildRepository(root, env = process.env, git = (args) => read
6046
6561
  }
6047
6562
  //#endregion
6048
6563
  //#region src/health-vite.ts
6049
- const defaultHealthRoute = "/api/_vitehub/health";
6564
+ const defaultHealthRoute = "/_vitehub/health";
6050
6565
  /** How long one Database, KV store, or Blob store may take to answer the health check. */
6051
6566
  const healthCheckTimeoutMs = 2e3;
6052
- /** A key that no app writes. KV and Blob read it to prove that the store answers, which costs one read. */
6567
+ /** A key that no app writes. KV reads it to prove that the store answers, which costs one read. */
6053
6568
  const probeKey = "vitehub-health-check";
6569
+ function blobRuntimeModule() {
6570
+ return fileURLToPath(import.meta.resolve("@vite-hub/blob/runtime/state"));
6571
+ }
6054
6572
  /**
6055
- * The health handler: `{ ok, version, commit, vitehub }`, and `checks` with whether each Database answered `SELECT 1` and
6056
- * whether each KV and Blob store answered one read, within {@link healthCheckTimeoutMs}. It answers 503 when a check
6057
- * fails. The response holds no error text, so it shows no connection details. The error goes to the server log.
6573
+ * The health handler: `{ ok, version, commit, vitehub }`, and `checks` with whether each Database answered `SELECT 1`,
6574
+ * each KV store answered one read, and each Blob store passed its driver check, within {@link healthCheckTimeoutMs}. It answers
6575
+ * 503 when a check fails. The response holds no error text, so it shows no connection details. The error goes to the
6576
+ * server log.
6058
6577
  */
6059
6578
  function renderHealthHandler(input) {
6060
6579
  const headers = `{ "cache-control": "no-store" }`;
6061
6580
  const groups = [
6062
6581
  ...input.database ? [`database: import("@vite-hub/database/runtime/registry").then(({ pingDatabases }) => pingDatabases())`] : [],
6063
- ...input.kv.length ? [`kv: import("vite-hub/kv").then(({ kv }) => checkStores("KV store", ${JSON.stringify(input.kv)}, name => kv.store(name, { mode: "read" }).has(${JSON.stringify(probeKey)})))`] : [],
6064
- ...input.blob.length ? [`blob: import("vite-hub/blob").then(({ blob }) => checkStores("Blob store", ${JSON.stringify(input.blob)}, name => blob.store(name, { mode: "read" }).head(${JSON.stringify(probeKey)})))`] : []
6582
+ ...input.kv.length ? [`kv: import("vite-hub/kv").then(({ kv }) => checkStores("KV store", ${JSON.stringify(input.kv)}, async (name) => { const [error] = await kv.store(name, { mode: "read" }).has(${JSON.stringify(probeKey)}); if (error) throw error }))`] : [],
6583
+ ...input.blob.length ? [`blob: import(${JSON.stringify(blobRuntimeModule())}).then(({ checkBlobStoreHealth }) => checkStores("Blob store", ${JSON.stringify(input.blob)}, checkBlobStoreHealth))`] : []
6065
6584
  ];
6066
6585
  const build = input.version ? "version, commit, vitehub" : "commit, vitehub";
6067
6586
  return [
@@ -6070,14 +6589,13 @@ function renderHealthHandler(input) {
6070
6589
  `const vitehub = ${JSON.stringify(input.vitehub)}`,
6071
6590
  "",
6072
6591
  ...input.kv.length || input.blob.length ? [
6073
- "/** Whether each store answers one read within the timeout. A store that fails is `false`, and its error goes to the server log. */",
6074
- "async function checkStores(kind, names, read) {",
6592
+ "/** Whether each store answers within the timeout. A store that fails is `false`, and its error goes to the server log. */",
6593
+ "async function checkStores(kind, names, check) {",
6075
6594
  " return Object.fromEntries(await Promise.all(names.map(async (name) => {",
6076
6595
  " let timer",
6077
6596
  " try {",
6078
6597
  ` const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("No answer within ${healthCheckTimeoutMs} ms.")), ${healthCheckTimeoutMs}) })`,
6079
- " const [error] = await Promise.race([read(name), timeout])",
6080
- " if (error) throw error",
6598
+ " await Promise.race([check(name), timeout])",
6081
6599
  " return [name, true]",
6082
6600
  " }",
6083
6601
  " catch (error) {",
@@ -6120,7 +6638,7 @@ function healthVitePlugin(options, targets) {
6120
6638
  const projectRoot = typeof viteConfig["__vitehubProjectRoot"] === "string" ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root || process.cwd());
6121
6639
  const handler = resolve(projectRoot, ".vitehub/nitro/health.mjs");
6122
6640
  const [{ commit }, version] = await Promise.all([readBuildRevision(projectRoot), readAppVersion(projectRoot)]);
6123
- await writeFileIfChanged$1(handler, renderHealthHandler({
6641
+ await writeFileIfChanged(handler, renderHealthHandler({
6124
6642
  ...version ? { version } : {},
6125
6643
  commit: commit ?? null,
6126
6644
  vitehub: readViteHubVersion(),
@@ -6129,7 +6647,7 @@ function healthVitePlugin(options, targets) {
6129
6647
  const kit = createNitroServerKit(viteConfig.nitro);
6130
6648
  kit.addHandler({
6131
6649
  handler,
6132
- route: options.route ?? "/api/_vitehub/health"
6650
+ route: options.route ?? "/_vitehub/health"
6133
6651
  });
6134
6652
  viteConfig.nitro = kit.config;
6135
6653
  }
@@ -6152,7 +6670,7 @@ function indexNowKey(publicUrl) {
6152
6670
  /** What `vitehub deploy` does after the upload, for `deployment.json`. Undefined when it does nothing. */
6153
6671
  function resolveDeployManifest(input) {
6154
6672
  const configured = typeof input.deploy?.check === "string" ? [input.deploy.check] : input.deploy?.check ?? [];
6155
- const health = input.health ? [input.health === true ? defaultHealthRoute : input.health.route ?? "/api/_vitehub/health"] : [];
6673
+ const health = input.health ? [input.health === true ? defaultHealthRoute : input.health.route ?? "/_vitehub/health"] : [];
6156
6674
  const check = [...new Set([...health, ...configured].map(checkPath))];
6157
6675
  let indexNow;
6158
6676
  if (input.deploy?.indexNow) {
@@ -6216,7 +6734,7 @@ function viteHubSeoPlugin(options, publicUrl) {
6216
6734
  const writePages = async () => {
6217
6735
  if (!projectRoot || !sitemap) return;
6218
6736
  const pages = discover ? [.../* @__PURE__ */ new Set([...nuxtPages, ...nitroPages])].sort() : [];
6219
- await writeFileIfChanged$1(resolve(projectRoot, pagesModule), `export default ${JSON.stringify(pages)}\n`);
6737
+ await writeFileIfChanged(resolve(projectRoot, pagesModule), `export default ${JSON.stringify(pages)}\n`);
6220
6738
  };
6221
6739
  return {
6222
6740
  name: "vite-hub/seo",
@@ -6261,7 +6779,7 @@ function viteHubSeoPlugin(options, publicUrl) {
6261
6779
  "sitemap.mjs"
6262
6780
  ].map((name) => join(directory, name))).find((file) => existsSync(file));
6263
6781
  await writePages();
6264
- await writeFileIfChanged$1(resolve(projectRoot, sitemapModule), [
6782
+ await writeFileIfChanged(resolve(projectRoot, sitemapModule), [
6265
6783
  `import { defineSitemapRoute } from ${runtime}`,
6266
6784
  `import pages from "./pages.mjs"`,
6267
6785
  "",
@@ -6276,7 +6794,7 @@ function viteHubSeoPlugin(options, publicUrl) {
6276
6794
  }
6277
6795
  const publicDir = config.publicDir === false ? false : resolve(root, config.publicDir ?? "public");
6278
6796
  if (options.robots !== false && base === "/" && !hasOwnRobots(root, publicDir, serverDirs)) {
6279
- await writeFileIfChanged$1(resolve(projectRoot, robotsModule), [
6797
+ await writeFileIfChanged(resolve(projectRoot, robotsModule), [
6280
6798
  `import { defineRobotsRoute } from ${runtime}`,
6281
6799
  "",
6282
6800
  `export default defineRobotsRoute({ site: ${JSON.stringify(site)}, sitemap: ${Boolean(sitemap)}, disallow: ${JSON.stringify(disallow)}${contentLoader} })`,
@@ -6686,7 +7204,7 @@ function staleChunkReloadNuxtPluginSource() {
6686
7204
  async function installStaleChunkReloadNuxt(nuxt, projectRoot) {
6687
7205
  if (nuxt.options.experimental?.emitRouteChunkError !== "automatic") return;
6688
7206
  const plugin = join(projectRoot, ".vitehub/stale-chunk-reload/nuxt-plugin.client.mjs");
6689
- await writeFileIfChanged$1(plugin, staleChunkReloadNuxtPluginSource());
7207
+ await writeFileIfChanged(plugin, staleChunkReloadNuxtPluginSource());
6690
7208
  const plugins = nuxt.options.plugins ??= [];
6691
7209
  if (!plugins.some((entry) => (typeof entry === "string" ? entry : entry.src) === plugin)) plugins.push(plugin);
6692
7210
  }
@@ -7588,7 +8106,7 @@ function withConsoleDocumentEditorSections(sections, catalog) {
7588
8106
  * and checked again when the app starts.
7589
8107
  */
7590
8108
  async function assertUniqueOperationNames(contributions) {
7591
- const { consoleOperations } = await import("./operations-H9q0QB2C.js");
8109
+ const { consoleOperations } = await import("./operations-CAQmIxGK.js");
7592
8110
  const sources = [{
7593
8111
  operations: [...consoleOperations],
7594
8112
  plugin: "vite-hub"
@@ -8824,28 +9342,22 @@ function consoleOperationFeatures(sections) {
8824
9342
  }
8825
9343
  //#endregion
8826
9344
  //#region src/console/dev-access-notice.ts
8827
- const guide = "https://vitehub.dev/docs/development/console";
9345
+ const guide = "https://vitehub.dev/docs/console/development#share-a-development-server";
8828
9346
  /**
8829
- * The startup line of a development server that takes Console calls without a signature: `local` or `open` access, or
8830
- * `console: true` (`token`) while `env` has no `VITEHUB_CONSOLE_KEY_<NAME>`. The Console endpoint answers only requests
8831
- * from this machine, such as `vitehub` commands, but a tunnel or a proxy on this machine connects from it too, so the
8832
- * line says that sharing the dev server needs signed calls. A server that listens on more than loopback gets a warning.
8833
- * Returns `undefined` for signed calls, and for a server that listens on no TCP address.
9347
+ * The startup warning of a development server that takes Console calls without a signature and listens beyond loopback,
9348
+ * such as with `--host`: `local` or `open` access, or `console: true` (`token`) while `env` has no
9349
+ * `VITEHUB_CONSOLE_KEY_<NAME>`. The Console endpoint refuses other machines, but a tunnel or a proxy on this machine
9350
+ * connects from it, so the warning says that sharing the dev server needs signed calls. A server on loopback only, as a
9351
+ * plain `vite dev`, gets no line: the Console endpoint answers only this machine there.
9352
+ * Returns `undefined` for signed calls, for loopback, and for a server that listens on no TCP address.
8834
9353
  */
8835
9354
  function consoleDevAccessNotice(mode, address, env = process.env) {
8836
- if (!mode || !address || typeof address === "string") return;
9355
+ if (!mode || !address || typeof address === "string" || isViteHubLoopbackAddress(address.address)) return;
8837
9356
  const keyless = mode === "token" && !Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_KEY_") && String(env[name] ?? "").trim());
8838
9357
  if (mode === "token" && !keyless) return;
8839
9358
  const key = `${consolePublicKeyPrefix}<NAME> variable`;
8840
9359
  const fix = keyless ? `Set a ${key}` : mode === "open" ? `Remove console.auth and set a ${key}` : `Set console: true and a ${key}`;
8841
- if (isViteHubLoopbackAddress(address.address)) return {
8842
- level: "info",
8843
- message: `[vitehub] The Console endpoint takes calls without a signature and answers only this machine. ${fix} before you share this dev server through a tunnel or a proxy: ${guide}`
8844
- };
8845
- return {
8846
- level: "warn",
8847
- message: `[vitehub] The dev server listens on ${address.address}, and the Console endpoint takes calls without a signature. It refuses other machines, but a tunnel or a proxy on this machine can reach it. ${fix} before you share this dev server: ${guide}`
8848
- };
9360
+ return `[vitehub] The dev server listens on ${address.address}, and the Console endpoint takes calls without a signature. It refuses other machines, but a tunnel or a proxy on this machine can reach it. ${fix} before you share this dev server: ${guide}`;
8849
9361
  }
8850
9362
  //#endregion
8851
9363
  //#region src/console/vite.ts
@@ -8863,7 +9375,7 @@ const localDevelopmentConsole = Object.freeze({
8863
9375
  auth: false,
8864
9376
  local: true
8865
9377
  });
8866
- const consoleGuide = "https://vitehub.dev/docs/development/console";
9378
+ const consoleGuide = "https://vitehub.dev/docs/console/migrate";
8867
9379
  /** Options that the Console had before it moved out of apps, with the change that replaces each one. */
8868
9380
  const removedConsoleOptions = {
8869
9381
  databaseUrl: "The Agent Invocation journal does not depend on the Console. Set agent: { invocations: { databaseUrl } } in vitehub() instead.",
@@ -8977,7 +9489,7 @@ function resolveConsoleAccessBuild(configured, options) {
8977
9489
  }
8978
9490
  /** Check the Console options against the app: `console.impersonation` needs app Auth. */
8979
9491
  function assertConsoleAccess(configured, options) {
8980
- if (configured.impersonation === true && !options.auth) throw viteHubErrorDiagnostics.VITE_HUB_B0005({ message: "[vitehub] console.impersonation needs app Auth. Set auth: true and add server/auth.ts with Better Auth's admin plugin, or remove console.impersonation." });
9492
+ if (configured.impersonation === true && !options.auth) throw viteHubErrorDiagnostics.VITE_HUB_B0005({ message: "[vitehub] console.impersonation needs app Auth. Add server/auth.ts with Better Auth's admin plugin, or remove console.impersonation." });
8981
9493
  }
8982
9494
  function generatedConsolePluginRegistration(value) {
8983
9495
  const normalized = value.replaceAll("\\", "/");
@@ -9206,13 +9718,13 @@ function consoleVitePlugin(options) {
9206
9718
  if (!cliDiscovery) await refreshConsoleCatalog();
9207
9719
  },
9208
9720
  configureServer(server) {
9209
- publishDevServer(server);
9721
+ publishViteHubDevServer(server);
9210
9722
  if (server.httpServer) addViteHubDevPeerUpgradeSigner(server.httpServer);
9211
9723
  if (resolvedConsoleConfiguration && server.httpServer) {
9212
9724
  const http = server.httpServer;
9213
9725
  http.once("listening", () => {
9214
9726
  const notice = consoleDevAccessNotice(consoleAccess()?.mode, http.address());
9215
- if (notice) server.config.logger[notice.level](notice.message);
9727
+ if (notice) server.config.logger.warn(notice);
9216
9728
  });
9217
9729
  }
9218
9730
  const refresh = async () => {
@@ -9236,7 +9748,7 @@ function consoleVitePlugin(options) {
9236
9748
  function consoleOperationContributions(sections) {
9237
9749
  return [{
9238
9750
  export: "consoleOperations",
9239
- load: async () => (await import("./operations-H9q0QB2C.js")).consoleOperations.filter((operation) => sections().includes("databases") || !operation.name.startsWith("databases.")),
9751
+ load: async () => (await import("./operations-CAQmIxGK.js")).consoleOperations.filter((operation) => sections().includes("databases") || !operation.name.startsWith("databases.")),
9240
9752
  module: "vite-hub/console/server",
9241
9753
  runtime: false
9242
9754
  }, ...sections().includes("mcp-client") ? [{
@@ -9247,35 +9759,6 @@ function consoleOperationContributions(sections) {
9247
9759
  }] : []];
9248
9760
  }
9249
9761
  /**
9250
- * Tell `vitehub` commands where this dev server listens: `.vitehub/dev-server.json` in the project root, removed when
9251
- * the server closes. A host that runs Vite in middleware mode has no listening server and writes nothing.
9252
- */
9253
- function publishDevServer(server) {
9254
- const http = server.httpServer;
9255
- if (!http || server.config.server.middlewareMode) return;
9256
- const root = resolve(server.config.root);
9257
- const write = () => {
9258
- const address = http.address();
9259
- if (!address || typeof address === "string") return;
9260
- const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
9261
- const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
9262
- try {
9263
- writeViteHubDevServerFile(root, {
9264
- root,
9265
- url
9266
- });
9267
- } catch {}
9268
- };
9269
- const remove = () => {
9270
- try {
9271
- removeViteHubDevServerFile(root);
9272
- } catch {}
9273
- };
9274
- if (http.listening) write();
9275
- else http.once("listening", write);
9276
- http.once("close", remove);
9277
- }
9278
- /**
9279
9762
  * Keeps `vite-hub` in the server environments of an app with Agents, so the Console and the app read one Agent
9280
9763
  * Invocation journal, and records when those environments close, so a closed server writes no generated plugin.
9281
9764
  */
@@ -9442,6 +9925,215 @@ async function writeSystemdUnit(outputDir, name, unit) {
9442
9925
  return file;
9443
9926
  }
9444
9927
  //#endregion
9928
+ //#region src/dockerfile.ts
9929
+ const appDir = "/app";
9930
+ const defaultDataDir = `${appDir}/.vitehub`;
9931
+ const dockerArch = {
9932
+ arm: "arm/v7",
9933
+ arm64: "arm64",
9934
+ ppc64: "ppc64le",
9935
+ s390x: "s390x",
9936
+ x64: "amd64"
9937
+ };
9938
+ function currentBuildPlatform() {
9939
+ const header = process.platform === "linux" ? (process.report?.getReport())?.header : void 0;
9940
+ return {
9941
+ arch: process.arch,
9942
+ libc: process.platform === "linux" ? header?.glibcVersionRuntime ? "glibc" : "musl" : void 0,
9943
+ nodeVersion: process.versions.node,
9944
+ os: process.platform
9945
+ };
9946
+ }
9947
+ /**
9948
+ * The packages in the server output that hold code for one OS or CPU: a package.json with `os` or `cpu`, as napi-rs
9949
+ * and esbuild binaries have, or a compiled `.node` addon.
9950
+ */
9951
+ async function findNativePackages(serverDir) {
9952
+ const root = join(serverDir, "node_modules");
9953
+ if (!existsSync(root)) return [];
9954
+ const packages = /* @__PURE__ */ new Set();
9955
+ for (const file of await readdir(root, { recursive: true })) {
9956
+ const entry = packageEntry(file.replaceAll("\\", "/"));
9957
+ if (!entry) continue;
9958
+ if (entry.file.endsWith(".node")) packages.add(entry.name);
9959
+ else if (entry.file === "package.json") {
9960
+ const manifest = JSON.parse(await readFile(join(root, file), "utf8"));
9961
+ if (manifest && typeof manifest === "object" && ("os" in manifest || "cpu" in manifest)) packages.add(entry.name);
9962
+ }
9963
+ }
9964
+ return [...packages].sort();
9965
+ }
9966
+ /** The innermost package that holds a path below `node_modules`, and the path inside that package. */
9967
+ function packageEntry(path) {
9968
+ const index = path.lastIndexOf("node_modules/");
9969
+ const parts = (index === -1 ? path : path.slice(index + 13)).split("/");
9970
+ const size = parts[0].startsWith("@") ? 2 : 1;
9971
+ if (parts.length <= size) return;
9972
+ return {
9973
+ file: parts.slice(size).join("/"),
9974
+ name: parts.slice(0, size).join("/")
9975
+ };
9976
+ }
9977
+ /** Docker image names allow lowercase letters, digits, and separators. */
9978
+ function imageName(name) {
9979
+ return name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "app";
9980
+ }
9981
+ function resolveDockerfile(options) {
9982
+ const { platform } = options;
9983
+ const native = options.nativePackages.length > 0 && platform.os === "linux";
9984
+ const major = platform.nodeVersion.split(".")[0];
9985
+ const arch = native ? dockerArch[platform.arch] : void 0;
9986
+ const dataDir = posix.normalize(options.dataDir ?? defaultDataDir).replace(/\/$/, "") || "/";
9987
+ const coversDefault = dataDir === defaultDataDir || defaultDataDir.startsWith(dataDir === "/" ? dataDir : `${dataDir}/`);
9988
+ return {
9989
+ baseImage: `node:${major}-${native && platform.libc === "musl" ? "alpine" : "slim"}`,
9990
+ dataDirs: coversDefault ? [dataDir] : [defaultDataDir, dataDir],
9991
+ drainMs: options.drainMs,
9992
+ ...options.healthRoute ? { healthRoute: options.healthRoute } : {},
9993
+ hasNativePackages: options.nativePackages.length > 0,
9994
+ imageName: imageName(options.name),
9995
+ ...arch ? { platform: `linux/${arch}` } : {}
9996
+ };
9997
+ }
9998
+ function shellArgument(value) {
9999
+ return /^[\w./:-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
10000
+ }
10001
+ function renderDockerfile(dockerfile) {
10002
+ const stopTimeout = systemdStopTimeoutSeconds(dockerfile.drainMs);
10003
+ const volumes = dockerfile.dataDirs.map((dir, index) => `-v ${shellArgument(`${dockerfile.imageName}${index === 0 ? "" : "-custom"}-data:${dir}`)}`).join(" ");
10004
+ const health = dockerfile.healthRoute ? [
10005
+ "const { NITRO_HOST, NITRO_PORT, HOST, PORT } = process.env",
10006
+ "const host = NITRO_HOST || HOST || '0.0.0.0'",
10007
+ "const address = host === '0.0.0.0' ? '127.0.0.1' : host === '::' ? '[::1]' : host.includes(':') ? '[' + host + ']' : host",
10008
+ "const port = Number.parseInt(NITRO_PORT ?? PORT ?? '')",
10009
+ `fetch('http://' + address + ':' + (Number.isNaN(port) ? 3000 : port) + ${JSON.stringify(dockerfile.healthRoute)}).then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))`
10010
+ ].join("; ") : void 0;
10011
+ return [
10012
+ ...dockerfile.platform ? ["# check=skip=FromPlatformFlagConstDisallowed"] : [],
10013
+ "# Generated by ViteHub. The next build replaces this file. Build the image from the build output and run it:",
10014
+ `# docker build -t ${dockerfile.imageName} .output`,
10015
+ ...volumes.includes("\n") || volumes.includes("\r") ? ["# Mount a named volume at each path listed in VOLUME."] : [`# docker run --init --stop-timeout ${stopTimeout} -p 3000:3000 --env-file .env ${volumes} ${dockerfile.imageName}`],
10016
+ `# --init reaps child processes. The build-time default stop timeout is ${stopTimeout} seconds.`,
10017
+ "# If VITEHUB_SHUTDOWN_DRAIN_MS is set at runtime, use --stop-timeout = ceil(budget in seconds) + 30.",
10018
+ ...dockerfile.platform ? ["# The output has native packages for this CPU, so the image uses the same platform."] : [],
10019
+ ...dockerfile.hasNativePackages ? [
10020
+ `# Native ABI compatibility is not inferred. Build the app in ${dockerfile.baseImage} for the target CPU, or use a compatible Linux Node base for both steps.`,
10021
+ "# To use the same exact base as the app build, pass --build-arg VITEHUB_NODE_IMAGE=<image-or-digest> to docker build.",
10022
+ `ARG VITEHUB_NODE_IMAGE=${dockerfile.baseImage}`
10023
+ ] : [],
10024
+ `FROM ${dockerfile.platform ? `--platform=${dockerfile.platform} ` : ""}${dockerfile.hasNativePackages ? "${VITEHUB_NODE_IMAGE}" : dockerfile.baseImage}`,
10025
+ `WORKDIR ${appDir}`,
10026
+ "COPY . .output/",
10027
+ `RUN ${JSON.stringify([
10028
+ "install",
10029
+ "-d",
10030
+ "-o",
10031
+ "node",
10032
+ "-g",
10033
+ "node",
10034
+ .../* @__PURE__ */ new Set([appDir, ...dockerfile.dataDirs])
10035
+ ])}`,
10036
+ "USER node",
10037
+ "ENV NODE_ENV=production HOST=0.0.0.0 PORT=3000",
10038
+ "EXPOSE 3000",
10039
+ `VOLUME ${JSON.stringify(dockerfile.dataDirs)}`,
10040
+ "STOPSIGNAL SIGTERM",
10041
+ ...health ? ["# This probe uses HTTP over TCP. For TLS or a Unix socket, use --no-healthcheck or replace the probe.", `HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ${JSON.stringify([
10042
+ "node",
10043
+ "-e",
10044
+ health
10045
+ ])}`] : [],
10046
+ `CMD ${JSON.stringify(["node", ".output/server/index.mjs"])}`,
10047
+ ""
10048
+ ].join("\n");
10049
+ }
10050
+ /** Writes `Dockerfile` into the build output. It warns when the output has native packages that a Linux image cannot load. */
10051
+ async function writeDockerfile(build, output) {
10052
+ const platform = currentBuildPlatform();
10053
+ const nativePackages = await findNativePackages(output.serverDir);
10054
+ if (nativePackages.length && platform.os !== "linux") output.logger.warn(formatDiagnostic(viteHubErrorDiagnostics.VITE_HUB_DOCKERFILE_NATIVE_PACKAGES_NOT_LINUX({
10055
+ os: platform.os,
10056
+ packages: nativePackages.join(", ")
10057
+ })));
10058
+ const file = join(output.outputDir, "Dockerfile");
10059
+ await writeFile(file, renderDockerfile(resolveDockerfile({
10060
+ ...build,
10061
+ nativePackages,
10062
+ platform
10063
+ })), "utf8");
10064
+ return file;
10065
+ }
10066
+ //#endregion
10067
+ //#region src/cloudflare-vars.ts
10068
+ /**
10069
+ * The Worker `vars` for `cloudflare: { vars: true }`: each non-secret Server Env value read from a host variable, under
10070
+ * the name that holds it in `env`, the build environment. A name is tried in the order Server Env reads it at runtime.
10071
+ * Secrets, literals, providers, and values that are missing or empty stay out, so a default still applies at runtime.
10072
+ */
10073
+ function cloudflareServerEnvVars(registry, env) {
10074
+ const vars = [];
10075
+ const secretNames = /* @__PURE__ */ new Set();
10076
+ const visit = (value) => {
10077
+ if (!isRecord$1(value) || value.kind === "literal") return;
10078
+ const source = value.source;
10079
+ if (isRecord$1(source) && typeof value.secret === "boolean" && typeof value.required === "boolean") {
10080
+ if (source.kind !== "env") return;
10081
+ const names = (Array.isArray(source.names) ? source.names : [source.name]).filter((name) => typeof name === "string");
10082
+ if (value.secret) {
10083
+ for (const name of names) secretNames.add(name);
10084
+ return;
10085
+ }
10086
+ const name = names.find((name) => Object.hasOwn(env, name) && Boolean(env[name]));
10087
+ vars.push(name ? {
10088
+ names,
10089
+ binding: [name, env[name]]
10090
+ } : { names });
10091
+ return;
10092
+ }
10093
+ for (const child of Object.values(value)) visit(child);
10094
+ };
10095
+ visit(registry);
10096
+ return vars.map((entry) => entry.binding && secretNames.has(entry.binding[0]) ? { names: entry.names } : entry);
10097
+ }
10098
+ /**
10099
+ * Adds `vars` to the generated `wrangler.json` in `serverDir`, at the top level and in each `env`, since named
10100
+ * environments do not inherit vars. A var that the Wrangler config already sets keeps its value. Nitro writes no file
10101
+ * with `cloudflare.deployConfig: false`, and then there is nothing to add to.
10102
+ */
10103
+ async function addCloudflareVars(serverDir, vars) {
10104
+ if (!vars.some((entry) => entry.binding)) return;
10105
+ const file = resolve(serverDir, "wrangler.json");
10106
+ const text = await readFile(file, "utf8").catch((error) => {
10107
+ if (error.code === "ENOENT") return void 0;
10108
+ throw error;
10109
+ });
10110
+ if (text === void 0) return;
10111
+ const wrangler = JSON.parse(text);
10112
+ if (!isRecord$1(wrangler)) return;
10113
+ const withVars = (target) => {
10114
+ const explicit = isRecord$1(target.vars) ? target.vars : {};
10115
+ const hasExplicit = (name) => Object.hasOwn(explicit, name) && explicit[name] !== void 0 && explicit[name] !== "";
10116
+ const protectedNames = /* @__PURE__ */ new Set();
10117
+ const candidates = [];
10118
+ for (const { names, binding } of vars) {
10119
+ const explicitIndex = names.findIndex(hasExplicit);
10120
+ if (explicitIndex !== -1) for (const name of names.slice(0, explicitIndex)) protectedNames.add(name);
10121
+ else if (binding) candidates.push(binding);
10122
+ }
10123
+ const additions = candidates.filter(([name]) => !protectedNames.has(name));
10124
+ return {
10125
+ ...target,
10126
+ vars: {
10127
+ ...Object.fromEntries(additions),
10128
+ ...explicit
10129
+ }
10130
+ };
10131
+ };
10132
+ const result = withVars(wrangler);
10133
+ if (isRecord$1(wrangler.env)) result.env = Object.fromEntries(Object.entries(wrangler.env).map(([name, config]) => [name, isRecord$1(config) ? withVars(config) : config]));
10134
+ await writeFile(file, `${JSON.stringify(result, null, 2)}\n`);
10135
+ }
10136
+ //#endregion
9445
10137
  //#region src/nitro-order.ts
9446
10138
  const nitroConfigPlugins = [
9447
10139
  "nitro:init",
@@ -9719,7 +10411,7 @@ function viteHubDurabilityPlugin(options = {}) {
9719
10411
  //#endregion
9720
10412
  //#region src/browser-errors-vite.ts
9721
10413
  /** Below the app base. */
9722
- const browserErrorsRoute = "/api/_vitehub/browser-errors";
10414
+ const browserErrorsRoute = "/_vitehub/browser-errors";
9723
10415
  /**
9724
10416
  * The browser code that reports uncaught errors to `endpoint`, a JavaScript expression. It defines `report(kind, error)`
9725
10417
  * and listens to the window `error` and `unhandledrejection` events. It sends each message once and at most 10 reports
@@ -9763,7 +10455,7 @@ function browserErrorsNuxtPluginSource() {
9763
10455
  ].join("\n");
9764
10456
  }
9765
10457
  /**
9766
- * `observability.browserErrors`: the route `POST <base>/api/_vitehub/browser-errors`, and in a Vite app the reporter
10458
+ * `observability.browserErrors`: the route `POST <base>/_vitehub/browser-errors`, and in a Vite app the reporter
9767
10459
  * script in `index.html`. Nuxt renders its own HTML, so `installBrowserErrorsNuxt()` adds a client plugin instead.
9768
10460
  */
9769
10461
  function browserErrorsVitePlugin() {
@@ -9792,7 +10484,7 @@ function browserErrorsVitePlugin() {
9792
10484
  /** Adds the client plugin of `observability.browserErrors` to a Nuxt app. */
9793
10485
  async function installBrowserErrorsNuxt(nuxt, projectRoot) {
9794
10486
  const plugin = join(projectRoot, ".vitehub/browser-errors/nuxt-plugin.client.mjs");
9795
- await writeFileIfChanged$1(plugin, browserErrorsNuxtPluginSource());
10487
+ await writeFileIfChanged(plugin, browserErrorsNuxtPluginSource());
9796
10488
  const plugins = nuxt.options.plugins ??= [];
9797
10489
  if (!plugins.some((entry) => (typeof entry === "string" ? entry : entry.src) === plugin)) plugins.push(plugin);
9798
10490
  }
@@ -9813,7 +10505,7 @@ function renderLogsPlugin(projectRoot, source, options = {}) {
9813
10505
  ""
9814
10506
  ].join("\n");
9815
10507
  }
9816
- /** Installs the log source of `observability.logs`. The observability plugin registers Evlog. */
10508
+ /** Installs the log source of `vitehub({ logs })`. The observability plugin registers Evlog. */
9817
10509
  function logsVitePlugin(options) {
9818
10510
  return {
9819
10511
  name: "vite-hub/logs",
@@ -9825,7 +10517,7 @@ function logsVitePlugin(options) {
9825
10517
  const nitroValue = Reflect.get(config, "nitro");
9826
10518
  const kit = createNitroServerKit(nitroValue instanceof Object ? Object.fromEntries(Object.entries(nitroValue)) : void 0);
9827
10519
  const file = resolve(root, ".vitehub/nitro/logs/plugin.mjs");
9828
- await writeFileIfChanged$1(file, renderLogsPlugin(root, source, "source" in options ? {} : {
10520
+ await writeFileIfChanged(file, renderLogsPlugin(root, source, "source" in options ? {} : {
9829
10521
  maxEntries: options.maxEntries,
9830
10522
  maxEntryBytes: options.maxEntryBytes
9831
10523
  }));
@@ -9897,7 +10589,7 @@ async function writeIfChanged(file, contents) {
9897
10589
  }
9898
10590
  /**
9899
10591
  * Register the evlog Nitro module. With a service name, also register a generated plugin that installs
9900
- * `useObservability()`. `logs` is not read here: `logsVitePlugin()` installs the log source.
10592
+ * `useObservability()`. `logsVitePlugin()` installs the log source of `vitehub({ logs })`.
9901
10593
  */
9902
10594
  function observabilityVitePlugin(options, target = {}) {
9903
10595
  if (options.service !== void 0 && !options.service.trim()) throw viteHubErrorDiagnostics.VITE_HUB_R0125({ message: "[vitehub] observability.service must be a non-empty service name." });
@@ -9975,7 +10667,7 @@ const generatedOwnerPackageNames = Object.entries({
9975
10667
  "@vite-hub/connections": true,
9976
10668
  "@vite-hub/content": true,
9977
10669
  "@vite-hub/database": true,
9978
- "@vite-hub/decisions": true,
10670
+ "@vite-hub/choices": true,
9979
10671
  "@vite-hub/device": false,
9980
10672
  "@vite-hub/docs": true,
9981
10673
  "@vite-hub/email": true,
@@ -10301,9 +10993,27 @@ function outputRelativeArgument(outputDir, file) {
10301
10993
  const path = relative(outputDir, file).replaceAll("\\", "/");
10302
10994
  return /^[\w./-]+$/.test(path) ? `./${path}` : `./${shellQuote(path)}`;
10303
10995
  }
10304
- function deploymentNitroModule(plan, services, identity, sandboxTaskRequested, isDeployCommandOwned, resolvedBuildConfig, systemd, envPlugin, contributedEnv, envDir, deploy) {
10996
+ function applyCloudflareCompatibilityDate(options) {
10997
+ if (options._config?.compatibilityDate !== void 0 || options._c12?.layers?.some((layer) => layer.config?.compatibilityDate !== void 0)) return;
10998
+ const value = process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE;
10999
+ const date = value === "latest" ? /* @__PURE__ */ new Date() : new Date(value ?? "");
11000
+ const cloudflare = process.env.COMPATIBILITY_DATE_CLOUDFLARE && options.compatibilityDate.cloudflare;
11001
+ options.compatibilityDate = {
11002
+ default: Number.isNaN(date.getTime()) ? defaultCloudflareCompatibilityDate : date.toISOString().slice(0, 10),
11003
+ ...cloudflare ? { cloudflare } : {}
11004
+ };
11005
+ }
11006
+ function applyCloudflareNodeCompatOptOut(cloudflare, rootDir) {
11007
+ if (cloudflare.nodeCompat === false) return;
11008
+ if ([isRecord(cloudflare.wrangler) ? cloudflare.wrangler.compatibility_flags : void 0, readProjectWranglerConfig(rootDir)?.compatibility_flags].some((flags) => Array.isArray(flags) && flags.includes("no_nodejs_compat"))) cloudflare.nodeCompat = false;
11009
+ }
11010
+ function deploymentNitroModule(plan, services, identity, sandboxTaskRequested, isDeployCommandOwned, resolvedBuildConfig, systemd, docker, envPlugin, contributedEnv, envDir, deploy, cloudflareVars) {
10305
11011
  return (nitro) => {
10306
11012
  if (hostFromNitroPreset(nitro.options.preset) !== plan.host) return;
11013
+ if (plan.host === "cloudflare") {
11014
+ applyCloudflareCompatibilityDate(nitro.options);
11015
+ applyCloudflareNodeCompatOptOut(nitro.options.cloudflare ??= {}, nitro.options.rootDir);
11016
+ }
10307
11017
  if (plan.host === "cloudflare" && nitro.options.cloudflare?.deployConfig !== false && !isDeployCommandOwned()) {
10308
11018
  const config = outputRelativeArgument(nitro.options.output.dir, join(nitro.options.output.serverDir, "wrangler.json"));
10309
11019
  nitro.options.commands.deploy = `npx wrangler deploy --config ${config}${sandboxTaskRequested ? " --containers-rollout=gradual" : ""}`;
@@ -10321,7 +11031,10 @@ function deploymentNitroModule(plan, services, identity, sandboxTaskRequested, i
10321
11031
  nitro.hooks.hook("compiled", async () => {
10322
11032
  const outputDir = nitro.options.output.dir;
10323
11033
  const rootDir = nitro.options.rootDir;
10324
- if (plan.host === "cloudflare") await collapseWranglerConfigFile(nitro.options.output.serverDir);
11034
+ if (plan.host === "cloudflare") {
11035
+ await addCloudflareVars(nitro.options.output.serverDir, cloudflareVars());
11036
+ await collapseWranglerConfigFile(nitro.options.output.serverDir);
11037
+ }
10325
11038
  if (plan.output.packaging === "deno-node-modules") {
10326
11039
  invariant(serverPackages, "denoServerPackagesPlugin() sets the runtime packages when it writes the Deno server bundle");
10327
11040
  await finalizeDenoDeploymentOutput({
@@ -10354,6 +11067,11 @@ function deploymentNitroModule(plan, services, identity, sandboxTaskRequested, i
10354
11067
  });
10355
11068
  await writeSystemdUnit(outputDir, systemd.name, unit);
10356
11069
  }
11070
+ if (docker) await writeDockerfile(docker, {
11071
+ logger: nitro.logger,
11072
+ outputDir,
11073
+ serverDir: nitro.options.output.serverDir
11074
+ });
10357
11075
  });
10358
11076
  };
10359
11077
  }
@@ -10373,14 +11091,23 @@ function agentDrainMs(agent) {
10373
11091
  const drainMs = agent && agent !== true && agent.shutdown ? agent.shutdown.drainMs : void 0;
10374
11092
  return typeof drainMs === "number" && Number.isFinite(drainMs) && drainMs >= 0 ? drainMs : 0;
10375
11093
  }
10376
- /** A Node server has no host cron. Its Schedules run only in the Process Runtime or when the app wakes them itself. */
11094
+ /**
11095
+ * A Node server has no host cron, so its Schedules run in the Process Runtime unless the app sets `runtime` or chooses
11096
+ * another `providerOutput` itself.
11097
+ */
11098
+ function scheduleOptionsForHost(host, schedule) {
11099
+ const options = schedule === true ? {} : schedule;
11100
+ if (host !== "node" || options.runtime !== void 0 || (options.providerOutput ?? "auto") !== "auto") return options;
11101
+ return {
11102
+ ...options,
11103
+ runtime: { driver: "process" }
11104
+ };
11105
+ }
11106
+ /** `nitro` and `standalone` hand the wake to the host cron, which a Node server does not have. */
10377
11107
  function assertNodeScheduleWake(schedule) {
10378
- if (!schedule) return;
10379
- if (schedule !== true) {
10380
- if (schedule.providerOutput === false) return;
10381
- if (schedule.runtime !== void 0 && schedule.providerOutput !== "nitro" && schedule.providerOutput !== "standalone") return;
10382
- }
10383
- throw viteHubErrorDiagnostics.VITE_HUB_R0137({ message: "[vitehub] The \"node\" host has no cron, so this build would never run its Schedules. Set schedule: { runtime: { driver: \"process\" }, providerOutput: \"auto\" } to run them in the server process, or schedule: { providerOutput: false } to wake them yourself." });
11108
+ if (!schedule || schedule === true) return;
11109
+ if (schedule.providerOutput !== "nitro" && schedule.providerOutput !== "standalone") return;
11110
+ throw viteHubErrorDiagnostics.VITE_HUB_R0137({ message: `[vitehub] schedule.providerOutput "${schedule.providerOutput}" writes host cron output, but the "node" host has no cron, so this build would never run its Schedules. Remove providerOutput to run them in the server process, or set providerOutput: false to wake them yourself.` });
10384
11111
  }
10385
11112
  /**
10386
11113
  * Rejects the former `provider` key of the features whose driver `vitehub()` picks from the host. The host checks run
@@ -10498,6 +11225,7 @@ function deploymentPlugins(plan, requestedServices, blobEnabled, services, optio
10498
11225
  order: "post",
10499
11226
  handler(config, environment) {
10500
11227
  const building = environment.command === "build";
11228
+ if (isProductionBuild(config, environment)) assertEmailBuildDriver(plan.host, options.email);
10501
11229
  Reflect.set(config, VITEHUB_DEPLOYMENT_HOST, plan.host);
10502
11230
  for (const service of requestedServices) assertHostService(plan, service);
10503
11231
  if (building && plan.host === "node") assertNodeScheduleWake(options.schedule);
@@ -10608,6 +11336,22 @@ function deploymentPlugins(plan, requestedServices, blobEnabled, services, optio
10608
11336
  name: systemdUnitName(systemdOptions, name),
10609
11337
  options: systemdOptions
10610
11338
  } : void 0;
11339
+ const docker = plan.host === "node" && options.docker !== false ? {
11340
+ ...options.dataDir ? { dataDir: options.dataDir } : {},
11341
+ drainMs: agentDrainMs(options.agent),
11342
+ ...options.health ? { healthRoute: options.health === true ? defaultHealthRoute : options.health.route ?? "/_vitehub/health" } : {},
11343
+ name
11344
+ } : void 0;
11345
+ const viteRoot = resolve(config.root ?? process.cwd());
11346
+ const cloudflareVars = () => {
11347
+ const envPlugin = deploymentEnvPlugin.current;
11348
+ if (plan.host !== "cloudflare" || !options.cloudflare?.vars || !envPlugin) return [];
11349
+ const buildEnv = {
11350
+ ...loadAllEnv(loadEnv, environment.mode, envPlugin.api.resolveProjectRoot(viteRoot)),
11351
+ ...process.env
11352
+ };
11353
+ return cloudflareServerEnvVars(envPlugin.api.getServerEnvRegistry(), buildEnv);
11354
+ };
10611
11355
  const deploy = resolveDeployManifest({
10612
11356
  deploy: options.deploy,
10613
11357
  health: options.health,
@@ -10622,7 +11366,7 @@ function deploymentPlugins(plan, requestedServices, blobEnabled, services, optio
10622
11366
  maxAge: 3600
10623
11367
  }];
10624
11368
  }
10625
- const module = deploymentNitroModule(plan, services, identity, requestedServices.includes("sandbox"), () => deployCommandOwned, () => buildConfigRef.current, systemd, () => deploymentEnvPlugin.current, contributedEnv, () => resolvedEnvDir, deploy);
11369
+ const module = deploymentNitroModule(plan, services, identity, requestedServices.includes("sandbox"), () => deployCommandOwned, () => buildConfigRef.current, systemd, docker, () => deploymentEnvPlugin.current, contributedEnv, () => resolvedEnvDir, deploy, cloudflareVars);
10626
11370
  resolvedBuildConfigs.set(module, buildConfigRef);
10627
11371
  nitro.modules = [module, ...Array.isArray(nitro.modules) ? nitro.modules : []];
10628
11372
  if (plan.output.packaging === "deno-node-modules") {
@@ -10786,26 +11530,11 @@ function normalizePublicUrl(value) {
10786
11530
  return url.origin;
10787
11531
  }
10788
11532
  const addRuntimeNoExternal = createNoExternalAddition("@vite-hub/runtime");
10789
- /**
10790
- * Fails when the app defines Agents under `server/agents/` but leaves `agent` unset. Without the option, ViteHub
10791
- * generates no Agent routes or Agent State, and the app fails only when it first uses an Agent. A Vitest config runs no
10792
- * routes: its tests import the Agent Definitions that they check.
10793
- */
10794
- function agentOptionMissingPlugin() {
10795
- return {
10796
- name: "vite-hub/agent-option-missing",
10797
- async configResolved(config) {
10798
- if (process.env.VITEST || config.plugins.some((plugin) => plugin.name === "@vite-hub/agent/vite")) return;
10799
- const root = resolveViteHubProjectRoot(config.root);
10800
- const definition = (config["__vitehubServerDirs"] ?? [resolve(root, "server")]).flatMap((directory) => listSourceFiles(resolve(root, directory, "agents")))[0];
10801
- if (!definition) return;
10802
- throw viteHubErrorDiagnostics.VITE_HUB_AGENT_OPTION_MISSING({ message: `[vitehub] ${relative(root, definition)} defines an Agent, but the \`agent\` option is not set, so the app has no Agent routes or Agent State.` });
10803
- }
10804
- };
10805
- }
10806
11533
  function publicUrlPlugin(publicUrl, signedConsole) {
11534
+ const packageLoading = createNativePackageLoading();
10807
11535
  return {
10808
11536
  name: "vite-hub/public-url",
11537
+ nitro: packageLoading.nitro,
10809
11538
  ...typeof publicUrl === "string" ? { vitehub: { cli: () => ({
10810
11539
  namespaces: [],
10811
11540
  publicUrl: normalizePublicUrl(publicUrl)
@@ -10831,7 +11560,7 @@ function publicUrlPlugin(publicUrl, signedConsole) {
10831
11560
  return { define: { __VITEHUB_PUBLIC_URL__: define } };
10832
11561
  },
10833
11562
  configEnvironment(name, config, env) {
10834
- if (!isServerEnvironment(name, config) || loadsViteHubPackagesNatively(name, env)) return;
11563
+ if (!isServerEnvironment(name, config) || packageLoading.configureEnvironment(name, env)) return;
10835
11564
  const noExternal = addRuntimeNoExternal(config.resolve?.noExternal);
10836
11565
  if (noExternal) return { resolve: { noExternal } };
10837
11566
  }
@@ -10849,7 +11578,7 @@ function doctorPlugin() {
10849
11578
  * turns KV on for the head commits of the Sources. See `withCmsPresetPlugins()`.
10850
11579
  */
10851
11580
  /** Builds the ViteHub plugin list for one resolved feature configuration. */
10852
- function createViteHubPlugins(options) {
11581
+ function createViteHubPlugins(options, reportVersionError) {
10853
11582
  if (!options || typeof options !== "object") throw viteHubErrorDiagnostics.VITE_HUB_R0085({ message: "vitehub() requires an options object." });
10854
11583
  assertNoProviderKey(options);
10855
11584
  const host = resolveBuildHost(options.host);
@@ -10872,17 +11601,16 @@ function createViteHubPlugins(options) {
10872
11601
  if (configuredAgent?.runtime === "deno" || plan.host === "netlify") throw viteHubErrorDiagnostics.VITE_HUB_R0132({ message: "[vitehub] agent.invocations requires Nitro-hosted Agents. Netlify and Deno Agent output are not supported. Set agent.invocations to false and configure invocations on each Agent Definition." });
10873
11602
  }
10874
11603
  assertFeatureSupported("browser", plan.host, options);
10875
- assertFeatureSupported("email", plan.host, options);
10876
11604
  const sandboxTaskDriver = resolveSandboxTaskDriver(options.sandboxTask, plan);
10877
11605
  const sandboxTaskEnabled = sandboxTaskDriver !== void 0;
10878
11606
  const blobEnabled = Boolean(options.blob) && (plan.services.blob.supported || hasExplicitBlobStore(options.blob));
10879
11607
  const configuredQueue = options.queue && options.queue !== true ? options.queue : void 0;
10880
11608
  assertNodeQueueDriver(options.queue, plan.host);
10881
11609
  const observability = options.observability === true ? {} : options.observability || void 0;
10882
- const { logs: logsOption, browserErrors, ...observabilityOptions } = observability ?? {};
10883
- const observabilityLogs = logsOption === true ? {} : logsOption || void 0;
11610
+ const { browserErrors, ...observabilityOptions } = observability ?? {};
11611
+ const logs = options.logs === true ? {} : options.logs || void 0;
10884
11612
  const telemetry = Boolean(observabilityOptions.service);
10885
- const workflowEnabled = options.workflow !== false && Boolean(options.workflow || options.agent && plan.host !== "netlify");
11613
+ const workflowEnabled = Boolean(options.workflow);
10886
11614
  const enabledFeatures = [
10887
11615
  ["agent", options.agent || telemetry],
10888
11616
  ["auth", options.auth],
@@ -10906,7 +11634,7 @@ function createViteHubPlugins(options) {
10906
11634
  ["workflow", workflowEnabled],
10907
11635
  ["workspace", options.workspace]
10908
11636
  ].filter(([, enabled]) => enabled).map(([feature]) => feature);
10909
- assertFeaturePackages(enabledFeatures, hostFeaturePackages(enabledFeatures, plan.host, options));
11637
+ assertFeaturePackages(enabledFeatures, hostFeaturePackages(enabledFeatures, plan.host, options), reportVersionError);
10910
11638
  const { blobVite, browserVite, channelsVite, connectionsVite, emailVite, kvVite, markdownTemplateVite, queueVite, rateLimitVite, sandboxTaskVite, workflowVite } = ownerModules;
10911
11639
  const configuredBlob = blobEnabled ? hostBlobOptions(plan, options.blob) : void 0;
10912
11640
  const resolvedConsoleBlob = configuredBlob ? requireOptionalOwner(blobVite, "blob").resolveBlobViteConfig(configuredBlob, { hosting: plan.nitroPreset }).blob : false;
@@ -10915,7 +11643,6 @@ function createViteHubPlugins(options) {
10915
11643
  ...options,
10916
11644
  env: options.env !== false,
10917
11645
  blob: blobEnabled,
10918
- host: plan.host,
10919
11646
  sandboxTask: sandboxTaskEnabled
10920
11647
  });
10921
11648
  const plugins = [
@@ -10960,10 +11687,11 @@ function createViteHubPlugins(options) {
10960
11687
  }
10961
11688
  plugins.push(...deploymentPlugins(plan, requestedServices, blobEnabled, manifestServices, options, envPlugin));
10962
11689
  plugins.push(publicUrlPlugin(options.publicUrl, Boolean(configuredConsole) && configuredConsole?.auth !== false));
10963
- if (options.agent === void 0) plugins.push(agentOptionMissingPlugin());
10964
11690
  plugins.push(devDefinesVitePlugin());
10965
11691
  plugins.push(standardContextVitePlugin());
10966
11692
  plugins.push(vitestInlinePlugin());
11693
+ if (plan.host === "cloudflare") plugins.push(cloudflareNodeDevPlugin());
11694
+ plugins.push(forgeBuildCheckPlugin());
10967
11695
  const providerImportAliases = {};
10968
11696
  const configuredKV = options.kv && options.kv !== true ? options.kv : void 0;
10969
11697
  const kvHosting = options.kv ? plan.nitroPreset : void 0;
@@ -10989,15 +11717,13 @@ function createViteHubPlugins(options) {
10989
11717
  }));
10990
11718
  if (plan.host === "cloudflare") plugins.push(cloudflareShSyntaxPlugin(), cloudflarePkceChallengePlugin(), cloudflareRedirectsFileVitePlugin());
10991
11719
  plugins.push(frameworkDependencyResolver(options, envPlugin, providerImportAliases, blobEnabled, configuredKV, kvHosting));
10992
- const evlogRegistered = Boolean(observability) && (telemetry || !(observabilityLogs && "source" in observabilityLogs));
10993
- if (observability) {
10994
- if (observabilityOptions.papercuts && !(configuredConsole && options.agent)) throw viteHubErrorDiagnostics.VITE_HUB_R0127({ message: "[vitehub] observability.papercuts stores reports in the Console invocation journal. Enable agent and console." });
10995
- if (evlogRegistered) plugins.push(observabilityVitePlugin(observabilityOptions, {
10996
- agent: options.agent,
10997
- hosting: plan.nitroPreset
10998
- }));
10999
- }
11000
- if (observabilityLogs) plugins.push(logsVitePlugin(observabilityLogs));
11720
+ const evlogRegistered = Boolean(observability) || Boolean(logs && !("source" in logs));
11721
+ if (observabilityOptions.papercuts && !(configuredConsole && options.agent)) throw viteHubErrorDiagnostics.VITE_HUB_R0127({ message: "[vitehub] observability.papercuts stores reports in the Console invocation journal. Enable agent and console." });
11722
+ if (evlogRegistered) plugins.push(observabilityVitePlugin(observabilityOptions, {
11723
+ agent: options.agent,
11724
+ hosting: plan.nitroPreset
11725
+ }));
11726
+ if (logs) plugins.push(logsVitePlugin(logs));
11001
11727
  if (browserErrors) plugins.push(browserErrorsVitePlugin());
11002
11728
  if (!evlogRegistered || observabilityOptions.evlog?.enabled === false) plugins.push(errorLogVitePlugin());
11003
11729
  const security = resolveSecurityPolicy(options.security);
@@ -11039,7 +11765,7 @@ function createViteHubPlugins(options) {
11039
11765
  databaseDiscoveryRoot: options.database && options.database !== true ? options.database.projectRoot : void 0,
11040
11766
  rateLimitDiscoveryRoot: options.rateLimit && options.rateLimit !== true ? options.rateLimit.projectRoot : void 0,
11041
11767
  rateLimitScanDirs: options.rateLimit && options.rateLimit !== true ? options.rateLimit.scanDirs : void 0,
11042
- resolveAuthConfig: options.auth ? (root, serverDirs) => requireOptionalOwner(ownerModules.authVite, "auth").resolveAuthViteConfig(options.auth === true ? void 0 : options.auth, root, { serverDirs }) : void 0,
11768
+ resolveAuthConfig: options.auth ? (root, serverDirs) => requireOptionalOwner(ownerModules.authVite, "auth").resolveAuthViteConfig(void 0, root, { serverDirs }) : void 0,
11043
11769
  resolveBlobStores: (blob) => {
11044
11770
  if (blob === false) return false;
11045
11771
  if (blob === void 0 && !options.blob) return false;
@@ -11064,7 +11790,7 @@ function createViteHubPlugins(options) {
11064
11790
  plugins.push(consolePlugin);
11065
11791
  if (options.agent && !devOperationsOnly) plugins.push(consoleInvocationRootPlugin(invocationRootState));
11066
11792
  }
11067
- if (options.auth) plugins.push(requireOptionalOwner(ownerModules.authVite, "auth").hubAuth(options.auth === true ? {} : options.auth || false, { importBase: "vite-hub/auth" }));
11793
+ if (options.auth) plugins.push(requireOptionalOwner(ownerModules.authVite, "auth").hubAuth(options.auth === true ? void 0 : options.auth, { importBase: "vite-hub/auth" }));
11068
11794
  if (sandboxTaskEnabled) {
11069
11795
  const sandboxTaskPluginOptions = {
11070
11796
  ...options.sandboxTask === true ? {} : options.sandboxTask,
@@ -11089,6 +11815,7 @@ function createViteHubPlugins(options) {
11089
11815
  }));
11090
11816
  plugins.push(requireOptionalOwner(ownerModules.agentVite, "agent").hubAgent({
11091
11817
  ...agentOptions,
11818
+ channelProjectRoot: typeof options.channels === "object" ? options.channels.projectRoot : void 0,
11092
11819
  kvImport: "vite-hub/kv",
11093
11820
  processDiscordGateway: plan.host === "node",
11094
11821
  providerImportAliases,
@@ -11096,10 +11823,10 @@ function createViteHubPlugins(options) {
11096
11823
  ...runtimeCapabilityImports,
11097
11824
  auth: "vite-hub/auth/agent"
11098
11825
  },
11099
- ...workflowEnabled ? { workflowModules: {
11826
+ workflowModules: workflowEnabled ? {
11100
11827
  index: "vite-hub/workflow",
11101
11828
  state: requireOptionalOwner(workflowVite, "workflow").workflowRuntimeModule("state")
11102
- } } : {},
11829
+ } : false,
11103
11830
  workspaceDependencyRuntimeImports
11104
11831
  }));
11105
11832
  }
@@ -11121,7 +11848,7 @@ function createViteHubPlugins(options) {
11121
11848
  presetDriver: (blob) => Boolean(blob && hostBlobConfigs.has(blob))
11122
11849
  })));
11123
11850
  if (options.email) {
11124
- const emailOptions = options.email === true ? { driver: "cloudflare" } : options.email;
11851
+ const emailOptions = options.email === true ? { driver: defaultEmailDriver(plan.host) } : options.email;
11125
11852
  plugins.push(requireOptionalOwner(emailVite, "email").hubEmail({
11126
11853
  ...emailOptions,
11127
11854
  hosting: plan.nitroPreset,
@@ -11216,24 +11943,25 @@ function createViteHubPlugins(options) {
11216
11943
  }));
11217
11944
  if (options.schedule) plugins.push(requireOptionalOwner(ownerModules.scheduleVite, "schedule").hubSchedule({
11218
11945
  ...plan.host === "vercel" || plan.host === "deno" ? { providerOutput: "standalone" } : {},
11219
- ...options.schedule === true ? {} : options.schedule,
11946
+ ...scheduleOptionsForHost(plan.host, options.schedule),
11220
11947
  databaseImport: "vite-hub/database",
11221
11948
  importBase: "vite-hub/schedule",
11222
- providerImportAliases
11949
+ providerImportAliases,
11950
+ requireKVPluginForProcessStores: true
11223
11951
  }));
11224
11952
  if (workflowEnabled) plugins.push(requireOptionalOwner(workflowVite, "workflow").hubWorkflow(options.workflow && options.workflow !== true ? options.workflow : {}, {
11225
11953
  databaseImport: "vite-hub/database",
11226
11954
  hosting: plan.nitroPreset,
11227
11955
  importBase: "vite-hub/workflow",
11228
- ...options.workflow === void 0 ? { implicitlyEnabled: true } : {},
11229
11956
  providerImportAliases,
11230
- includeUserAppEntry: options.workflow !== void 0 && options.workflow !== false,
11957
+ includeUserAppEntry: true,
11231
11958
  workspaceDependencyRuntimeImports,
11232
11959
  workspaceRuntimeModule: options.agent ? requireOptionalOwner(ownerModules.agentVite, "agent").agentRuntimeModule("internal/workspace/runtime") : "vite-hub/workspace/runtime"
11233
11960
  }));
11234
11961
  if (options.workspace) plugins.push(requireOptionalOwner(ownerModules.workspaceVite, "workspace").hubWorkspace({
11235
11962
  ...options.workspace === true ? {} : options.workspace,
11236
- hosting: plan.nitroPreset
11963
+ hosting: plan.nitroPreset,
11964
+ assertGitHubStoreAvailable: () => assertFeaturePackages(["forge"])
11237
11965
  }));
11238
11966
  if (options.seo?.sitemap || options.seo?.robots) plugins.push(viteHubSeoPlugin(options.seo, typeof options.publicUrl === "string" ? normalizePublicUrl(options.publicUrl) : void 0));
11239
11967
  const sourcePlugin = hubSource({
@@ -11241,9 +11969,11 @@ function createViteHubPlugins(options) {
11241
11969
  sitemap: Boolean(options.seo.sitemap),
11242
11970
  robots: options.seo.robots !== false
11243
11971
  } } : {},
11244
- auth: options.auth ? ({ projectRoot, serverDirs }) => Boolean(requireOptionalOwner(ownerModules.authVite, "auth").resolveAuthViteConfig(options.auth === true ? void 0 : options.auth, projectRoot, { serverDirs })) : false,
11972
+ auth: options.auth ? ({ projectRoot, serverDirs }) => Boolean(requireOptionalOwner(ownerModules.authVite, "auth").resolveAuthViteConfig(void 0, projectRoot, { serverDirs })) : false,
11245
11973
  contentImportBase: "vite-hub/content",
11246
- importBase: "vite-hub/source"
11974
+ importBase: "vite-hub/source",
11975
+ queue: Boolean(options.queue) && plan.services.queue.supported && plan.host !== "vercel",
11976
+ queueImport: "vite-hub/queue"
11247
11977
  });
11248
11978
  plugins.push(sourcePlugin);
11249
11979
  if (ownerModules.contentVite) plugins.push(ownerModules.contentVite.hubContent({
@@ -11317,9 +12047,24 @@ function createViteHubPlugins(options) {
11317
12047
  * The ViteHub plugins without Nitro. `vitehub()` adds Nitro's Vite plugin to them. `vite-hub/nuxt` uses them as they
11318
12048
  * are, because Nuxt runs its own Nitro, so it never loads `nitro/vite`.
11319
12049
  */
11320
- function viteHubPlugins(options) {
12050
+ function viteHubPlugins(options, reportVersionError = true) {
11321
12051
  assertNoRemovedViteHubOptions(options, "`vitehub()`");
11322
- return withCmsPresetPlugins(withComments(options), (resolved) => withPrintedDiagnostics(createViteHubPlugins(resolved)));
12052
+ const create = (resolved) => withCmsPresetPlugins(withComments(resolved), (variant) => withPrintedDiagnostics(createViteHubPlugins(variant, reportVersionError)));
12053
+ if (featureOptionsResolved(options)) return create(options);
12054
+ const project = {
12055
+ projectRoot: resolveViteHubProjectRoot(process.cwd()),
12056
+ viteRoot: process.cwd()
12057
+ };
12058
+ const rootPlugin = (validate) => withPrintedDiagnostics(definitionFeaturesRootPlugin(options, project, validate));
12059
+ try {
12060
+ const resolved = resolveDefinitionFeatures(options, project);
12061
+ if (resolved !== options) return [...create(resolved), rootPlugin()];
12062
+ } catch (error) {
12063
+ return [rootPlugin(() => {
12064
+ throw error;
12065
+ })];
12066
+ }
12067
+ return [...create(options), rootPlugin()];
11323
12068
  }
11324
12069
  //#endregion
11325
- export { defaultDatabaseD1Binding as $, assertAgentInvocationsRetention as A, redisDriverSpecifier as B, discoverConsoleEntrySections as C, cloudflareEmailDevShimSource as D, staleChunkReloadPluginName as E, disabledKVConfigModule as F, hostFromNitroPreset as G, markCmsPresetFeaturesResolved as H, disabledRedisDriver as I, resolveDeploymentPlan as J, normalizeNitroPreset as K, disabledUpstashDriver as L, defaultJournalNeedsLibsql as M, writeAgentInvocationsNitroPlugin as N, cloudflareWorkersDevShimSource as O, generatedModules as P, agentJournalStateUrl as Q, hasRedisStore as R, consoleDocumentEditorSectionIds as S, installStaleChunkReloadNuxt as T, resolveCmsPresetFeatures as U, upstashDriverSpecifier as V, detectHost as W, nitroCacheBypass as X, writeFileIfChanged$1 as Y, describeDeploymentPlanOutput as Z, serializeConsoleRefresh as _, assertConsoleAccess as a, ownerModules as at, discoverConsoleBuildCatalog as b, consoleOperationContributions as c, VITEHUB_APP_BASE_URL as ct, resolveConsoleOptions as d, VITEHUB_PREPARE as dt, withComments as et, resolveGeneratedConsolePlugin as f, VITEHUB_PROJECT_ROOT as ft, addConsoleRpcHandler as g, resolveViteHubProjectRoot as gt, addConsoleAppRoutes as h, resolveNuxtServerDirs as ht, cloudflareExportConditions as i, hasSyncDirectory as it, assertAgentInvocationsUrl as j, VITEHUB_AGENT_JOURNAL_D1 as k, generatedConsolePluginRegistration as l, VITEHUB_GENERATED_ROOT as lt, consoleOperationFeatures as m, getResolvedFeatureOptions as mt, viteHubPlugins as n, withDataDir as nt, assertConsoleProductionAuth as o, isIncludedNitroPlugin as ot, consoleDevAccessNotice as p, VITEHUB_SERVER_DIRS as pt, resolveBuildHost as q, installBrowserErrorsNuxt as r, isDefaultAgentJournal as rt, consoleInvocationRootPlugin as s, markIncludedNitroPlugin as st, resolveSandboxTaskDriver as t, withConnectionsDatabase as tt, resolveConsoleAccessBuild as u, VITEHUB_NITRO_CONFIG_CONTEXT as ut, writeConsoleNitroPlugin as v, isConsoleContributedSectionId as w, consoleContributedSections as x, resolveConsoleProjectName as y, hasUpstashStore as z };
12070
+ export { nitroCacheBypass as $, cloudflareWorkersDevShimSource as A, hasRedisStore as B, consoleDocumentEditorSectionIds as C, resolveViteHubProjectRoot as Ct, staleChunkReloadPluginName as D, installStaleChunkReloadNuxt as E, writeAgentInvocationsNitroPlugin as F, writeFileIfChanged as G, redisDriverSpecifier as H, generatedModules as I, detectHost as J, markCmsPresetFeaturesResolved as K, disabledKVConfigModule as L, assertAgentInvocationsRetention as M, assertAgentInvocationsUrl as N, forgeBuildCheckPlugin as O, defaultJournalNeedsLibsql as P, resolveDeploymentPlan as Q, disabledRedisDriver as R, consoleContributedSections as S, resolveNuxtServerDirs as St, isConsoleContributedSectionId as T, upstashDriverSpecifier as U, hasUpstashStore as V, resolveDefinitionFeatures as W, normalizeNitroPreset as X, hostFromNitroPreset as Y, resolveBuildHost as Z, addConsoleRpcHandler as _, VITEHUB_NITRO_CONFIG_CONTEXT as _t, cloudflareExportConditions as a, defaultDatabaseD1Binding as at, resolveConsoleProjectName as b, VITEHUB_SERVER_DIRS as bt, consoleInvocationRootPlugin as c, withDataDir as ct, resolveConsoleAccessBuild as d, ownerModules as dt, describeDeploymentPlanOutput as et, resolveConsoleOptions as f, isIncludedNitroPlugin as ft, addConsoleAppRoutes as g, VITEHUB_GENERATED_ROOT as gt, consoleOperationFeatures as h, VITEHUB_APP_BASE_URL as ht, installBrowserErrorsNuxt as i, agentJournalStateUrl as it, VITEHUB_AGENT_JOURNAL_D1 as j, cloudflareEmailDevShimSource as k, consoleOperationContributions as l, isDefaultAgentJournal as lt, consoleDevAccessNotice as m, withShortInspect as mt, resolveSandboxTaskDriver as n, reportViteHubHint as nt, assertConsoleAccess as o, withComments as ot, resolveGeneratedConsolePlugin as p, markIncludedNitroPlugin as pt, resolveCmsPresetFeatures as q, viteHubPlugins as r, startViteHubHints as rt, assertConsoleProductionAuth as s, withConnectionsDatabase as st, applyCloudflareNodeCompatOptOut as t, VITEHUB_NUXT_HINTS as tt, generatedConsolePluginRegistration as u, hasSyncDirectory as ut, serializeConsoleRefresh as v, VITEHUB_PREPARE as vt, discoverConsoleEntrySections as w, discoverConsoleBuildCatalog as x, getResolvedFeatureOptions as xt, writeConsoleNitroPlugin as y, VITEHUB_PROJECT_ROOT as yt, disabledUpstashDriver as z };