@pyric/cli 0.1.0-alpha.11 → 0.1.0-alpha.13

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 (424) hide show
  1. package/dist/cli/serve.js +4 -4
  2. package/dist/cli/serve.js.map +1 -1
  3. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  4. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  5. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  6. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  7. package/dist/conformance/.generated/can-i-use.js +2 -2
  8. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  9. package/dist/serve/bundler.d.ts +13 -8
  10. package/dist/serve/bundler.d.ts.map +1 -1
  11. package/dist/serve/bundler.js +31 -36
  12. package/dist/serve/bundler.js.map +1 -1
  13. package/dist/serve/docs-ui/docs/_rhythm/index.html +1 -1
  14. package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +1 -1
  15. package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +1 -1
  16. package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +1 -1
  17. package/dist/serve/docs-ui/docs/ai-compat/index.html +1 -1
  18. package/dist/serve/docs-ui/docs/api-reference/index.html +2 -2
  19. package/dist/serve/docs-ui/docs/api-reference.md +1 -1
  20. package/dist/serve/docs-ui/docs/app-compat/index.html +1 -1
  21. package/dist/serve/docs-ui/docs/auth-compat/index.html +1 -1
  22. package/dist/serve/docs-ui/docs/build/ai-logic/index.html +44 -22
  23. package/dist/serve/docs-ui/docs/build/ai-logic.md +69 -21
  24. package/dist/serve/docs-ui/docs/build/authentication/index.html +1 -1
  25. package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +1 -1
  26. package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +1 -1
  27. package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +1 -1
  28. package/dist/serve/docs-ui/docs/build/realtime-database/index.html +1 -1
  29. package/dist/serve/docs-ui/docs/conformance-scores/index.html +1 -1
  30. package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +1 -1
  31. package/dist/serve/docs-ui/docs/database-compat/index.html +1 -1
  32. package/dist/serve/docs-ui/docs/firestore-compat/index.html +1 -1
  33. package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +1 -1
  34. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +2 -1
  35. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works.md +2 -0
  36. package/dist/serve/docs-ui/docs/get-started/start-building/index.html +3 -2
  37. package/dist/serve/docs-ui/docs/get-started/start-building.md +3 -1
  38. package/dist/serve/docs-ui/docs/index.json +349 -29
  39. package/dist/serve/docs-ui/docs/messaging-compat/index.html +1 -1
  40. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status/index.html +28 -0
  41. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status.md +47 -0
  42. package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +1 -1
  43. package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +1 -1
  44. package/dist/serve/docs-ui/docs/overview/index.html +1 -1
  45. package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  46. package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  47. package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  48. package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  49. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api/index.html +916 -0
  50. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api.md +706 -0
  51. package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  52. package/dist/serve/docs-ui/docs/pyric-ai-reference-api/index.html +1 -1
  53. package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  54. package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +1 -1
  55. package/dist/serve/docs-ui/docs/pyric-auth-reference-api/index.html +1 -1
  56. package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  57. package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  58. package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  59. package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  60. package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
  61. package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  62. package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
  63. package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  64. package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  65. package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  66. package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  67. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api/index.html +168 -76
  68. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api.md +156 -73
  69. package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  70. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +11 -8
  71. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api.md +17 -4
  72. package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +1 -1
  73. package/dist/serve/docs-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  74. package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  75. package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  76. package/dist/serve/docs-ui/docs/pyric-rules-reference-api/index.html +1 -1
  77. package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  78. package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  79. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api/index.html +37 -14
  80. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api.md +28 -8
  81. package/dist/serve/docs-ui/docs/pyric-storage-reference-api/index.html +1 -1
  82. package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  83. package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  84. package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  85. package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  86. package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  87. package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  88. package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  89. package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  90. package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  91. package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  92. package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
  93. package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  94. package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  95. package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  96. package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  97. package/dist/serve/docs-ui/docs/rules-compat/index.html +1 -1
  98. package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +1 -1
  99. package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  100. package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +1 -1
  101. package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  102. package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +1 -1
  103. package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  104. package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +1 -1
  105. package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  106. package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +1 -1
  107. package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +1 -1
  108. package/dist/serve/docs-ui/docs/storage-compat/index.html +1 -1
  109. package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  110. package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  111. package/dist/serve/docs-ui/docs/tutorial/index.html +429 -0
  112. package/dist/serve/docs-ui/docs/tutorial.md +701 -0
  113. package/dist/serve/docs-ui/llms.txt +3 -1
  114. package/dist/serve/entries/init.d.ts.map +1 -1
  115. package/dist/serve/entries/init.js +3 -0
  116. package/dist/serve/entries/init.js.map +1 -1
  117. package/dist/serve/entries/runtime.d.ts.map +1 -1
  118. package/dist/serve/entries/runtime.js +20 -5
  119. package/dist/serve/entries/runtime.js.map +1 -1
  120. package/dist/serve/entries/worker-runtime.d.ts +2 -2
  121. package/dist/serve/entries/worker-runtime.d.ts.map +1 -1
  122. package/dist/serve/entries/worker-runtime.js +45 -10
  123. package/dist/serve/entries/worker-runtime.js.map +1 -1
  124. package/dist/serve/runtime/chip-config.d.ts +19 -0
  125. package/dist/serve/runtime/chip-config.d.ts.map +1 -0
  126. package/dist/serve/runtime/chip-config.js +19 -0
  127. package/dist/serve/runtime/chip-config.js.map +1 -0
  128. package/dist/serve/runtime/chip-install.d.ts +10 -0
  129. package/dist/serve/runtime/chip-install.d.ts.map +1 -0
  130. package/dist/serve/runtime/chip-install.js +15 -0
  131. package/dist/serve/runtime/chip-install.js.map +1 -0
  132. package/dist/serve/runtime/chip.d.ts +17 -0
  133. package/dist/serve/runtime/chip.d.ts.map +1 -0
  134. package/dist/serve/runtime/chip.js +257 -0
  135. package/dist/serve/runtime/chip.js.map +1 -0
  136. package/dist/serve/runtime/manifest.d.ts +22 -0
  137. package/dist/serve/runtime/manifest.d.ts.map +1 -0
  138. package/dist/serve/runtime/manifest.js +20 -0
  139. package/dist/serve/runtime/manifest.js.map +1 -0
  140. package/dist/serve/runtime/status.d.ts +49 -0
  141. package/dist/serve/runtime/status.d.ts.map +1 -0
  142. package/dist/serve/runtime/status.js +164 -0
  143. package/dist/serve/runtime/status.js.map +1 -0
  144. package/dist/serve/runtime/worker-connection.d.ts +4 -0
  145. package/dist/serve/runtime/worker-connection.d.ts.map +1 -0
  146. package/dist/serve/runtime/worker-connection.js +11 -0
  147. package/dist/serve/runtime/worker-connection.js.map +1 -0
  148. package/dist/serve/runtime/worker-generation.d.ts +14 -0
  149. package/dist/serve/runtime/worker-generation.d.ts.map +1 -0
  150. package/dist/serve/runtime/worker-generation.js +56 -0
  151. package/dist/serve/runtime/worker-generation.js.map +1 -0
  152. package/dist/serve/runtime/worker-replacement.d.ts +18 -0
  153. package/dist/serve/runtime/worker-replacement.d.ts.map +1 -0
  154. package/dist/serve/runtime/worker-replacement.js +29 -0
  155. package/dist/serve/runtime/worker-replacement.js.map +1 -0
  156. package/dist/serve/standalone-assets.d.ts +2 -2
  157. package/dist/serve/standalone-assets.d.ts.map +1 -1
  158. package/dist/serve/standalone-assets.js +1 -1
  159. package/dist/serve/standalone-assets.js.map +1 -1
  160. package/dist/serve/studio-ui/assets/{RulesCodeEditor-CxVYcZXw.js → RulesCodeEditor-BDlH-5lp.js} +1 -1
  161. package/dist/serve/studio-ui/assets/{index-cpSfgQ7H.js → index-Bf9SSE8L.js} +5 -5
  162. package/dist/serve/studio-ui/assets/{seed-DeuFKi4J.js → seed-D_UjxfOU.js} +1 -1
  163. package/dist/serve/studio-ui/index.html +1 -1
  164. package/dist/serve/vite-ai-config.d.ts +25 -0
  165. package/dist/serve/vite-ai-config.d.ts.map +1 -0
  166. package/dist/serve/vite-ai-config.js +45 -0
  167. package/dist/serve/vite-ai-config.js.map +1 -0
  168. package/dist/serve/vite-plugin.d.ts +17 -36
  169. package/dist/serve/vite-plugin.d.ts.map +1 -1
  170. package/dist/serve/vite-plugin.js +38 -57
  171. package/dist/serve/vite-plugin.js.map +1 -1
  172. package/dist/serve/vite-rules-source.d.ts +8 -0
  173. package/dist/serve/vite-rules-source.d.ts.map +1 -0
  174. package/dist/serve/vite-rules-source.js +23 -0
  175. package/dist/serve/vite-rules-source.js.map +1 -0
  176. package/dist/serve/vite-worker-runtime.d.ts +20 -0
  177. package/dist/serve/vite-worker-runtime.d.ts.map +1 -0
  178. package/dist/serve/vite-worker-runtime.js +25 -0
  179. package/dist/serve/vite-worker-runtime.js.map +1 -0
  180. package/dist/serve/worker/client/connection.d.ts +7 -2
  181. package/dist/serve/worker/client/connection.d.ts.map +1 -1
  182. package/dist/serve/worker/client/connection.js +13 -16
  183. package/dist/serve/worker/client/connection.js.map +1 -1
  184. package/dist/serve/worker/client/core.d.ts +7 -0
  185. package/dist/serve/worker/client/core.d.ts.map +1 -1
  186. package/dist/serve/worker/client/core.js +28 -0
  187. package/dist/serve/worker/client/core.js.map +1 -1
  188. package/dist/serve/worker/client/runtime-control.d.ts +8 -0
  189. package/dist/serve/worker/client/runtime-control.d.ts.map +1 -0
  190. package/dist/serve/worker/client/runtime-control.js +11 -0
  191. package/dist/serve/worker/client/runtime-control.js.map +1 -0
  192. package/dist/serve/worker/entry.js +44 -2
  193. package/dist/serve/worker/entry.js.map +1 -1
  194. package/dist/serve/worker/host/core.js +1 -1
  195. package/dist/serve/worker/host/core.js.map +1 -1
  196. package/dist/serve/worker/host/firestore-writes.d.ts.map +1 -1
  197. package/dist/serve/worker/host/firestore-writes.js +3 -2
  198. package/dist/serve/worker/host/firestore-writes.js.map +1 -1
  199. package/dist/serve/worker/host/studio.js +1 -1
  200. package/dist/serve/worker/host/studio.js.map +1 -1
  201. package/dist/serve/worker/host-context.d.ts +1 -1
  202. package/dist/serve/worker/host-context.d.ts.map +1 -1
  203. package/dist/serve/worker/index.d.ts +2 -1
  204. package/dist/serve/worker/index.d.ts.map +1 -1
  205. package/dist/serve/worker/index.js +2 -1
  206. package/dist/serve/worker/index.js.map +1 -1
  207. package/dist/serve/worker/protocol.d.ts +15 -1
  208. package/dist/serve/worker/protocol.d.ts.map +1 -1
  209. package/dist/serve/worker/protocol.js +2 -2
  210. package/dist/serve/worker/protocol.js.map +1 -1
  211. package/dist/serve/worker/retirement.d.ts +21 -0
  212. package/dist/serve/worker/retirement.d.ts.map +1 -0
  213. package/dist/serve/worker/retirement.js +97 -0
  214. package/dist/serve/worker/retirement.js.map +1 -0
  215. package/dist/serve/worker/serve-init.d.ts.map +1 -1
  216. package/dist/serve/worker/serve-init.js +5 -6
  217. package/dist/serve/worker/serve-init.js.map +1 -1
  218. package/dist/vite.d.ts +1 -0
  219. package/dist/vite.d.ts.map +1 -1
  220. package/dist/vite.js.map +1 -1
  221. package/package.json +6 -4
  222. package/src/assurance/.generated/conformance-verdicts.ts +1090 -0
  223. package/src/assurance/attachment.ts +211 -0
  224. package/src/assurance/browser.ts +80 -0
  225. package/src/assurance/campaign.ts +496 -0
  226. package/src/assurance/capabilities.ts +446 -0
  227. package/src/assurance/cases.ts +43 -0
  228. package/src/assurance/index.ts +75 -0
  229. package/src/assurance/runner.ts +885 -0
  230. package/src/assurance/tool-names.ts +15 -0
  231. package/src/assurance/tools.ts +830 -0
  232. package/src/assurance/types.ts +352 -0
  233. package/src/assurance/validation.ts +434 -0
  234. package/src/bridge/client/bridge.ts +550 -0
  235. package/src/bridge/client/dispatch.ts +137 -0
  236. package/src/bridge/client.ts +45 -0
  237. package/src/bridge/protocol.ts +351 -0
  238. package/src/bridge/server/audit.ts +53 -0
  239. package/src/bridge/server/bridge.ts +597 -0
  240. package/src/bridge/server/headless.ts +160 -0
  241. package/src/bridge/server/json-schema-to-zod.ts +108 -0
  242. package/src/bridge/server/local-bridge.ts +66 -0
  243. package/src/bridge/server/logger.ts +50 -0
  244. package/src/bridge/server/mcp-contract.ts +93 -0
  245. package/src/bridge/server/mcp.ts +129 -0
  246. package/src/bridge/server/peer.ts +232 -0
  247. package/src/bridge/server/standalone.ts +347 -0
  248. package/src/bridge/server/tool-metadata.ts +99 -0
  249. package/src/bridge/server.ts +28 -0
  250. package/src/cli/can-i-use.ts +50 -0
  251. package/src/cli/cli.test.ts +493 -0
  252. package/src/cli/database-rules.ts +329 -0
  253. package/src/cli/dev-runner.ts +282 -0
  254. package/src/cli/firebase-json.ts +100 -0
  255. package/src/cli/firestore-indexes.ts +70 -0
  256. package/src/cli/index.ts +425 -0
  257. package/src/cli/init.ts +260 -0
  258. package/src/cli/mcp-proxy.ts +196 -0
  259. package/src/cli/parse-args.ts +80 -0
  260. package/src/cli/rules.ts +259 -0
  261. package/src/cli/scope.ts +67 -0
  262. package/src/cli/serve.ts +996 -0
  263. package/src/cli/service-commands.ts +73 -0
  264. package/src/cli/snapshot.ts +164 -0
  265. package/src/cli/storage-rules.ts +172 -0
  266. package/src/cli/verify.ts +416 -0
  267. package/src/conformance/.generated/can-i-use-browser.ts +113 -0
  268. package/src/conformance/.generated/can-i-use.ts +117 -0
  269. package/src/conformance/.generated/conformance-docs.ts +14 -0
  270. package/src/conformance/browser.ts +24 -0
  271. package/src/conformance/can-i-use-tool.ts +51 -0
  272. package/src/conformance/can-i-use.ts +18 -0
  273. package/src/conformance/docs.ts +8 -0
  274. package/src/conformance/index.ts +20 -0
  275. package/src/conformance/tools.ts +16 -0
  276. package/src/credentials/core/memoize-ttl.ts +142 -0
  277. package/src/credentials/core/types.ts +10 -0
  278. package/src/credentials/node/from-adc.ts +96 -0
  279. package/src/credentials/node/from-service-account.ts +133 -0
  280. package/src/credentials/node/index.ts +6 -0
  281. package/src/discover/concurrency.ts +127 -0
  282. package/src/discover/crawler-adapter.ts +142 -0
  283. package/src/discover/crawler.ts +1127 -0
  284. package/src/discover/credential-free.ts +27 -0
  285. package/src/discover/findCollectionGroup.ts +131 -0
  286. package/src/discover/firestore-source.ts +59 -0
  287. package/src/discover/index.ts +5 -0
  288. package/src/discover/merge.ts +523 -0
  289. package/src/discover/session.ts +402 -0
  290. package/src/discover/tools.ts +201 -0
  291. package/src/discover/types.ts +187 -0
  292. package/src/discover/wire.ts +324 -0
  293. package/src/functions-rtdb/child.ts +382 -0
  294. package/src/functions-rtdb/delivery.ts +7 -0
  295. package/src/functions-rtdb/discovery.ts +136 -0
  296. package/src/functions-rtdb/event.ts +64 -0
  297. package/src/functions-rtdb/execution.ts +111 -0
  298. package/src/functions-rtdb/in-memory-delivery.ts +40 -0
  299. package/src/functions-rtdb/project.ts +74 -0
  300. package/src/functions-rtdb/projection.ts +104 -0
  301. package/src/functions-rtdb/reference-pattern.ts +20 -0
  302. package/src/functions-rtdb/remote-delivery.ts +23 -0
  303. package/src/pkg-version.ts +49 -0
  304. package/src/register/esm-exports.ts +63 -0
  305. package/src/register/hooks.ts +30 -0
  306. package/src/register/index.ts +150 -0
  307. package/src/register/mapping.ts +33 -0
  308. package/src/remote/index.ts +1050 -0
  309. package/src/rtdb/crawl-snapshot.ts +118 -0
  310. package/src/rtdb/inspection.ts +137 -0
  311. package/src/rtdb/load-rules-document.ts +56 -0
  312. package/src/rtdb/rules-generation-tool.ts +38 -0
  313. package/src/rtdb/rules-json.ts +29 -0
  314. package/src/serve/activity-guard.ts +29 -0
  315. package/src/serve/activity-route.ts +164 -0
  316. package/src/serve/activity-warning.ts +26 -0
  317. package/src/serve/bridge-mount.ts +200 -0
  318. package/src/serve/bundler.ts +519 -0
  319. package/src/serve/capture-store.ts +65 -0
  320. package/src/serve/discovery.ts +199 -0
  321. package/src/serve/entries/ai.ts +292 -0
  322. package/src/serve/entries/app-backend.ts +4 -0
  323. package/src/serve/entries/app-client.ts +26 -0
  324. package/src/serve/entries/app-session-store.ts +47 -0
  325. package/src/serve/entries/app.ts +11 -0
  326. package/src/serve/entries/auth-helper-core.ts +181 -0
  327. package/src/serve/entries/auth-helper-dom.ts +134 -0
  328. package/src/serve/entries/auth-helper-runtime.ts +20 -0
  329. package/src/serve/entries/auth.ts +255 -0
  330. package/src/serve/entries/bridge-url.ts +31 -0
  331. package/src/serve/entries/database.ts +129 -0
  332. package/src/serve/entries/firestore.ts +232 -0
  333. package/src/serve/entries/init.ts +49 -0
  334. package/src/serve/entries/keepalive.ts +46 -0
  335. package/src/serve/entries/messaging-sw.ts +75 -0
  336. package/src/serve/entries/messaging.ts +96 -0
  337. package/src/serve/entries/runtime.ts +556 -0
  338. package/src/serve/entries/session-store.ts +97 -0
  339. package/src/serve/entries/storage.ts +92 -0
  340. package/src/serve/entries/tab-sync-wiring.ts +274 -0
  341. package/src/serve/entries/worker-runtime.ts +135 -0
  342. package/src/serve/init-payload.ts +42 -0
  343. package/src/serve/namespace.ts +675 -0
  344. package/src/serve/open-browser.ts +68 -0
  345. package/src/serve/rules.ts +272 -0
  346. package/src/serve/runtime/chip-config.ts +30 -0
  347. package/src/serve/runtime/chip-install.ts +27 -0
  348. package/src/serve/runtime/chip.ts +282 -0
  349. package/src/serve/runtime/manifest.ts +37 -0
  350. package/src/serve/runtime/status.ts +216 -0
  351. package/src/serve/runtime/worker-connection.ts +14 -0
  352. package/src/serve/runtime/worker-generation.ts +75 -0
  353. package/src/serve/runtime/worker-replacement.ts +42 -0
  354. package/src/serve/sandbox-marker.ts +31 -0
  355. package/src/serve/server.ts +428 -0
  356. package/src/serve/standalone-assets.ts +180 -0
  357. package/src/serve/state-store.ts +166 -0
  358. package/src/serve/studio/disk-project-store.ts +185 -0
  359. package/src/serve/studio/disk-workspace.ts +162 -0
  360. package/src/serve/studio/index.ts +20 -0
  361. package/src/serve/studio/routes.ts +237 -0
  362. package/src/serve/studio/store-types.ts +48 -0
  363. package/src/serve/studio/studio-storage.test.ts +289 -0
  364. package/src/serve/vite-ai-config.ts +77 -0
  365. package/src/serve/vite-plugin.ts +1075 -0
  366. package/src/serve/vite-rules-source.ts +28 -0
  367. package/src/serve/vite-worker-runtime.ts +51 -0
  368. package/src/serve/worker/activity-bootstrap.ts +24 -0
  369. package/src/serve/worker/client/admin-firestore.ts +38 -0
  370. package/src/serve/worker/client/ai.ts +124 -0
  371. package/src/serve/worker/client/auth.ts +489 -0
  372. package/src/serve/worker/client/connection.ts +227 -0
  373. package/src/serve/worker/client/core.ts +384 -0
  374. package/src/serve/worker/client/disconnect.ts +45 -0
  375. package/src/serve/worker/client/firestore-reads.ts +181 -0
  376. package/src/serve/worker/client/firestore-refs.ts +226 -0
  377. package/src/serve/worker/client/firestore-writes.ts +232 -0
  378. package/src/serve/worker/client/handles.ts +91 -0
  379. package/src/serve/worker/client/messaging.ts +119 -0
  380. package/src/serve/worker/client/presence.ts +174 -0
  381. package/src/serve/worker/client/rtdb.ts +311 -0
  382. package/src/serve/worker/client/rules.ts +63 -0
  383. package/src/serve/worker/client/runtime-control.ts +22 -0
  384. package/src/serve/worker/client/service-worker-connection.ts +59 -0
  385. package/src/serve/worker/client/snapshots.ts +86 -0
  386. package/src/serve/worker/client/storage.ts +195 -0
  387. package/src/serve/worker/client/studio.ts +88 -0
  388. package/src/serve/worker/client.ts +57 -0
  389. package/src/serve/worker/durable-persistence.ts +137 -0
  390. package/src/serve/worker/entry.ts +223 -0
  391. package/src/serve/worker/host/admin-firestore.ts +88 -0
  392. package/src/serve/worker/host/connection.ts +179 -0
  393. package/src/serve/worker/host/core.ts +387 -0
  394. package/src/serve/worker/host/dispatch.ts +316 -0
  395. package/src/serve/worker/host/firestore-reads.ts +117 -0
  396. package/src/serve/worker/host/firestore-writes.ts +456 -0
  397. package/src/serve/worker/host/presence.ts +312 -0
  398. package/src/serve/worker/host/rtdb.ts +136 -0
  399. package/src/serve/worker/host/rules.ts +128 -0
  400. package/src/serve/worker/host/storage.ts +312 -0
  401. package/src/serve/worker/host/studio.ts +75 -0
  402. package/src/serve/worker/host/subscriptions.ts +238 -0
  403. package/src/serve/worker/host-ai.ts +165 -0
  404. package/src/serve/worker/host-auth.ts +469 -0
  405. package/src/serve/worker/host-context.ts +273 -0
  406. package/src/serve/worker/host-events.ts +94 -0
  407. package/src/serve/worker/host-messaging.ts +240 -0
  408. package/src/serve/worker/host.ts +47 -0
  409. package/src/serve/worker/index.ts +196 -0
  410. package/src/serve/worker/presence-timing.ts +15 -0
  411. package/src/serve/worker/protocol.ts +1124 -0
  412. package/src/serve/worker/retirement.ts +125 -0
  413. package/src/serve/worker/serve-init.ts +605 -0
  414. package/src/serve/worker/service-worker-channel.ts +33 -0
  415. package/src/serve/worker/service-worker-relay.ts +86 -0
  416. package/src/serve/writer-lock.ts +53 -0
  417. package/src/verify/cases.ts +233 -0
  418. package/src/verify/fixture.ts +258 -0
  419. package/src/verify/index.ts +519 -0
  420. package/src/verify/tools.ts +108 -0
  421. package/src/version/compat-target.ts +17 -0
  422. package/src/vite.ts +18 -0
  423. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api/index.html +0 -31
  424. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api.md +0 -29
@@ -0,0 +1,1075 @@
1
+ /**
2
+ * `@pyric/cli/vite` — the firebase→pyric-sandbox swap as a Vite plugin.
3
+ *
4
+ * The serve analog for SOURCE-driven apps: instead of `vite build && pyric dev
5
+ * dist`, a team keeps `vite dev` (HMR, source maps) with the in-process sandbox
6
+ * standing in for Firebase. The app's `firebase/*` imports are UNCHANGED — the
7
+ * plugin swaps them at the module-resolution layer (`resolveId`), the same way
8
+ * `pyric dev` swaps via a runtime import map. (Design: `plans/pyric-vite-plugin.md`.)
9
+ *
10
+ * Two flavors, one `apply` function. Under `vite dev` the swap is ALWAYS on.
11
+ * For `vite build` the swap is MODE-gated: a plain `vite build` (mode
12
+ * `production`) ships the real `firebase` package — the swap never reaches the
13
+ * prod artifact — while `vite build --mode development` (any NON-production
14
+ * mode) produces a SANDBOX build that bundles pyric's in-page adapters instead
15
+ * of the real SDK: self-contained, meant to be previewed under `pyric dev`, and
16
+ * stamped with the sandbox-build marker so it can never be deployed (`pyric
17
+ * deploy hosting` refuses it). `pyric({ swapInBuild })` forces the build
18
+ * behavior on/off regardless of mode. See `sandbox-marker.ts`.
19
+ *
20
+ * This is a thin adapter over serve's proven machinery. It REUSES, not reimplements:
21
+ * - the node-builtin shims — `NODE_BUILTIN_SHIMS`;
22
+ * - the swap targets — `defaultSdkEntries()` (the `serve/entries/*` wrappers,
23
+ * compiled-dist preferred, src fallback);
24
+ * - the `/__pyric/*` namespace — `createPyricNamespace` mounted verbatim behind
25
+ * a connect-middleware adapter;
26
+ * - rules load + prepare — `loadProjectRules` / `prepareRulesSource`;
27
+ * - the SharedWorker host — `bundleWorker` served at `/__pyric/sdk/worker.js`;
28
+ * - durable stores — `createStateStore` (persist) / `createCaptureStore`.
29
+ *
30
+ * Scope = M1 (swap + rules) + M2 (SharedWorker multi-tab + persist/capture/seed)
31
+ * + M3 (the MCP bridge fold — `{ bridge }`). M3 reuses `createBridgeMount` (the
32
+ * proven serve-flavored bridge behind `pyric dev --bridge`), composing it into
33
+ * the same `/__pyric` middleware; on the worker path the bridge peer routes
34
+ * agent tool-calls THROUGH the SharedWorker (`connectBridgePeer`), so the agent
35
+ * and the app share one backend without forcing the page in-page.
36
+ *
37
+ * Serving `worker.js` flips `runtime.ts` to the worker path (one backend across
38
+ * tabs, IndexedDB-durable); on that path the WORKER owns persist/capture/seed via
39
+ * the same `/__pyric/*` routes. If the worker bundle fails, the plugin falls back
40
+ * to the in-page sandbox (single-tab, ephemeral).
41
+ */
42
+ import { readFile } from 'node:fs/promises';
43
+ import { existsSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
44
+ import path from 'node:path';
45
+ import type { IncomingMessage, ServerResponse, Server as HttpServer } from 'node:http';
46
+ import type { Plugin, UserConfig, ConfigEnv } from 'vite';
47
+ import type { Plugin as EsbuildPlugin } from 'esbuild';
48
+ import {
49
+ SDK_MODULES,
50
+ defaultSdkEntries,
51
+ resolveStudioUiDir,
52
+ pyricPackageRoot,
53
+ NODE_BUILTIN_RE,
54
+ NODE_BUILTIN_SHIMS,
55
+ } from './bundler.js';
56
+ import { createViteWorkerRuntime } from './vite-worker-runtime.js';
57
+ import {
58
+ createEventHub,
59
+ createPyricNamespace,
60
+ type InitPayload,
61
+ } from './namespace.js';
62
+ import { formatActivityWarning } from './activity-warning.js';
63
+ import { diskWorkspace, diskProjectStore } from './studio/index.js';
64
+ import { createBridgeMount } from './bridge-mount.js';
65
+ import {
66
+ loadProjectDatabaseRules,
67
+ loadProjectRules,
68
+ loadProjectStorageRules,
69
+ prepareRulesSource,
70
+ rulesHashOf,
71
+ } from './rules.js';
72
+ import { createStateStore, STATE_FILE_VERSION, type PyricStateFile } from './state-store.js';
73
+ import { createCaptureStore } from './capture-store.js';
74
+ import { isAllowedHost } from './server.js';
75
+ import { SANDBOX_BUILD_META } from './sandbox-marker.js';
76
+ import { readFirebaseJson, readFirebaseRc, type FirebaseJson } from '../cli/firebase-json.js';
77
+ import {
78
+ discoverFunctionsRtdbProject,
79
+ type FunctionsRtdbProject,
80
+ } from '../functions-rtdb/project.js';
81
+ import {
82
+ spawnFunctionsRtdbChild,
83
+ type FunctionsRtdbChildHandle,
84
+ } from '../functions-rtdb/child.js';
85
+ import {
86
+ buildChildEnv,
87
+ createLinePrefixer,
88
+ registerModuleUrl,
89
+ } from '../cli/dev-runner.js';
90
+ import {
91
+ loadViteAiEnv,
92
+ resolveViteAiConfig,
93
+ type PyricAiOptions,
94
+ } from './vite-ai-config.js';
95
+ import { resolveViteRulesConfig } from './vite-rules-source.js';
96
+ import {
97
+ PYRIC_RUNTIME_CHIP_META,
98
+ runtimeChipMetaValue,
99
+ type PyricRuntimeChipOption,
100
+ } from './runtime/chip-config.js';
101
+
102
+ /**
103
+ * Whether a `vite build` should run the firebase→pyric swap (produce a SANDBOX
104
+ * build). MODE-based with a plugin-config override:
105
+ * - `options.swapInBuild` wins outright when set (force on/off);
106
+ * - otherwise swap for any NON-production mode. A plain `vite build` (mode
107
+ * `production`) ships real firebase; `vite build --mode development` (or any
108
+ * custom non-prod mode) is a sandbox build.
109
+ * `vite dev` is handled separately in `apply` (always on).
110
+ */
111
+ function swapsInBuild(env: ConfigEnv, swapInBuild: boolean | undefined): boolean {
112
+ if (swapInBuild !== undefined) return swapInBuild;
113
+ return env.mode !== 'production';
114
+ }
115
+
116
+ /** Any `firebase/<sub>` specifier. */
117
+ const FB_ANY = /^firebase\/([a-z-]+(?:\/[a-z-]+)*)$/;
118
+
119
+ /** The firebase subpaths with swap entries. */
120
+ const SERVED = new Set(SDK_MODULES.map((specifier) => specifier.slice('firebase/'.length)));
121
+ const entryKey = (subpath: string): string => subpath.replaceAll('/', '-');
122
+ const NODE_SHIM_PREFIX = '\0pyric:node-shim:';
123
+
124
+ /** Walk up from a file to the nearest directory containing a package.json. */
125
+ function packageRootOf(file: string): string {
126
+ let dir = path.dirname(file);
127
+ while (dir !== path.dirname(dir) && !existsSync(path.join(dir, 'package.json'))) {
128
+ dir = path.dirname(dir);
129
+ }
130
+ return dir;
131
+ }
132
+
133
+ export interface PyricOptions {
134
+ /** Firestore rules path (relative to `root`). Default discovery prefers an
135
+ * authored `firestore.modules.rules`, then `firebase.json`, then
136
+ * `firestore.rules` in the project root. */
137
+ rules?: string;
138
+ /** Project dir for `firebase.json` / rules discovery. Default: Vite's `root`. */
139
+ root?: string;
140
+ /** Persist sandbox state to `.pyric/state/state.json` so data + test users
141
+ * survive reloads/restarts. Off by default (ephemeral). */
142
+ persist?: boolean;
143
+ /** With `persist`: discard any existing state file and re-seed from scratch. */
144
+ fresh?: boolean;
145
+ /** Write the live session fixture to `.pyric/last-session.json` (for
146
+ * `pyric verify`). Default `true`; pass `false` to suppress. */
147
+ capture?: boolean;
148
+ /** Seed file: a `"collection/doc" → fields` JSON map, or a `pyric snapshot`
149
+ * state-file envelope. Applied at page init (state wins once it exists). */
150
+ seed?: string;
151
+ /** Mount the MCP **bridge** on Vite's dev origin so an external agent
152
+ * (Claude Code, Cursor) can drive this sandbox over MCP — `POST /__pyric/mcp`
153
+ * + `GET /__pyric/health` + `WS /__pyric/sandbox`, all on Vite's port.
154
+ * `true` is shorthand for `{}`. The agent and the page share ONE sandbox.
155
+ *
156
+ * Does NOT change the sandbox topology: on the default SharedWorker path the
157
+ * page dials the bridge WS and relays agent tool-calls THROUGH the worker
158
+ * (`connectBridgePeer`), so multi-tab stays on. The in-page fallback engages
159
+ * only when the worker bundle itself fails, bridge or not. */
160
+ bridge?: boolean | { project?: string; disableAuditLog?: boolean };
161
+ /** Serve the **Pyric Studio** app at `/__pyric/ui/` on Vite's dev origin (the
162
+ * `pyric dev --ui` equivalent). Mounts the disk-backed workspace/project
163
+ * routes Studio's `local` mode talks to AND serves the built Studio assets
164
+ * (vendored in this package at `dist/serve/studio-ui`). **On by default**,
165
+ * including under `bridge` (the bridge peer routes through the SharedWorker,
166
+ * so app, Studio, and agent all observe the one sandbox); pass `ui: false`
167
+ * to disable. */
168
+ ui?: boolean;
169
+ /** Inject the collapsed Pyric runtime chip into the app during sandbox Vite
170
+ * dev/builds. On by default. Pass `false` to hide it, or
171
+ * `{ initiallyOpen: true }` when actively debugging runtime errors. */
172
+ runtimeChip?: PyricRuntimeChipOption;
173
+ /** RTDB-triggered Cloud Functions under this dev server (the `pyric dev`
174
+ * parity fold). By default a `functions` block in `firebase.json` is
175
+ * discovered automatically: its `onValueCreated` triggers run in an isolated
176
+ * node child against the shared sandbox (other trigger kinds warn and are
177
+ * skipped), and the discovered codebase turns the MCP bridge mount on (the
178
+ * child dials the sandbox over the bridge WS — the page's sandbox topology
179
+ * is unchanged, see `bridge`). `functions: false` is the off switch: no
180
+ * discovery, no child, no functions-forced bridge mount.
181
+ *
182
+ * Field precedence: explicit option > env var > firebase files > default.
183
+ * - `region`: the trigger location. Beats `PYRIC_FUNCTIONS_RTDB_REGION`;
184
+ * default `us-central1`.
185
+ * - `instance`: the RTDB instance name. Default `<projectId>-default-rtdb`,
186
+ * where projectId is `PYRIC_PROJECT`, else `.firebaserc`'s default
187
+ * project, else `demo-project`.
188
+ * - `watch`: hot-reload the functions source (default `true`, matching
189
+ * rules). A save under the functions source dir stops the child and
190
+ * respawns it — redeploy semantics: in-flight executions in the old child
191
+ * may drop, and writes landing during the swap gap are consumed as the new
192
+ * child's baseline (they do not fire). Unlike rules, a broken save cannot
193
+ * keep last-good live — the old child is already gone — so functions stay
194
+ * down until the next good save. */
195
+ functions?: false | { region?: string; instance?: string; watch?: boolean };
196
+ /** Force whether `vite build` runs the firebase→pyric swap, overriding the
197
+ * mode default. Unset (default): swap for any NON-production mode, keep real
198
+ * firebase for mode `production`. `true` = always produce a sandbox build;
199
+ * `false` = never swap in build (real firebase regardless of mode). `vite
200
+ * dev` is unaffected — the swap is always on there. */
201
+ swapInBuild?: boolean;
202
+ /**
203
+ * Dev-server-level AI configuration for `pyric/ai` (the sanctioned
204
+ * replacement for threading `engine` through every app `getAI(...)` call,
205
+ * which is first-call-wins and easy to get wrong).
206
+ *
207
+ * pyric({
208
+ * ai: {
209
+ * model: 'llama3.2',
210
+ * proxyUpstream: 'http://localhost:11434/v1', // your Ollama
211
+ * },
212
+ * })
213
+ *
214
+ * - `model` is the simple OpenAI-compatible path. It uses the same-origin
215
+ * proxy and becomes the catch-all upstream model. `PYRIC_AI_MODEL` selects
216
+ * the same path when neither `model` nor `engine` is explicit.
217
+ * - `engine` is `pyric/ai`'s `EngineConfig` (scripted | openai), applied on
218
+ * both the SharedWorker and in-page paths. An openai `baseUrl` of
219
+ * `/__pyric/ai-proxy` (or omitted) routes through the same-origin proxy so a
220
+ * localhost upstream needs zero CORS setup.
221
+ * - `proxyUpstream` sets what `/__pyric/ai-proxy` forwards to (beats the
222
+ * `PYRIC_AI_PROXY_UPSTREAM` env var; default `http://localhost:11434/v1`).
223
+ *
224
+ * Precedence: explicit `engine` or `model`, then `PYRIC_AI_MODEL`, then an
225
+ * engine passed by the app's first `getAI()` call; with none, the zero-config
226
+ * scripted default applies. `model` and `engine` are mutually exclusive.
227
+ */
228
+ ai?: PyricAiOptions;
229
+ }
230
+
231
+ /**
232
+ * The dev-only Vite plugin. Add to `vite.config`:
233
+ *
234
+ * import { pyric } from '@pyric/cli/vite';
235
+ * export default defineConfig({ plugins: [pyric()] });
236
+ */
237
+ export function pyric(options: PyricOptions = {}): Plugin {
238
+ let resolvedAi = resolveViteAiConfig(options.ai, {});
239
+ // Resolved once. `defaultSdkEntries()` prefers compiled dist `.js` and falls
240
+ // back to source `.ts` in the workspace.
241
+ const entries = defaultSdkEntries(); // { app, auth, firestore, init } → abs paths
242
+ const pyricRoot = pyricPackageRoot();
243
+ // The @pyric/cli package root — covers the served entries AND their siblings
244
+ // (`worker/client.js`, the bridge client) that the entries statically import.
245
+ const cliRoot = packageRootOf(entries.init);
246
+
247
+ // section 8 refinement: a firebase import is "pyric-internal" iff its importer lives
248
+ // under the resolved pyric package root — keyed on the root, not a `/pyric/`
249
+ // substring (which a user project path could false-positive).
250
+ const isPyricImporter = (importer: string | undefined): boolean => {
251
+ if (!importer) return false;
252
+ const f = importer.split('?')[0];
253
+ return f === pyricRoot || f.startsWith(pyricRoot + path.sep);
254
+ };
255
+ // Node builtins are reached only from OUR code (pyric internals + the served
256
+ // entries) — shim those, but NEVER hijack a user app or third-party library's
257
+ // own `fs`/`path`/`url` (which Vite, or the user's polyfill plugin, should
258
+ // resolve). The firebase branch stays scoped to pyric; this is the wider "ours".
259
+ const isOurCode = (importer: string | undefined): boolean => {
260
+ if (!importer) return false;
261
+ if (isPyricImporter(importer)) return true;
262
+ const f = importer.split('?')[0];
263
+ return f === cliRoot || f.startsWith(cliRoot + path.sep);
264
+ };
265
+ const shimFor = (spec: string): string => NODE_BUILTIN_SHIMS[spec.replace(/^node:/, '')]!;
266
+
267
+ // The esbuild mirror for Vite's dep optimizer — REQUIRED so a node_modules
268
+ // library's `firebase/*` swaps too (the optimizer's esbuild pass bypasses the
269
+ // Rollup-pipeline resolveId below and would otherwise pre-bake real firebase).
270
+ const esbuildMirror: EsbuildPlugin = {
271
+ name: 'pyric-sandbox-optimizer',
272
+ setup(build) {
273
+ build.onResolve({ filter: FB_ANY }, (args) => {
274
+ const sub = FB_ANY.exec(args.path)![1]!;
275
+ if (SERVED.has(sub)) return { path: entries[entryKey(sub)]! };
276
+ return null; // non-served firebase from a lib → real firebase
277
+ });
278
+ build.onResolve({ filter: NODE_BUILTIN_RE }, (args) => {
279
+ if (!isOurCode(args.importer)) return null; // user/lib node builtins → Vite/their polyfill
280
+ return { path: args.path.replace(/^node:/, ''), namespace: 'pyric-node-shim' };
281
+ });
282
+ build.onLoad({ filter: /.*/, namespace: 'pyric-node-shim' }, (args) => ({
283
+ contents: NODE_BUILTIN_SHIMS[args.path]!,
284
+ loader: 'js',
285
+ }));
286
+ },
287
+ };
288
+
289
+ // Live rules box — the watcher swaps it; the init payload always serves the
290
+ // current version.
291
+ const live: {
292
+ rules: string | null;
293
+ rulesHash: string | null;
294
+ databaseRules: { rules: Record<string, unknown> } | null;
295
+ databaseRulesHash: string | null;
296
+ databaseUrl: string | null;
297
+ storageRules: string | null;
298
+ storageRulesHash: string | null;
299
+ } = {
300
+ rules: null,
301
+ rulesHash: null,
302
+ databaseRules: null,
303
+ databaseRulesHash: null,
304
+ databaseUrl: null,
305
+ storageRules: null,
306
+ storageRulesHash: null,
307
+ };
308
+
309
+ // M2: the SharedWorker bundle's content hash (sync) — stamped into the page so
310
+ // a still-running OLD worker is detected as stale. The collaborator becomes
311
+ // ready once its bundle succeeds; until then (or on bundle failure) the page
312
+ // is forced onto the in-page sandbox path. transformIndexHtml reads its tag.
313
+ const workerRuntime = createViteWorkerRuntime();
314
+
315
+ // Set by the `config` hook. When the plugin runs under `vite build` at all it
316
+ // is a SANDBOX build (the `apply` gate below only lets build through under the
317
+ // sandbox trigger), so `command === 'build'` is sufficient to know we are
318
+ // producing marker-stamped, non-production output.
319
+ let sandboxBuild = false;
320
+ // Sandbox build: the serve init entry (runtime bootstrap + the ServeAuthHelper
321
+ // popup picker) is emitted as its OWN chunk and script-tagged into index.html.
322
+ // Rollup dedupes the shared runtime module between this chunk and the app
323
+ // chunk (both import the same absolute file), so the page runs exactly ONE
324
+ // sandbox runtime — unlike serve-time injection of /__pyric/sdk/init.js,
325
+ // which is a separately-bundled second runtime copy (the double-init bug:
326
+ // two banners, two bridge registrations). `pyric dev` sees the marker and
327
+ // skips its injection for these pages (see injectServeTags).
328
+ let initChunkRef: string | undefined;
329
+ let initChunkFile: string | undefined;
330
+
331
+ // M3 bridge fold: normalize `bridge` once (true ⇒ `{}`, falsy ⇒ null). When
332
+ // on, the MCP mount is composed into the /__pyric middleware (createBridgeMount,
333
+ // shared with `pyric dev --bridge`) AND the page is forced onto the in-page
334
+ // sandbox path — the bridge peer is the in-page sandbox, never the SharedWorker,
335
+ // so multi-tab is disabled under bridge to keep agent + app on one backend.
336
+ const bridgeOpts = options.bridge === true ? {} : options.bridge || null;
337
+
338
+ // Plugin-level AI engine, normalized to the JSON-safe wire shape. Travels
339
+ // to the worker host via the init payload (→ ctx.aiEngine) AND to the in-page
340
+ // fallback via an injected synchronous global (see transformIndexHtml).
341
+ // An explicit engine is available immediately (some hook tests call the HTML
342
+ // transform directly); Vite's config hook may otherwise select the simple
343
+ // PYRIC_AI_MODEL environment path for the active mode/root.
344
+ return {
345
+ name: 'pyric:sandbox',
346
+ // Active for `vite dev` ALWAYS, and for `vite build` only when it is a
347
+ // SANDBOX build (any non-`production` mode, or `swapInBuild: true`). A plain
348
+ // `vite build` keeps the real firebase package — the swap never reaches
349
+ // production output. A sandbox build applies the same swap so the output
350
+ // bundles pyric's in-page adapters (self-contained; preview it under
351
+ // `pyric dev`, never deploy it).
352
+ apply(config, env) {
353
+ void config;
354
+ if (env.command === 'serve') return true;
355
+ return swapsInBuild(env, options.swapInBuild);
356
+ },
357
+ enforce: 'pre',
358
+
359
+ config(config, env) {
360
+ sandboxBuild = env.command === 'build';
361
+ const loadedEnv = loadViteAiEnv(env.mode, config.root, config.envDir);
362
+ resolvedAi = resolveViteAiConfig(options.ai, loadedEnv);
363
+ // Cast: the `esbuild` package's `Plugin` type skews slightly from Vite's
364
+ // bundled esbuild types (benign — the Plugin shape is stable across the
365
+ // versions in range).
366
+ return {
367
+ optimizeDeps: {
368
+ // Keep firebase out of the optimizer's pre-bake; the resolver swaps it
369
+ // per-importer at request time.
370
+ exclude: [...SDK_MODULES],
371
+ // The excluded SDK is served as ESM straight from dist, so Vite never
372
+ // scans it for dependencies. js-md5 / js-sha256 are CJS-only (no ESM
373
+ // named exports); without a forced pre-bundle the browser gets the raw
374
+ // UMD source and `import { md5 }` throws a SyntaxError. Force-including
375
+ // them gives the dist imports the interop-wrapped optimized copies.
376
+ include: ['js-md5', 'js-sha256'],
377
+ esbuildOptions: { plugins: [esbuildMirror] },
378
+ },
379
+ // Sandbox build only: the swapped-in runtime chunk uses TOP-LEVEL AWAIT
380
+ // (it deploys rules before app code runs — load-bearing, see
381
+ // entries/runtime.ts). Vite's default build target predates TLA and the
382
+ // esbuild transpile would fail. A sandbox build is a throwaway preview
383
+ // served under `pyric dev` (modern browser), so pin an ESNext target
384
+ // that keeps TLA. A plain production `vite build` never runs this plugin,
385
+ // so the user's own target is untouched there.
386
+ ...(sandboxBuild ? { build: { target: 'esnext' } } : {}),
387
+ } as unknown as UserConfig;
388
+ },
389
+
390
+ configResolved(resolved) {
391
+ // AUGMENT (don't replace) the fs allow-list: pyric dist + the @pyric/cli
392
+ // tree live outside the app root, but setting `server.fs.allow` in config()
393
+ // would clobber Vite's auto-added root/workspace entries and 403 the app's
394
+ // own source. Push the two PACKAGE ROOTS — @pyric/cli' root (not just the
395
+ // entries dir) is needed because the served init entry statically imports
396
+ // siblings (`worker/client.js`, the bridge client) outside entries/.
397
+ const allow = resolved.server?.fs?.allow;
398
+ if (allow) {
399
+ for (const dir of [pyricRoot, cliRoot]) {
400
+ if (!allow.includes(dir)) allow.push(dir);
401
+ }
402
+ }
403
+ },
404
+
405
+ resolveId(source, importer) {
406
+ const fb = FB_ANY.exec(source);
407
+ if (fb) {
408
+ const sub = fb[1]!;
409
+ if (SERVED.has(sub)) return entries[entryKey(sub)]!; // swap served set for user/lib
410
+ return null; // non-served firebase from user → real firebase
411
+ }
412
+ const node = NODE_BUILTIN_RE.exec(source);
413
+ // Shim node builtins ONLY when reached from our own code — never hijack a
414
+ // user app or library's own fs/path/url (Vite/their polyfill handles those).
415
+ if (node && isOurCode(importer)) return NODE_SHIM_PREFIX + node[2]!;
416
+ return null;
417
+ },
418
+
419
+ load(id) {
420
+ if (id.startsWith(NODE_SHIM_PREFIX)) return shimFor(id.slice(NODE_SHIM_PREFIX.length));
421
+ return null;
422
+ },
423
+
424
+ async configureServer(server) {
425
+ const cwd = options.root ?? server.config.root;
426
+
427
+ // Reproduce serve's rules prelude: firebase.json (optional) → loadProjectRules.
428
+ let fbJson: FirebaseJson | null = null;
429
+ try {
430
+ fbJson = await readFirebaseJson(cwd);
431
+ } catch {
432
+ /* optional — serve without a firebase.json */
433
+ }
434
+ // Convention-first development source: an explicit option wins; otherwise
435
+ // an authored 2+modules file wins over firebase.json's generated deployment
436
+ // target. Projects without that convention retain the normal Firebase
437
+ // discovery path.
438
+ const config = resolveViteRulesConfig(cwd, options.rules, fbJson);
439
+ const loaded = await loadProjectRules(cwd, config);
440
+ const loadedDatabase = await loadProjectDatabaseRules(cwd, config);
441
+ const loadedStorage = await loadProjectStorageRules(cwd, config);
442
+ live.rules = loaded.rules;
443
+ live.rulesHash = loaded.rulesHash;
444
+ live.databaseRules = loadedDatabase.rules;
445
+ live.databaseRulesHash = loadedDatabase.rulesHash;
446
+ live.databaseUrl = loadedDatabase.databaseUrl;
447
+ live.storageRules = loadedStorage.rules;
448
+ live.storageRulesHash = loadedStorage.rulesHash;
449
+
450
+ // ── M2 durable stores (mirrors serve's startServe orchestration) ──────
451
+ // Capture (default-on): the worker/page pushes its session fixture to
452
+ // /__pyric/capture; the store writes .pyric/last-session.json for `pyric verify`.
453
+ const capture = (options.capture ?? true) ? createCaptureStore(cwd) : undefined;
454
+ // Persist: createStateStore IS the durable sandbox. Load eagerly so a
455
+ // corrupt/mismatched file fails the start (not silently ephemeral).
456
+ const state = options.persist ? createStateStore(cwd) : undefined;
457
+ if (state && options.fresh) {
458
+ for (const p of [state.path, state.backupPath]) if (existsSync(p)) rmSync(p);
459
+ server.config.logger.info(' ⓘ [pyric] fresh: discarded the existing state file; re-seeding');
460
+ }
461
+ // Eager load (mirrors serve.ts:158) — parse the file NOW so a corrupt or
462
+ // version-mismatched state file throws StateFileError and FAILS THE START
463
+ // with the actionable inspect-or-delete message. Without this the first
464
+ // parse is deferred into initPayload() at request time, where it throws
465
+ // synchronously AFTER namespace.ts has committed `writeHead(200)`: the
466
+ // client gets a 200 with an empty body, the page/worker swallow the JSON
467
+ // error, and the sandbox silently runs WITHOUT the persisted data + rules.
468
+ // (No-op on first run: load() returns null for a missing file.)
469
+ // configureServer is async, so an uncaught throw aborts the dev start.
470
+ if (state) state.load();
471
+
472
+ // Seed: a "collection/doc" → fields map, OR a `pyric snapshot` state-file
473
+ // envelope (detected by its `version` key). Ported from serve.ts.
474
+ let seed: Record<string, Record<string, unknown>> | null = null;
475
+ let seedState: unknown | null = null;
476
+ let seedUsers: Record<string, unknown>[] | null = null;
477
+ if (options.seed) {
478
+ const seedPath = path.resolve(cwd, options.seed);
479
+ let parsed: unknown;
480
+ try {
481
+ parsed = JSON.parse(readFileSync(seedPath, 'utf8'));
482
+ } catch (e) {
483
+ throw new Error(`@pyric/cli/vite: failed to read seed ${seedPath}: ${e instanceof Error ? e.message : String(e)}`);
484
+ }
485
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
486
+ throw new Error('@pyric/cli/vite: seed must be a JSON object of "collection/doc" → fields');
487
+ }
488
+ const obj = parsed as Record<string, unknown>;
489
+ if (obj.version === STATE_FILE_VERSION && ('firestore' in obj || 'auth' in obj)) {
490
+ const fixture = obj as unknown as PyricStateFile;
491
+ if (state && !state.exists()) {
492
+ // persist first run from a fixture: prime the store, then the normal
493
+ // persist path restores it like any lived state.
494
+ if (fixture.firestore != null) state.writeSection('firestore', fixture.firestore);
495
+ if (fixture.auth != null) state.writeSection('auth', fixture.auth);
496
+ } else if (!state) {
497
+ seedState = fixture.firestore ?? null;
498
+ seedUsers = (fixture.auth?.users as Record<string, unknown>[] | undefined) ?? null;
499
+ }
500
+ // persist + existing state: lived state wins; the fixture is inert.
501
+ } else {
502
+ seed = parsed as Record<string, Record<string, unknown>>;
503
+ }
504
+ }
505
+
506
+ // ── M2 SharedWorker host: bundle it (cached per version) and serve it at
507
+ // /__pyric/sdk/worker.js. This is what flips runtime.ts to the worker path.
508
+ // On bundle failure, the collaborator stays unready and its HTML tag
509
+ // forces the in-page sandbox.
510
+ try {
511
+ await workerRuntime.prepare();
512
+ } catch (e) {
513
+ server.config.logger.warn(
514
+ ` ⚠ [pyric] SharedWorker bundle failed — using the in-page sandbox (single-tab, ephemeral): ${e instanceof Error ? e.message : String(e)}`,
515
+ );
516
+ }
517
+
518
+ // ── Functions (RTDB triggers) — the `pyric dev` parity fold ───────────
519
+ // Discover the one supported Functions codebase from the same resolved
520
+ // firebase.json the rules used (project.ts reads it itself). Reuses the
521
+ // exact serve module, so absent `functions` → null (silently off) and a
522
+ // malformed config throws serve's own error text — which, thrown from an
523
+ // async configureServer, fails the dev start the same way serve's
524
+ // `return 2` aborts. The Functions child connects to the sandbox over the
525
+ // bridge WS, so a discovered codebase forces the bridge mount on (mirrors
526
+ // serve's `bridgeEnabledFor(..., functionsProject)`). `functions: false`
527
+ // is the off switch: discovery never runs, so neither does the mount.
528
+ const functionsOpts = typeof options.functions === 'object' ? options.functions : {};
529
+ let functionsProject: FunctionsRtdbProject | null = null;
530
+ if (options.functions !== false) {
531
+ try {
532
+ functionsProject = discoverFunctionsRtdbProject(cwd);
533
+ } catch (error) {
534
+ // Malformed functions config: fail the start with serve's exact message.
535
+ throw error instanceof Error ? error : new Error(String(error));
536
+ }
537
+ }
538
+ const functionsProjectId = functionsProject
539
+ ? (process.env.PYRIC_PROJECT ?? (await readFirebaseRc(cwd))?.projects?.default ?? 'demo-project')
540
+ : null;
541
+
542
+ // ── M3 MCP bridge (mirrors serve.ts:221–274) ─────────────────────────
543
+ // The mount is long-lived (one bridge per dev session); its MCP transport
544
+ // is rebuilt per request (stateless). Composed into the /__pyric middleware
545
+ // below (handler tier) + the server's WS upgrade. middlewareMode has no
546
+ // httpServer → HTTP routes still work, no WS peer.
547
+ // Guard the WS upgrade with the SAME allow rule Vite's own host check
548
+ // uses (host + allowedHosts, where `true` = opted into all hosts). Vite's
549
+ // upgrade path bypasses connect middleware, so this is the only guard on it.
550
+ const mount = bridgeOpts || functionsProject
551
+ ? createBridgeMount({
552
+ ...(bridgeOpts ?? {}),
553
+ // A functions-only session still needs a labeled bridge; prefer an
554
+ // explicit bridge project, else the resolved functions project id.
555
+ project: bridgeOpts?.project ?? functionsProjectId ?? undefined,
556
+ upgradeGuard: {
557
+ boundHost: typeof server.config.server.host === 'string' ? server.config.server.host : 'localhost',
558
+ allowedHosts:
559
+ server.config.server.allowedHosts === true
560
+ ? true
561
+ : Array.isArray(server.config.server.allowedHosts)
562
+ ? server.config.server.allowedHosts
563
+ : [],
564
+ },
565
+ })
566
+ : null;
567
+
568
+ // The /__pyric/* namespace, reused VERBATIM (now with the sdk dir + state +
569
+ // capture routes live).
570
+ const events = createEventHub();
571
+ const initPayload = (): InitPayload => ({
572
+ rules: live.rules,
573
+ rulesHash: live.rulesHash,
574
+ databaseRules: live.databaseRules,
575
+ databaseRulesHash: live.databaseRulesHash,
576
+ databaseUrl: live.databaseUrl,
577
+ storageRules: live.storageRules,
578
+ storageRulesHash: live.storageRulesHash,
579
+ // Project identity: scopes the storage IDB name per served project
580
+ // (issue #359). Local-only — a dev path never leaves the machine.
581
+ projectKey: cwd,
582
+ // The bound port is known only after `listen`; initPayload runs per
583
+ // request (after listen), so resolve it lazily here. Absolute ws://host:port
584
+ // mirrors serve (the browser reads this as the bridge peer URL).
585
+ bridgeUrl: (() => {
586
+ if (!mount) return null;
587
+ const addr = server.httpServer?.address();
588
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
589
+ const host = (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
590
+ return port > 0 ? mount.wsUrl({ host, port }) : null;
591
+ })(),
592
+ // Precedence: once a state file exists, lived state is the truth — seed
593
+ // applies only on the first (state-less) run.
594
+ seed: state?.exists() ? null : seed,
595
+ seedState,
596
+ persist: Boolean(state),
597
+ capture: Boolean(capture),
598
+ authUsers: state
599
+ ? ((state.readSection('auth') as { users?: Record<string, unknown>[] } | null)?.users ?? null)
600
+ : seedUsers,
601
+ // Messaging is part of the canonical firebase/* sandbox swap.
602
+ messaging: true,
603
+ // Plugin-level engine → the worker host's ctx.aiEngine (host-ai.ts),
604
+ // which wins over any op-carried engine. Null when unset.
605
+ ai: resolvedAi.engineWire ? { engine: resolvedAi.engineWire } : null,
606
+ });
607
+ // Pyric Studio: mount the disk-backed workspace/project routes that
608
+ // Studio's `local` mode talks to + serve the built Studio app at
609
+ // /__pyric/ui/. Mirrors `pyric dev --ui`; the studio-ui assets are
610
+ // vendored in this package's dist (resolveStudioUiDir).
611
+ //
612
+ // ON BY DEFAULT, including under `bridge`: the bridge now routes agent
613
+ // tool-calls THROUGH the SharedWorker (see `connectBridgePeer`), so the
614
+ // app, Studio, and agent all observe the ONE sandbox. Explicit `ui: false`
615
+ // still wins.
616
+ const uiEnabled = options.ui ?? true;
617
+ const studio = uiEnabled
618
+ ? {
619
+ workspace: diskWorkspace(cwd),
620
+ projects: diskProjectStore(path.join(cwd, '.pyric', 'projects')),
621
+ }
622
+ : undefined;
623
+ let studioUiDir: string | undefined;
624
+ if (uiEnabled) {
625
+ studioUiDir = resolveStudioUiDir() ?? undefined;
626
+ if (!studioUiDir) {
627
+ server.config.logger.warn(
628
+ '[pyric] ui: built Studio app not found; /__pyric/ui/ will 404 ' +
629
+ '(run the full build, or reinstall @pyric/cli).',
630
+ );
631
+ }
632
+ }
633
+ const { sdkDir } = workerRuntime.status();
634
+ const namespace = createPyricNamespace({
635
+ sdkDir,
636
+ initPayload,
637
+ events,
638
+ activity: (incident) => server.config.logger.warn(formatActivityWarning(incident)),
639
+ state,
640
+ capture,
641
+ studio,
642
+ studioUiDir,
643
+ // `ai.proxyUpstream`: what `/__pyric/ai-proxy` forwards to (beats the
644
+ // PYRIC_AI_PROXY_UPSTREAM env var; falls back to the default when unset).
645
+ aiProxyUpstream: resolvedAi.proxyUpstream,
646
+ // Adapt Vite's logger to the plain info/note shape the namespace's
647
+ // diagnostics (denial relay, future hot-reload lines) expect —
648
+ // matches the `↻`/`⚠ [pyric]` lines already logged elsewhere in this
649
+ // plugin via `server.config.logger` directly.
650
+ logger: {
651
+ info: (m) => server.config.logger.info(m),
652
+ note: (m) => server.config.logger.warn(m),
653
+ },
654
+ });
655
+
656
+ // DNS-rebinding guard for the /__pyric/* surface. Vite has its own host
657
+ // check, but a `configureServer` hook that doesn't return a function mounts
658
+ // BEFORE it (and the ordering differs across Vite 5/6/7), so guard here too
659
+ // — independent of Vite's internals. Reuses serve's `isAllowedHost`.
660
+ const srvOpts = server.config.server;
661
+ const hostAllowed = (req: IncomingMessage): boolean => {
662
+ if (srvOpts.allowedHosts === true) return true; // user opted into all hosts
663
+ const boundHost = typeof srvOpts.host === 'string' ? srvOpts.host : 'localhost';
664
+ const extra = Array.isArray(srvOpts.allowedHosts) ? srvOpts.allowedHosts : [];
665
+ return isAllowedHost(req.headers.host, boundHost, extra);
666
+ };
667
+
668
+ // Connect-middleware adapter (build `url` from originalUrl; next() when the
669
+ // namespace closure returns false; never rewrite route bodies).
670
+ server.middlewares.use('/__pyric', (req: IncomingMessage & { originalUrl?: string }, res: ServerResponse, next: () => void) => {
671
+ if (!hostAllowed(req)) {
672
+ res.statusCode = 403;
673
+ res.end(`pyric: refused request for Host '${req.headers.host ?? ''}' (DNS-rebinding guard).`);
674
+ return;
675
+ }
676
+ const url = new URL(req.originalUrl ?? req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
677
+ // Bridge first (mirrors serve.ts): /__pyric/mcp + /__pyric/health must be
678
+ // handled by the mount, not 404 through the namespace. Falls through to the
679
+ // namespace when the mount returns false (every non-bridge route).
680
+ Promise.resolve(mount ? mount.handler(req, res, url) : false)
681
+ .then((bridged) => (bridged ? true : Promise.resolve(namespace(req, res, url))))
682
+ .then((handled) => {
683
+ if (!handled) next();
684
+ })
685
+ .catch((err: unknown) => {
686
+ if (!res.headersSent) res.statusCode = 500;
687
+ res.end(err instanceof Error ? err.message : String(err));
688
+ });
689
+ });
690
+
691
+ // WS upgrade for the in-page sandbox peer (ws://…/__pyric/sandbox). The
692
+ // listener only fires once upgrades arrive (after listen), so adding it in
693
+ // configureServer is safe. middlewareMode has no httpServer → HTTP bridge
694
+ // routes still work, just no WS peer.
695
+ // Cast: Vite types `httpServer` as http.Server | http2.Http2SecureServer;
696
+ // attachUpgrade only needs `.on('upgrade')`, present on both. (serve passes
697
+ // a plain http.Server, so this widening is plugin-specific.)
698
+ if (mount && server.httpServer) mount.attachUpgrade(server.httpServer as unknown as HttpServer);
699
+
700
+ // A2 discovery pointer: the stdio `mcp-proxy` (the sanctioned Claude Code
701
+ // entrypoint) reads `.pyric/serve.json` to find the bridge without a fixed
702
+ // URL -- it takes the PORT and probes BOTH loopback families, defeating the
703
+ // IPv6/IPv4 trap that broke the hand-written `.mcp.json`. serve writes this
704
+ // pointer; the Vite plugin must too. Written after listen (port known),
705
+ // removed on close.
706
+ if (mount && server.httpServer) {
707
+ const httpServer = server.httpServer;
708
+ const pointer = path.join(cwd, '.pyric', 'serve.json');
709
+ const host =
710
+ (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
711
+ const writePointer = (): void => {
712
+ const addr = httpServer.address();
713
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
714
+ if (!port) return;
715
+ try {
716
+ mkdirSync(path.dirname(pointer), { recursive: true });
717
+ writeFileSync(
718
+ pointer,
719
+ JSON.stringify(
720
+ {
721
+ url: `http://${host}:${port}`,
722
+ mcpUrl: mount.mcpUrl({ host, port }),
723
+ port,
724
+ pid: process.pid,
725
+ instanceId: mount.instanceId,
726
+ project: bridgeOpts?.project ?? 'sandbox',
727
+ },
728
+ null,
729
+ 2,
730
+ ) + '\n',
731
+ );
732
+ } catch {
733
+ /* best-effort: the proxy falls back to a port scan */
734
+ }
735
+ };
736
+ // Cross-family collision guard: once listening, probe BOTH loopback
737
+ // families on our port. If a DIFFERENT sandbox answers on the other
738
+ // family, two dev servers are colliding (IPv4 `*:P` + IPv6 `[::1]:P`)
739
+ // and the agent/browser can split across them (writes seem to vanish).
740
+ // #697's dual-bind can't apply here — Vite owns the single listen — so
741
+ // we can only warn, loudly. (Our own family answers with our instanceId
742
+ // and is skipped; a dual-stack bind owns both and never trips this.)
743
+ const warnOnCollision = async (): Promise<void> => {
744
+ const a = httpServer.address();
745
+ const p = a && typeof a === 'object' ? a.port : 0;
746
+ if (!p) return;
747
+ for (const probe of [`http://127.0.0.1:${p}`, `http://[::1]:${p}`]) {
748
+ try {
749
+ const res = await fetch(`${probe}/__pyric/health`, { signal: AbortSignal.timeout(1000) });
750
+ if (res.status !== 200) continue;
751
+ const body = (await res.json()) as { mode?: string; instanceId?: string };
752
+ if (body.mode === 'sandbox' && body.instanceId && body.instanceId !== mount.instanceId) {
753
+ server.config.logger.warn(
754
+ `\n⚠ pyric: another sandbox already serves port ${p} on a different loopback ` +
755
+ `family (${probe}). Two dev servers are colliding across IPv4/IPv6 — your MCP ` +
756
+ `agent and browser can land on DIFFERENT sandboxes (writes seem to vanish). ` +
757
+ `Stop the other server, or give this app a unique \`server.port\` so the two ` +
758
+ `don't share one (pinning server.host to a family the squatter holds would ` +
759
+ `just EADDRINUSE).\n`,
760
+ { timestamp: true },
761
+ );
762
+ return; // one warning is enough
763
+ }
764
+ } catch {
765
+ /* other family silent — no collision */
766
+ }
767
+ }
768
+ };
769
+ const announce = (): void => {
770
+ writePointer();
771
+ void warnOnCollision();
772
+ };
773
+ if ((httpServer as unknown as { listening?: boolean }).listening) announce();
774
+ else httpServer.once('listening', announce);
775
+ httpServer.once('close', () => {
776
+ try {
777
+ rmSync(pointer);
778
+ } catch {
779
+ /* gone already */
780
+ }
781
+ });
782
+ }
783
+
784
+ // ── Functions child lifecycle (mirrors serve's runServe) ─────────────
785
+ // The Functions runtime executes in an isolated node child (child.ts),
786
+ // exactly as `pyric dev` runs it: the child loads the user's unchanged
787
+ // functions module, and `--import @pyric/cli/register` + `PYRIC_SANDBOX=
788
+ // remote:<serveUrl>` route its `firebase-admin/app` to a RemoteSandbox that
789
+ // dials the bridge WS (`/__pyric/sandbox`). onValueCreated triggers observe
790
+ // RTDB writes and write their effects back through that one shared sandbox.
791
+ // Started once a sandbox peer (a browser tab / SharedWorker relay) has
792
+ // connected — the trigger's baseline needs a live backend — and stopped on
793
+ // server close. Vite restarts re-run configureServer, so the child respawns
794
+ // with the new server. Unlike `pyric dev` (which does not watch functions
795
+ // source), the plugin hot-reloads it via Vite's own watcher — see the
796
+ // watch block below; `functions: { watch: false }` restores dev's
797
+ // restart-to-reload behavior.
798
+ if (functionsProject && functionsProjectId && mount && server.httpServer) {
799
+ const httpServer = server.httpServer;
800
+ const project = functionsProject;
801
+ const projectId = functionsProjectId;
802
+ const bridgeMount = mount;
803
+ const host =
804
+ (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
805
+ // Prefer the compiled child (node cannot execute the .ts source when the
806
+ // plugin runs from source in tests); fall back to spawnFunctionsRtdbChild's
807
+ // own default (correct when the plugin runs from dist in production).
808
+ const builtChild = path.join(cliRoot, 'dist/functions-rtdb/child.js');
809
+ const childModuleUrl = existsSync(builtChild) ? builtChild : undefined;
810
+ let functionsChild: FunctionsRtdbChildHandle | null = null;
811
+ let disposed = false;
812
+
813
+ const start = async (mode: 'initial' | 'reload' = 'initial'): Promise<void> => {
814
+ const addr = httpServer.address();
815
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
816
+ if (!port || disposed) return;
817
+ const serveUrl = `http://${host}:${port}`;
818
+
819
+ // Wait (bounded) for a sandbox peer — the SharedWorker relay / browser
820
+ // tab that holds the backend. Poll the mount directly (no self-fetch).
821
+ // On a hot reload the peer is usually still connected (the loop exits
822
+ // immediately); when it dropped mid-session, wait briefly rather than
823
+ // the full initial 30s.
824
+ const deadline = Date.now() + (mode === 'reload' ? 5_000 : 30_000);
825
+ while (!disposed && !bridgeMount.sandboxConnected()) {
826
+ if (Date.now() >= deadline) break;
827
+ await new Promise((r) => setTimeout(r, 250));
828
+ }
829
+ if (disposed) return;
830
+ if (!bridgeMount.sandboxConnected()) {
831
+ server.config.logger.warn(
832
+ mode === 'reload'
833
+ ? ` ✖ [pyric] functions not restarted — no sandbox peer connected. ` +
834
+ `Functions stay down until the next save with ${serveUrl} open.`
835
+ : ` ⚠ [pyric] functions not started — no browser tab connected after 30s. ` +
836
+ `Open ${serveUrl} and restart the dev server.`,
837
+ );
838
+ return;
839
+ }
840
+
841
+ functionsChild = spawnFunctionsRtdbChild({
842
+ cwd: project.sourceDir,
843
+ entry: project.entry,
844
+ env: buildChildEnv(process.env, { serveUrl, registerUrl: registerModuleUrl() }),
845
+ // Precedence (per field): plugin option > env var > firebase files
846
+ // > default. projectId already folds PYRIC_PROJECT > .firebaserc >
847
+ // demo-project.
848
+ instance: functionsOpts.instance ?? `${projectId}-default-rtdb`,
849
+ location: functionsOpts.region ?? process.env.PYRIC_FUNCTIONS_RTDB_REGION ?? 'us-central1',
850
+ ...(childModuleUrl ? { childModuleUrl } : {}),
851
+ onEvent(event) {
852
+ if (event.type === 'execution') {
853
+ const params = Object.entries(event.params)
854
+ .map(([name, value]) => `${name}=${value}`)
855
+ .join(', ');
856
+ const suffix = params ? ` (${params})` : '';
857
+ if (event.status === 'fulfilled') {
858
+ server.config.logger.info(` ✔ [pyric] function ${event.exportName} ← /${event.ref}${suffix}`);
859
+ } else {
860
+ server.config.logger.error(
861
+ ` ✖ [pyric] function ${event.exportName} ← /${event.ref}${suffix}: ${event.error.message}`,
862
+ );
863
+ }
864
+ } else {
865
+ server.config.logger.error(
866
+ ` ✖ [pyric] functions delivery for ${event.exportName}: ${event.error.message}`,
867
+ );
868
+ }
869
+ },
870
+ });
871
+
872
+ const out = createLinePrefixer('[functions] ', (line) => server.config.logger.info(line.replace(/\n$/, '')));
873
+ const err = createLinePrefixer('[functions] ', (line) => server.config.logger.warn(line.replace(/\n$/, '')));
874
+ functionsChild.child.stdout?.setEncoding('utf8');
875
+ functionsChild.child.stderr?.setEncoding('utf8');
876
+ functionsChild.child.stdout?.on('data', (chunk: string) => out.push(chunk));
877
+ functionsChild.child.stderr?.on('data', (chunk: string) => err.push(chunk));
878
+ functionsChild.child.stdout?.once('end', () => out.flush());
879
+ functionsChild.child.stderr?.once('end', () => err.flush());
880
+
881
+ try {
882
+ const ready = await functionsChild.ready;
883
+ server.config.logger.info(
884
+ mode === 'reload'
885
+ ? ` ↻ [pyric] functions reloaded (${ready.triggerCount} trigger${ready.triggerCount === 1 ? '' : 's'})`
886
+ : ` ✔ [pyric] functions ${ready.triggerCount} onValueCreated ` +
887
+ `trigger${ready.triggerCount === 1 ? '' : 's'} from ${path.relative(cwd, project.entry)}`,
888
+ );
889
+ for (const unsupported of ready.unsupportedTriggers) {
890
+ server.config.logger.warn(
891
+ ` ⚠ [pyric] functions export ${unsupported.exportName} uses unsupported trigger ` +
892
+ `${unsupported.eventType}; it will not run.`,
893
+ );
894
+ }
895
+ } catch (error) {
896
+ const message = error instanceof Error ? error.message : String(error);
897
+ server.config.logger.error(
898
+ mode === 'reload'
899
+ ? // Unlike rules, last-good cannot stay live — the old child is
900
+ // already stopped — so a broken save takes functions down.
901
+ ` ✖ [pyric] functions failed to reload: ${message}\n` +
902
+ ` ✖ [pyric] functions are down until the next good save.`
903
+ : ` ✖ [pyric] functions failed to start: ${message}`,
904
+ );
905
+ await functionsChild.stop().catch(() => undefined);
906
+ functionsChild = null;
907
+ }
908
+ };
909
+
910
+ let reloadDebounce: ReturnType<typeof setTimeout> | null = null;
911
+ httpServer.once('close', () => {
912
+ disposed = true;
913
+ if (reloadDebounce) clearTimeout(reloadDebounce);
914
+ void functionsChild?.stop().catch(() => undefined);
915
+ });
916
+ if ((httpServer as unknown as { listening?: boolean }).listening) void start();
917
+ else httpServer.once('listening', () => void start());
918
+
919
+ // Functions hot-reload from Vite's OWN watcher (mirrors the rules block
920
+ // below). Restart = redeploy: stop the old child, respawn via the same
921
+ // start path — there is no in-place swap, so in-flight executions in the
922
+ // old child may drop and writes landing in the swap gap become the new
923
+ // child's baseline (execution.ts consumes each trigger's first observed
924
+ // value as baseline; they do not fire). Debounced 300ms — a save fans
925
+ // out several fs events and a child respawn is far heavier than a rules
926
+ // re-parse. Restarts are serialized: a save landing mid-restart queues
927
+ // exactly one follow-up run.
928
+ if (functionsOpts.watch !== false) {
929
+ const sourceDir = project.sourceDir;
930
+ // Usually redundant (Vite watches its root, which contains the
931
+ // functions dir in the common layout) but load-bearing when the
932
+ // functions source lives outside Vite's root. node_modules stays
933
+ // ignored: Vite's watcher ignores `**/node_modules/**` globally, and
934
+ // the handler below filters it again for explicitly-added trees.
935
+ server.watcher.add(sourceDir);
936
+ let restarting = false;
937
+ let queued = false;
938
+ const restart = async (): Promise<void> => {
939
+ if (restarting) {
940
+ queued = true;
941
+ return;
942
+ }
943
+ restarting = true;
944
+ try {
945
+ do {
946
+ queued = false;
947
+ if (disposed) return;
948
+ const old = functionsChild;
949
+ functionsChild = null;
950
+ if (old) await old.stop().catch(() => undefined);
951
+ await start('reload');
952
+ } while (queued && !disposed);
953
+ } finally {
954
+ restarting = false;
955
+ }
956
+ };
957
+ const onFunctionsFsEvent = (file: string): void => {
958
+ const resolved = path.resolve(file);
959
+ const rel = path.relative(sourceDir, resolved);
960
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return;
961
+ if (rel.split(path.sep).includes('node_modules')) return;
962
+ if (reloadDebounce) clearTimeout(reloadDebounce);
963
+ reloadDebounce = setTimeout(() => void restart(), 300);
964
+ };
965
+ server.watcher.on('change', onFunctionsFsEvent);
966
+ server.watcher.on('add', onFunctionsFsEvent);
967
+ server.watcher.on('unlink', onFunctionsFsEvent);
968
+ }
969
+ }
970
+
971
+ // Rules hot-reload from Vite's OWN watcher (no second fs watcher). Reuse
972
+ // prepareRulesSource (resolve + lint); last-good stays live on a broken save.
973
+ // Debounced (editors emit several change events per save) — matches
974
+ // watchProjectRules' 150ms cadence, which we can't reuse here (it opens its
975
+ // own fs watcher).
976
+ if (loaded.sourcePath) {
977
+ const rulesFile = loaded.sourcePath;
978
+ let debounce: ReturnType<typeof setTimeout> | null = null;
979
+ server.watcher.add(rulesFile);
980
+ server.watcher.on('change', (file) => {
981
+ if (path.resolve(file) !== path.resolve(rulesFile)) return;
982
+ if (debounce) clearTimeout(debounce);
983
+ debounce = setTimeout(() => {
984
+ void readFile(rulesFile, 'utf8').then(
985
+ (raw) => {
986
+ try {
987
+ const rules = prepareRulesSource(raw, rulesFile);
988
+ live.rules = rules;
989
+ live.rulesHash = rulesHashOf(rules);
990
+ events.broadcast('rules-changed', { rules, rulesHash: live.rulesHash });
991
+ server.config.logger.info(` ↻ [pyric] rules reloaded (${live.rulesHash})`);
992
+ } catch (e) {
993
+ server.config.logger.warn(
994
+ ` ⚠ [pyric] rules NOT reloaded (last-good stays live): ${e instanceof Error ? e.message : String(e)}`,
995
+ );
996
+ }
997
+ },
998
+ () => {},
999
+ );
1000
+ }, 150);
1001
+ });
1002
+ }
1003
+ },
1004
+
1005
+ // Sandbox build only: emit the serve init entry as its own chunk. Emitted in
1006
+ // buildStart (module graph time); its final filename is resolved in
1007
+ // generateBundle. Our plugin is `enforce: 'pre'`, so our generateBundle runs
1008
+ // BEFORE Vite's build-html plugin applies transformIndexHtml — the filename
1009
+ // is always available when the script tag is injected below.
1010
+ buildStart() {
1011
+ if (sandboxBuild) {
1012
+ initChunkRef = this.emitFile({
1013
+ type: 'chunk',
1014
+ id: entries.init,
1015
+ name: 'pyric-sandbox-init',
1016
+ });
1017
+ }
1018
+ },
1019
+ generateBundle() {
1020
+ if (initChunkRef) initChunkFile = this.getFileName(initChunkRef);
1021
+ },
1022
+
1023
+ transformIndexHtml(html) {
1024
+ const runtimeChipTag = `<meta name="${PYRIC_RUNTIME_CHIP_META}" content="${runtimeChipMetaValue(options.runtimeChip)}" data-studio="${options.ui === false ? 'off' : 'on'}" data-pyric-sandbox>`;
1025
+ // Sandbox BUILD: the app's own `firebase/*` imports were already swapped
1026
+ // (resolveId, above) to pyric's in-page adapters and BUNDLED into the app
1027
+ // chunk, and the emitted init chunk (script-tagged here) carries the
1028
+ // runtime bootstrap + the ServeAuthHelper popup picker — rollup shares
1029
+ // ONE runtime module between the two, so the output is fully
1030
+ // self-contained. `pyric dev` sees the marker below and skips its own
1031
+ // serve-time injection for this page (a second injected runtime would
1032
+ // double-init: two banners, two bridge peers). The marker is also the
1033
+ // signal that makes `pyric dev` trust this dist (skip the inlined-SDK
1034
+ // scan). transformIndexHtml runs BEFORE Vite writes index.html, so both
1035
+ // land in the emitted asset.
1036
+ if (sandboxBuild) {
1037
+ if (html.includes(SANDBOX_BUILD_META)) return html;
1038
+ const initTag = initChunkFile
1039
+ ? `<script type="module" crossorigin src="/${initChunkFile}" data-pyric-sandbox-init></script>`
1040
+ : '';
1041
+ const tags = SANDBOX_BUILD_META + runtimeChipTag + initTag;
1042
+ return html.includes('</head>')
1043
+ ? html.replace('</head>', `${tags}</head>`)
1044
+ : tags + html;
1045
+ }
1046
+ const MARKER = 'data-pyric-sandbox';
1047
+ if (html.includes(MARKER)) return html;
1048
+ // Worker path (default): stamp the served worker's content hash so the page
1049
+ // can WARN when a still-running OLD worker is stale (a SharedWorker can't
1050
+ // hot-update). In-page path: force it via the explicit flag before the init
1051
+ // module evaluates — a classic inline script runs before the deferred module.
1052
+ // The flag (not nulling `window.SharedWorker`) leaves the user's own
1053
+ // SharedWorker usage intact. We force in-page ONLY when the worker bundle
1054
+ // failed (worker runtime unready) — the ephemeral fallback. `bridge` no longer
1055
+ // forces in-page: the bridge peer routes agent tool-calls THROUGH the
1056
+ // worker (see `connectBridgePeer`), so the agent shares the one sandbox the
1057
+ // app + Studio use.
1058
+ const head = workerRuntime.headTag(MARKER);
1059
+ // Plugin-level engine for the IN-PAGE path: a classic inline script runs
1060
+ // before the deferred init module AND before app code's `getAI`, so the
1061
+ // served `getAI` (entries/ai.ts) reads it synchronously — init.json can't
1062
+ // be awaited there. Harmless on the worker path (that branch ignores the
1063
+ // global; the worker reads ctx.aiEngine from init.json). `<` is escaped so
1064
+ // an engine value can never break out of the script tag.
1065
+ const aiEngineTag = resolvedAi.engineWire
1066
+ ? `<script ${MARKER}>globalThis.__PYRIC_AI_ENGINE__=${JSON.stringify(resolvedAi.engineWire).replace(/</g, '\\u003c')};</script>`
1067
+ : '';
1068
+ // Boot the sandbox by loading the real init entry as a module (Vite
1069
+ // serves + transforms it). The init module's top-level await deploys rules
1070
+ // before app code runs. Mirrors serve's injectServeTags.
1071
+ const tag = head + aiEngineTag + runtimeChipTag + `<script type="module" src="/@fs/${entries.init}" ${MARKER}></script>`;
1072
+ return html.includes('</head>') ? html.replace('</head>', `${tag}</head>`) : tag + html;
1073
+ },
1074
+ };
1075
+ }